ess.go 12 KB

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