ess.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package tencent
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "fmt"
  11. "mtp2_if/config"
  12. "mtp2_if/db"
  13. "mtp2_if/logger"
  14. "mtp2_if/models"
  15. "mtp2_if/services/tencent/essapi"
  16. "mtp2_if/utils"
  17. essbasic "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/essbasic/v20210526"
  18. )
  19. func CreateConsoleLoginUrl(agent *essbasic.Agent, proxyOrganizationName string) (response *essbasic.CreateConsoleLoginUrlResponse, err error) {
  20. response, err = essapi.CreateConsoleLoginUrl(agent, proxyOrganizationName)
  21. return
  22. }
  23. // InitTencentESS 按用户ID和机构ID创建腾讯电子签业务信息
  24. func InitTencentESS(userId, areaUserId int) (err error) {
  25. esignTemplateConfigs, err := models.QueryEsignTemplateConfigs(2, 4)
  26. if err != nil {
  27. return
  28. }
  29. session := db.GetEngine().NewSession()
  30. defer session.Close()
  31. // 开启事务
  32. session.Begin()
  33. // 新增 MdUserSwapProtocol
  34. err = models.InsertMdUserSwapProtocol(userId, areaUserId, 1, session)
  35. if err != nil {
  36. session.Rollback()
  37. return
  38. }
  39. // 新增 UserEsignRecord
  40. for _, item := range esignTemplateConfigs {
  41. err = models.InsertUserEsignRecord(userId, areaUserId, item, session)
  42. if err != nil {
  43. session.Rollback()
  44. return
  45. }
  46. }
  47. return session.Commit()
  48. }
  49. func InitMdUserSwapProtocol(userId, areaUserId int) (err error) {
  50. // 新增 MdUserSwapProtocol
  51. err = models.InsertMdUserSwapProtocol(userId, areaUserId, 3, db.GetEngine().NewSession())
  52. if err != nil {
  53. return
  54. }
  55. return
  56. }
  57. // CreateFlowByTemplateDirectly 通过合同模板创建合同签署流程
  58. func CreateFlowByTemplateDirectly(tmplateName string, userType int,
  59. personName, personMobile, personIdCardNumber string,
  60. organizationName string,
  61. record *models.Useresignrecord) (flowId, signUrl string, err error) {
  62. // 获取模板信息
  63. templateInfo, err := GetTemplateInfo(&tmplateName)
  64. if err != nil {
  65. return
  66. }
  67. if templateInfo == nil {
  68. err = fmt.Errorf("获取模板信息失败, tmplateName:%v", tmplateName)
  69. logger.GetLogger().Errorf("CreateFlowByTemplateDirectly, %v", err.Error())
  70. return
  71. }
  72. // 获取模板里面的参与方RecipientId
  73. recipients := templateInfo.Recipients
  74. if recipients == nil {
  75. err = fmt.Errorf("获取模板参与方信息失败, tmplateName:%v", tmplateName)
  76. logger.GetLogger().Errorf("CreateFlowByTemplateDirectly, %v", err.Error())
  77. return
  78. }
  79. // 此处为快速发起的签署方;如果是正式接入,构造签署方,请参考函数内说明,构造需要的场景参数
  80. var flowApproverInfos []*essbasic.FlowApproverInfo
  81. for i := range recipients {
  82. recipient := recipients[i]
  83. if config.SerCfg.TencentCfg.ProxyOrganizationName == *recipient.RoleName {
  84. if *recipient.SignType != 1 {
  85. // 签署方为本企业,同时不是自动签署时(一般为甲方非自动签署)
  86. flowApproverInfos = append(flowApproverInfos, buildSelfOrganizationApprovers(recipient)...)
  87. }
  88. } else {
  89. // 乙方
  90. if userType == 1 {
  91. // 个人
  92. flowApproverInfos = append(flowApproverInfos, buildPersonApprovers(personName, personMobile, personIdCardNumber, recipient)...)
  93. } else {
  94. // 企业
  95. flowApproverInfos = append(flowApproverInfos, buildOrganizationApprovers(organizationName, recipient)...)
  96. }
  97. }
  98. }
  99. // 发起合同
  100. resp, err := essapi.CreateFlowByTemplateDirectly(*templateInfo.TemplateName, *templateInfo.TemplateId, flowApproverInfos)
  101. if err != nil {
  102. return
  103. }
  104. if resp == nil || len(resp["flowIds"]) == 0 || len(resp["urls"]) == 0 {
  105. err = fmt.Errorf("发起合同签署流程失败, tmplateName:%v", tmplateName)
  106. logger.GetLogger().Errorf("CreateFlowByTemplateDirectly, %v", err.Error())
  107. return
  108. }
  109. if len(resp["flowIds"]) > 0 {
  110. flowId = *resp["flowIds"][0]
  111. }
  112. if len(resp["urls"]) > 0 {
  113. signUrl = *resp["urls"][0]
  114. }
  115. // 更新电子签记录表信息状态
  116. record.CONTRACTNO = flowId
  117. record.SIGNURL = signUrl
  118. record.RECORDSTATUS = 2
  119. if err = record.Update("CONTRACTNO,SIGNURL,RECORDSTATUS"); err != nil {
  120. logger.GetLogger().Errorf("CreateFlowByTemplateDirectly, %v", err.Error())
  121. }
  122. return
  123. }
  124. // GetFlowStatus 获取合同状态
  125. func GetFlowStatus(flowId string) (recordStatus int, err error) {
  126. agent := utils.SetAgent()
  127. response, err := essapi.DescribeFlowDetailInfo(agent, []*string{&flowId})
  128. if err == nil {
  129. if len(response.Response.FlowInfo) == 0 {
  130. err = fmt.Errorf("获取合同明细失败")
  131. return
  132. }
  133. flowDetailInfo := response.Response.FlowInfo[0]
  134. // 获取对应电子签信息
  135. var record *models.Useresignrecord
  136. record, err = models.GetUseresignRecordByFlowID(flowId)
  137. if err != nil {
  138. err = fmt.Errorf("获取电子签信息失败")
  139. return
  140. }
  141. // 更新电子签信息状态
  142. if *flowDetailInfo.FlowStatus == "ALL" {
  143. recordStatus = 3
  144. }
  145. if *flowDetailInfo.FlowStatus == "REJECT" {
  146. recordStatus = 4
  147. }
  148. if recordStatus == 0 {
  149. err = fmt.Errorf("合同状态异常")
  150. return
  151. }
  152. record.RECORDSTATUS = int32(recordStatus)
  153. if err = record.Update("RECORDSTATUS"); err != nil {
  154. logger.GetLogger().Errorf("GetFlowStatus, %v", err.Error())
  155. }
  156. if recordStatus == 3 {
  157. // 更新用户掉期协议签署表
  158. UpdateMdUserSwapProtocol(flowId)
  159. }
  160. }
  161. return
  162. }
  163. func UpdateMdUserSwapProtocol(flowId string) (err error) {
  164. // 获取对应的电子签记录
  165. var record *models.Useresignrecord
  166. record, err = models.GetUseresignRecordByFlowID(flowId)
  167. if err != nil {
  168. logger.GetLogger().Errorf("UpdateMdUserSwapProtocol, 获取对应的电子签记录失败:%v", err.Error())
  169. return
  170. }
  171. // 获取此用户对应机构的电子签记录列表
  172. records, err := models.QueryUsereSignRecords(int(record.USERID), int(record.AREAUSERID), nil, nil, nil)
  173. if err == nil {
  174. // 所有合同签署完成后,更新用户掉期协议签署表
  175. flag := true
  176. for _, item := range records {
  177. if item.RECORDSTATUS != 3 {
  178. flag = false
  179. break
  180. }
  181. }
  182. if flag {
  183. // 获取对应用户掉期协议签署记录
  184. var datas []models.Mduserswapprotocol
  185. datas, err = models.QueryMdUserSwapProtocol(int(record.USERID), &record.AREAUSERID)
  186. if err == nil {
  187. if len(datas) > 0 {
  188. data := datas[0]
  189. // 获取用户信息,如果是用户所属机构则改状态为 4:已审核,否则改为 3:已签署
  190. var userAccount *models.Useraccount
  191. if userAccount, err = models.GetUserAccount(int(record.USERID)); err == nil {
  192. status := 4
  193. if userAccount.Memberuserid != record.AREAUSERID {
  194. status = 3
  195. }
  196. data.PROTOCOLSTATUS = int32(status)
  197. err = data.Update("PROTOCOLSTATUS")
  198. }
  199. }
  200. } else {
  201. logger.GetLogger().Errorf("UpdateMdUserSwapProtocol, 获取对应用户掉期协议签署记录失败:%v", err.Error())
  202. }
  203. }
  204. } else {
  205. logger.GetLogger().Errorf("UpdateMdUserSwapProtocol, 获取对应的机构电子签记录失败:%v", err.Error())
  206. }
  207. return
  208. }
  209. // GetTemplateInfo 获取模板信息
  210. func GetTemplateInfo(contractName *string) (templateInfo *essbasic.TemplateInfo, err error) {
  211. agent := utils.SetAgent()
  212. templatesResp, err := essapi.DescribeTemplates(agent, contractName)
  213. if err == nil {
  214. if len(templatesResp.Response.Templates) > 0 {
  215. templateInfo = templatesResp.Response.Templates[0]
  216. } else {
  217. err = fmt.Errorf("获取模板信息失败")
  218. }
  219. }
  220. return
  221. }
  222. // buildPersonApprovers 构造个人签署人 - 以BtoC为例, 实际请根据自己的场景构造签署方、控件
  223. func buildPersonApprovers(personName, personMobile, personIdCardNumber string, recipient *essbasic.Recipient) []*essbasic.FlowApproverInfo {
  224. var flowApproverInfos []*essbasic.FlowApproverInfo
  225. // 传入个人签署方
  226. flowApproverInfo := &essbasic.FlowApproverInfo{}
  227. approverType := "PERSON"
  228. flowApproverInfo.ApproverType = &approverType
  229. flowApproverInfo.Name = &personName
  230. flowApproverInfo.Mobile = &personMobile
  231. flowApproverInfo.IdCardType = utils.SetPointValue("ID_CARD")
  232. flowApproverInfo.IdCardNumber = &personIdCardNumber
  233. // 模板中对应签署方的参与方id
  234. flowApproverInfo.RecipientId = recipient.RecipientId
  235. flowApproverInfos = append(flowApproverInfos, flowApproverInfo)
  236. // 传入企业静默签署,此处需要在config.php中设置一个持有的印章值serverSignSealId
  237. // flowApproverInfos = append(flowApproverInfos, BuildServerSignApprover())
  238. // 内容控件填充结构,详细说明参考
  239. // https://cloud.tencent.com/document/api/1420/61525#FormField
  240. return flowApproverInfos
  241. }
  242. // buildOrganizationApprovers 构造企业签署人
  243. func buildOrganizationApprovers(organizationName string, recipient *essbasic.Recipient) []*essbasic.FlowApproverInfo {
  244. var flowApproverInfos []*essbasic.FlowApproverInfo
  245. // 传入企业签署方
  246. flowApproverInfo := &essbasic.FlowApproverInfo{}
  247. approverType := "ORGANIZATION"
  248. flowApproverInfo.ApproverType = &approverType
  249. flowApproverInfo.OrganizationName = &organizationName
  250. // 模板中对应签署方的参与方id
  251. flowApproverInfo.RecipientId = recipient.RecipientId
  252. flowApproverInfos = append(flowApproverInfos, flowApproverInfo)
  253. return flowApproverInfos
  254. }
  255. // buildSelfOrganizationApprovers 构造本企业签署人
  256. func buildSelfOrganizationApprovers(recipient *essbasic.Recipient) []*essbasic.FlowApproverInfo {
  257. var flowApproverInfos []*essbasic.FlowApproverInfo
  258. // 传入企业签署方
  259. flowApproverInfo := &essbasic.FlowApproverInfo{}
  260. approverType := "ORGANIZATION"
  261. flowApproverInfo.ApproverType = &approverType
  262. flowApproverInfo.OrganizationOpenId = &config.SerCfg.TencentCfg.ProxyOrganizationOpenId // 本企业OpenID
  263. // 模板中对应签署方的参与方id
  264. flowApproverInfo.RecipientId = recipient.RecipientId
  265. flowApproverInfo.OpenId = &config.SerCfg.TencentCfg.ProxyOperatorOpenId // 本企业员工OpenID
  266. flowApproverInfos = append(flowApproverInfos, flowApproverInfo)
  267. return flowApproverInfos
  268. }
  269. func ProcessNotice(content string) {
  270. // "{\"MsgId\":\"yDSLWUUckposmdf8UBxiJvuDbgiYRYbj\",\"MsgType\":\"FlowStatusChange\",\"MsgVersion\":\"ThirdPartyApp\",\"MsgData\":{\"ApplicationId\":\"yDwiuUUckpogfoa4UxhigrYChFMdSJQV\",\"ProxyOrganizationOpenId\":\"TJMD\",\"CustomerData\":\"\",\"FlowId\":\"yDSLWUUckposcsthUwvcaGSuV5EKZAzu\",\"FlowName\":\"1000_P_风险揭示书\",\"FlowType\":\"合同\",\"FlowStatus\":\"INIT\",\"FlowMessage\":\"\",\"CreateOn\":1699077064,\"Deadline\":1730613064,\"FlowApproverInfo\":[{\"ProxyOrganizationOpenId\":\"\",\"ProxyOperatorOpenId\":\"\",\"recipientId\":\"yDSLNUUckpos1i71UuGNih5yMGbZij46\",\"RecipientId\":\"yDSLNUUckpos1i71UuGNih5yMGbZij46\",\"PhoneNumber\":\"15914012152\",\"ProxyOrganizationName\":\"\",\"SignOrder\":0,\"ApproveName\":\"曹晓亮\",\"ApproveStatus\":\"PENDING\",\"ApproveMessage\":\"\",\"ApproveTime\":0,\"CaSign\":\"\"}],\"OccurTime\":1699077064,\"CcInfo\":[]}}"
  271. m := make(map[string]interface{})
  272. if err := json.Unmarshal([]byte(content), &m); err == nil {
  273. // 判断通知类型
  274. msgType, _ := m["MsgType"].(string)
  275. if msgType == "FlowStatusChange" {
  276. // 合同相关回调
  277. // https://qian.tencent.com/developers/partner/callback_types_contracts_sign
  278. msgData, _ := m["MsgData"].(map[string]interface{})
  279. flowId, _ := msgData["FlowId"].(string)
  280. flowStatus, _ := msgData["FlowStatus"].(string)
  281. if flowStatus == "ALL" || flowStatus == "REJECT" {
  282. // 更新电子签合同状态
  283. if record, err := models.GetUseresignRecordByFlowID(flowId); err == nil {
  284. if flowStatus == "ALL" {
  285. record.RECORDSTATUS = 3
  286. } else {
  287. record.RECORDSTATUS = 4
  288. }
  289. if err = record.Update("RECORDSTATUS"); err != nil {
  290. logger.GetLogger().Errorf("ProcessNotice, %v", err.Error())
  291. }
  292. if record.RECORDSTATUS == 3 {
  293. // 更新用户掉期协议签署表
  294. UpdateMdUserSwapProtocol(flowId)
  295. }
  296. }
  297. }
  298. }
  299. }
  300. }
  301. // VerifySign 电子签通知推送验签
  302. func VerifySign(payload, signFromHeader string) bool {
  303. // 验证签名
  304. hash := "sha256=" + hmacsha256hex(payload, config.SerCfg.TencentCfg.SignToken)
  305. return hash == signFromHeader
  306. }
  307. // DecryptContent 电子签通知推送内容解密
  308. func DecryptContent(payload string) (content string, err error) {
  309. // string -> json
  310. m := make(map[string]string)
  311. err = json.Unmarshal([]byte(payload), &m)
  312. if err != nil {
  313. return
  314. }
  315. encrypt, ok := m["encrypt"]
  316. if !ok {
  317. err = fmt.Errorf("电子签通知推送内容解密失败")
  318. logger.GetLogger().Errorf("DecryptContent, %v", err.Error())
  319. return
  320. }
  321. // base64解密
  322. crypted, err := base64.StdEncoding.DecodeString(encrypt)
  323. if err != nil {
  324. logger.GetLogger().Errorf("base64 DecodeString returned: %s", err)
  325. return
  326. }
  327. b, err := aesDecrypt(crypted, []byte(config.SerCfg.TencentCfg.SignKey))
  328. if err != nil {
  329. logger.GetLogger().Errorf("AesDecrypt returned: %s", err)
  330. return
  331. }
  332. content = string(b)
  333. return
  334. }
  335. // Hmacsha256hex hmac sha256
  336. func hmacsha256hex(s, key string) string {
  337. hashed := hmac.New(sha256.New, []byte(key))
  338. hashed.Write([]byte(s))
  339. return hex.EncodeToString(hashed.Sum(nil))
  340. }
  341. // 使用callbackKey解密
  342. func aesDecrypt(crypted, key []byte) ([]byte, error) {
  343. block, err := aes.NewCipher(key)
  344. if err != nil {
  345. return nil, err
  346. }
  347. blockSize := block.BlockSize()
  348. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  349. origData := make([]byte, len(crypted))
  350. blockMode.CryptBlocks(origData, crypted)
  351. origData = pkcs7UnPadding(origData)
  352. return origData, nil
  353. }
  354. // PKCS7UnPadding 去除填充
  355. func pkcs7UnPadding(origData []byte) []byte {
  356. length := len(origData)
  357. unPadding := int(origData[length-1])
  358. return origData[:(length - unPadding)]
  359. }