ess.go 14 KB

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