e签宝 SaaS V3 API 接入:Kotlin 项目对接流程模板签署
项目要接电子签,选的是 e签宝 SaaS V3 版。官方给了个 Java demo,但我们是 Kotlin 项目,直接拷进来会有一堆编译设置要调。
这篇记录从建模板到拿到签署链接、再到接收回调的完整链路。
参考文档:
官方 demo 里 cn.tsign.hz 包下都是封装好的方法(签名、HTTP 调用、加密验签),全部拷到自己项目里即可。
一、Kotlin 项目要先开 Java 编译
这是第一个坑:demo 是 Java 写的,放进 Kotlin 项目的 src/main/kotlin 下,如果没配 Java 源码目录,.java 文件根本不会被编译。

Gradle 里补上这段:

subprojects {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
sourceSets.main.kotlin.srcDirs('src/main/kotlin')
sourceSets.main.java.srcDirs('src/main/kotlin') // 关键:让 Java 编译器也扫 kotlin 目录
}
sourceSets.main.java.srcDirs 这一行是关键 —— 让 javac 也去扫 src/main/kotlin,混合编译才成立。
二、配置
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "esign")
data class EsignConfig(
// 应用ID
var appId: String = "",
// 应用密钥
var appSecret: String = "",
// e签宝接口调用域名
var host: String = "",
// 模板ID
var templateId: String = "",
// orgId正式账号和沙箱账号不一样
var orgId: String = "",
//回调 ip白名单
var callBackWhiteIp: String = "",
//回调地址
var callBackUrl: String = ""
)
esign:
appId: "7439****"
appSecret: "***********************"
host: "https://smlopenapi.esign.cn"
templateId: "*************************"
orgId: "*************************"
callBackWhiteIp: "47.**.**.**" #官方回调ip
callBackUrl: "xxxxx/esign/eSignCallback"
注意 orgId 正式账号和沙箱账号不一样,切环境时这个最容易漏,报的错还是「模板不存在」,会往模板方向查半天。
host 这里写的是沙箱 smlopenapi.esign.cn;生产是 openapi.esign.cn。
三、请求实体
整个 CreateSignFlowByTemplateRequest 有三百多行,覆盖了流程配置、参与方、抄送、附件、控件预填。主体结构:
package com.example.server.v2.esign.entity
/**
* 通过流程模板创建合同拟定和签署流程 - 请求参数实体
* 接口地址:POST /v3/sign-flow/create-by-sign-template
*/
data class CreateSignFlowByTemplateRequest(
// 流程模板ID
val signTemplateId: String,
// 签署流程配置项
val signFlowConfig: SignFlowConfig,
// 发起方信息(指在平台中发起合同签约的一方,合同的归属方)
val signFlowInitiator: SignFlowInitiator? = null,
// 合同备注信息(显示到签署页面的任务详情信息里)
// 目前最多支持1条备注,最多300个字符
val initialRemarks: List<String>? = null,
// 参与方信息
// 如果模板设置页面的参与方配置为:使用模板时指定 和 固定企业 时,则此参数必传
// 如果模板设置页面的参与方配置为:固定成员 和 发起人本人 时,则此参数不要指定
val participants: List<Participant>? = null,
// 添加抄送方
val addCopiers: List<AddCopier>? = null,
// 添加合同附件信息(指无需签名的文件,仅用于查看)
val addAttachments: List<AddAttachment>? = null,
// 控件列表(用于模板控件的开发者预填内容)
val components: List<Component>? = null
)
SignFlowConfig 里的关键字段:
data class SignFlowConfig(
// 签署任务主题
// 主题名称不可含有以下9个特殊字符:/ \ : * " < > | ?以及所有emoji表情
val signFlowTitle: String,
// 签署截止时间(Unix时间戳格式,单位:毫秒)
// 默认在签署流程开启后的90天时截止
val signFlowExpireTime: Long? = null,
// 合同拟定完成后是否自动开启签署流程,默认值 true
val autoStart: Boolean? = null,
// ...
)
配套的还有 SignConfig、NoticeConfig、AuthConfig、ContractConfig,以及参与方三件套 Participant / OrgParticipant / PsnParticipant。
另外两个接口的请求体(GetDraftUrlRequest、GetSignUrlRequest)和模板详情响应体(TemplateDetailResponse,包含 Doc / TemplateParticipant / TemplateComponent / ComponentPosition 等十几个嵌套类)结构类似,都是照着官方文档一个个字段抄的,这里不重复贴了。
四、Controller:六个接口串起主流程
package com.example.server.v2.esign.controller
import com.example.server.v2.controller.APIConstant
import com.example.server.v2.controller.APIController
import com.example.server.v2.esign.comm.EsignEncryption
import com.example.server.v2.esign.comm.EsignHttpHelper
import com.example.server.v2.esign.comm.EsignHttpResponse
import com.example.server.v2.esign.constant.EsignConfig
import com.example.server.v2.esign.entity.*
import com.example.server.v2.esign.enums.EsignRequestType
import com.example.server.v2.wd.util.CommonUtil
import com.alibaba.fastjson.JSON
import com.example.common.net.getRealIp
import com.example.common.response.GenericResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Async
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@RestController
@RequestMapping(APIConstant.DASHBOARD_ESIGN_URL)
class EsignController: APIController() {
val logger = CommonUtil.getLogger(this::class.java)
@Autowired
private lateinit var esignConfig: EsignConfig
private fun eSignRequestHelper(url:String, jsonParam: String,requestType:EsignRequestType): EsignHttpResponse {
//请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
//生成签名鉴权方式的的header
val header = EsignHttpHelper.signAndBuildSignAndJsonHeader(
esignConfig.appId,
esignConfig.appSecret,
jsonParam,
requestType.name,
url,
true
)
val result = EsignHttpHelper.doCommHttp(esignConfig.host, url, requestType, jsonParam, header, true)
return result
}
/**
* 查询流程模板详情
* 查询企业用户下某一个流程模板的详情,以便开发者确认模板的文件信息、参与人信息以及控件信息等。
* 接口地址: GET /v3/sign-templates/detail
*/
@GetMapping("/getTemplatesDetail")
fun getTemplatesDetail():GenericResponse<Any?> {
authService.mustAdmin()
val url = "/v3/sign-templates/detail?orgId=" + esignConfig.orgId + "&queryComponents=true&signTemplateId=" + esignConfig.templateId
val result = eSignRequestHelper(url,"", EsignRequestType.GET)
val resultJson = JSON.parseObject(result.body, TemplateDetailResponse::class.java)
return GenericResponse(code = HttpServletResponse.SC_OK, message = "调用结果", items = resultJson)
}
/**
* 通过流程模板创建合同拟定和签署流程
* 使用signTemplateId(流程模板ID)发起合同的拟定(用户填写)和签署流程
* 接口地址: POST /v3/sign-flow/create-by-sign-template
*/
@GetMapping("/createBySignTemplate")
fun createBySignTemplate(): GenericResponse<Any?> {
authService.mustAdmin()
//请求参数body体,json格式。get或者delete请求时jsonString传空json:"{}"或者null
val DAY_IN_MILLIS = 24L * 60 * 60 * 1000
val request = CreateSignFlowByTemplateRequest(
signTemplateId = esignConfig.templateId,
signFlowConfig = SignFlowConfig(
signFlowTitle = "合同签订测试",
signFlowExpireTime = System.currentTimeMillis() + 90 * DAY_IN_MILLIS,
//这里设置自动开启就不用后面的start方法了
autoStart = true,
autoFinish = true,
notifyUrl = esignConfig.callBackUrl,
signConfig = SignConfig(
availableSignClientTypes = "1",
autoFillAndSubmit = true,
editComponentValue = false
),
noticeConfig = NoticeConfig(
// noticeTypes = "1" // 短信和邮件通知
),
authConfig = AuthConfig(
psnAvailableAuthModes = listOf(PsnAuthMode.MOBILE3, PsnAuthMode.FACE),
orgAvailableAuthModes = listOf(OrgAuthMode.BANK_TRANSFER, OrgAuthMode.LEGALREP)
)
),
participants = listOf(
Participant(
participantId = "f17437*****495b1c13d5d6",
orgParticipant = OrgParticipant(
orgName = "***媒体",
transactor = OrgParticipantTransactor(
transactorPsnAccount = "131****1254",
transactorName = "张*"
)
)
),
Participant(
participantId = "1847fb*****7bc611f102038b",
psnParticipant = PsnParticipant(
psnAccount = "131****1254",
psnName = "张*"
)
)
),
components = listOf(
// Component(
// fileId = "b68a****12fg",
// componentId = "dfdb9d7b84ba111112dd922ded7",
// componentValue = "1000000.00"
// ),
Component(
fileId = "28cfd9******4d0b92f7a2c963",
componentId = "b93221******9bd1e401dc8716147",
componentValue = "xxxx科技公司"
),
// Component(
// fileId = "28cfd96958574eb18e4d0b92f7a2c963",
// componentKey = "5eaff98ff3184cd0bfb235fee55f6ff6",
// componentValue = "企业用章"
// ),
// Component(
// fileId = "28cfd96958574eb18e4d0b92f7a2c963",
// componentKey = "partBSeal",
// componentValue = "测试个人印章"
// ),
// Component(
// fileId = "28cfd96958574eb18e4d0b92f7a2c963",
// componentKey = "partBSignTime",
// componentValue = LocalDateTime.now().format(format)
// )
)
)
val url = "/v3/sign-flow/create-by-sign-template"
val jsonParam = JSON.toJSONString(request)
val result = eSignRequestHelper(url,jsonParam, EsignRequestType.POST)
//发起接口请求
val detailResponse = JSON.parseObject(result.body)
if(detailResponse.get("signFlowId") != null){
return GenericResponse(code = HttpServletResponse.SC_OK, message = "调用结果", items = detailResponse.get("signFlowId"))
}else{
return GenericResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "调用结果", items = detailResponse)
}
}
/**
* 获取填写页面链接
* 通过signFlowId(签署流程ID )获取用户的合同拟定页面链接
* 接口地址: POST /v3/sign-flow/{signFlowId}/draft-url
*/
@PostMapping("/getDraftUrl/{signFlowId}")
fun getDraftUrl(
@PathVariable("signFlowId") signFlowId: String,
@RequestBody request: GetDraftUrlRequest
): GenericResponse<Any?> {
authService.mustAdmin()
// 构建请求体参数(只包含operator、needLogin、urlType、clientType、redirectConfig)
val bodyRequest = GetDraftUrlRequest(
operator = request.operator,
needLogin = request.needLogin,
urlType = request.urlType,
clientType = request.clientType,
redirectConfig = request.redirectConfig
)
val url = "/v3/sign-flow/create-by-sign-template"
val jsonParam = JSON.toJSONString(bodyRequest)
val result = eSignRequestHelper(url,jsonParam, EsignRequestType.POST)
return GenericResponse(
code = HttpServletResponse.SC_OK,
message = "调用结果",
items = result
)
}
/**
* 开启签署流程
* 签署流程开启之后,签署任务会按照流程既定配置开始执行(通知相关签署人开始签署等),签署流程此时为“签署中”状态。
* 接口地址: POST /v3/sign-flow/{signFlowId}/start
*
* 注意!! 如果create-by-sign-template参数设置autoStart=true自动开启就不用该start方法了
*/
@PostMapping("/signFlowStart/{signFlowId}")
fun signFlowStart(
@PathVariable("signFlowId") signFlowId: String,
): GenericResponse<Any?> {
authService.mustAdmin()
val url = "/v3/sign-flow/${signFlowId}/start"
val result = eSignRequestHelper(url,"", EsignRequestType.POST)
return GenericResponse(
code = HttpServletResponse.SC_OK,
message = "调用结果",
items = result
)
}
/**
* 获取签署页面链接
* 签署流程开启后,才可以获取到文件的签署链接。
* 接口地址: POST /v3/sign-flow/{signFlowId}/sign-url
*/
@PostMapping("/getSignUrl/{signFlowId}")
fun getSignUrl(
@PathVariable("signFlowId") signFlowId: String,
@RequestBody request: GetSignUrlRequest
): GenericResponse<Any?> {
authService.mustAdmin()
// 构建请求体参数
val bodyRequest = GetSignUrlRequest(
operator = request.operator,
needLogin = request.needLogin,
urlType = request.urlType,
clientType = request.clientType,
redirectConfig = request.redirectConfig,
organization = request.organization,
appScheme = request.appScheme
)
val url = "/v3/sign-flow/$signFlowId/sign-url"
val jsonParam = JSON.toJSONString(bodyRequest)
val result = eSignRequestHelper(url,jsonParam, EsignRequestType.POST)
return GenericResponse(
code = HttpServletResponse.SC_OK,
message = "调用结果",
items = result
)
}
/**
* 查询合同拟定和签署流程状态
* 查询流程的具体状态(包含合同拟定状态和签署状态)
* 接口地址: GET /v3/sign-flow/{signFlowId}/status
*
* @param signFlowId 签署流程ID
* @return 返回流程状态信息,包含draftStatus(合同拟定状态)、signFlowStatus(签署流程状态)、rescissionStatus(解约状态)
*/
@GetMapping("/signFlowStatus/{signFlowId}")
fun querySignFlowStatus(
@PathVariable("signFlowId") signFlowId: String,
): GenericResponse<Any?> {
authService.mustAdmin()
val url = "/v3/sign-flow/${signFlowId}/status"
val result = eSignRequestHelper(url,"", EsignRequestType.GET)
return GenericResponse(
code = HttpServletResponse.SC_OK,
message = "调用结果",
items = result
)
}
/**
* 下载已签署文件及附属材料
* 流程结束后,获取签署完成的文件以及相关附属材料的下载链接。
* 未签署完成的流程,无法下载相关文件,否则会报错:"流程非签署完成状态,不允许下载文档"。
* 接口地址: POST /v3/sign-flow/{signFlowId}/file-download-url
*
* 注意!! 如果create-by-sign-template参数设置autoStart=true自动开启就不用该start方法了
*/
@PostMapping("/signFlowFileDownload/{signFlowId}")
fun signFlowFileDownload(
@PathVariable("signFlowId") signFlowId: String,
): GenericResponse<Any?> {
authService.mustAdmin()
val url = "/v3/sign-flow/${signFlowId}/file-download-url"
// 请求方法
val result = eSignRequestHelper(url,"", EsignRequestType.POST)
return GenericResponse(
code = HttpServletResponse.SC_OK,
message = "调用结果",
items = result
)
}
/**
* e签宝回调验签
* 只能是回调的IP是白名单的IP
* 调用验签通过才走更新
*/
@PostMapping("/eSignCallback")
fun callBackCheck(
request: HttpServletRequest,
@RequestBody body: String
): GenericResponse<Any?> {
var ip=request.getRealIp()
if(ip!=esignConfig.callBackWhiteIp){
logger.info("回调ip非法: $ip")
return GenericResponse(HttpServletResponse.SC_BAD_REQUEST, "", "failure")
}
try {
// 1. 从请求头获取验签所需参数
val timestamp = request.getHeader("X-Tsign-Open-TIMESTAMP")
val signature = request.getHeader("X-Tsign-Open-SIGNATURE")
val appId = request.getHeader("X-Tsign-Open-App-Id")
// 2. 处理Query参数:按key字典序排序后拼接value
val queryString = request.queryString
val processedQuery = processQueryString(queryString)
// 3. 根据appId获取对应的AppSecret
val appSecret = esignConfig.appSecret
// 4. 调用封装好的验签方法
val isValid = EsignEncryption.callBackCheck(
timestamp,
processedQuery,
body,
appSecret,
signature
)
if (!isValid) {
logger.warn("回调验签失败-appId: $appId")
return GenericResponse(HttpServletResponse.SC_BAD_REQUEST, "", "failure")
}
logger.info("回调验签成功-回调结果: $body")
// 5. 验签成功,异步处理业务
asyncHandleCallback(body)
// 6. 返回成功
return GenericResponse(HttpServletResponse.SC_OK, "", "success")
} catch (e: Exception) {
logger.error("回调处理异常", e)
return GenericResponse(HttpServletResponse.SC_BAD_REQUEST, "", "failure")
}
}
/**
* 处理Query字符串:按key字典序排序后拼接value
*/
private fun processQueryString(queryString: String?): String {
if (queryString.isNullOrBlank()) return ""
val params = queryString.split("&")
.mapNotNull { pair ->
val parts = pair.split("=", limit = 2)
if (parts.size == 2) parts[0] to parts[1] else null
}
.sortedBy { it.first }
.map { it.second }
return params.joinToString("")
}
/**
* 异步处理回调业务
*/
@Async
fun asyncHandleCallback(body: String) {
// 处理业务逻辑
println("待实现的回调业务逻辑---")
}
}
五、整体流程串一下
大体流程:登录 e签宝 → 创建模板 → 拿到模板 ID 和 orgId。
调用顺序:
-
查询模板详情
/v3/sign-templates/detail?orgId=xxx&queryComponents=true&signTemplateId=xxx把模板里的文件信息、参与人、控件 ID 全捞出来,对照网页上的模板,选需要预填的控件 ID。 -
创建签署流程
POST /v3/sign-flow/create-by-sign-template把templateId+ 参与方 + 控件预填值拼进去,成功返回signFlowId。 -
拿链接,两条路:

- 方式一 —— e签宝自己发:第 2 步创建时把
noticeTypes=1打开,e签宝通过短信把签署链接直接发到用户手机,用户点链接就能签,我们不用管。 - 方式二 —— 自己集成:调
POST /v3/sign-flow/{signFlowId}/draft-url拿到填写页面链接,塞进自己业务系统里。
方式二拿到的是「合同拟定」页面(PDF 预览 + 填内容),用户填完还需要再开启流程:
-
开启签署流程
POST /v3/sign-flow/{signFlowId}/start如果在第 2 步设了autoStart = true,这一步可以跳过。 -
获取签署页面链接
POST /v3/sign-flow/{signFlowId}/sign-url流程开启后才有签署链接。 -
回调 + 下载:签完 e签宝回调到
callBackUrl,验签通过后调POST /v3/sign-flow/{signFlowId}/file-download-url下载已签文件。
微信小程序集成的官方参考:e签宝开放平台 - 案例。最后一节有一张官方截图说明小程序侧的接入方式。
六、几个要注意的点
getDraftUrl 里 URL 写错了
上面代码里 getDraftUrl 方法内 val url = "/v3/sign-flow/create-by-sign-template" —— 这是复制粘贴留下的,draft-url 接口的正确地址是 /v3/sign-flow/{signFlowId}/draft-url。原样贴出来提醒一下,别照抄。
autoStart = true 和手动 start 只能选一个
设了自动开启又调 /start,e签宝会返回「流程已开启」之类的错误。同理 autoFinish。
回调验签的 Query 参数要按 key 排序拼 value
processQueryString 这段不能省。e签宝的签名算法是「query 参数按 key 字典序排序后,把 value 直接拼起来」(不带 & 和 =),顺序错了签名必失败。
回调 IP 白名单
callBackWhiteIp 是 e签宝官方的回调出口 IP,不是自己的。上线前要跟官方确认当前出口 IP 有没有变,他们换过一次。
mustAdmin() 这种鉴权别直接暴露给前端
demo 里这些接口都是 @GetMapping 且只做了 admin 校验。实际项目里「创建签署流程」这类写操作用 POST,并且要带业务单号做幂等 —— 用户点两次会创建两个签署流程,两个 signFlowId 都得处理。
沙箱和生产两套 orgId
开头说过,orgId 沙箱和正式不同,host 也不同。建议配置里直接分环境写死,别用同一个变量名靠 profile 覆盖,容易覆盖错。
评论 · 讨论
评论由 GitHub Discussions 承载 · 去讨论区留言 →