wechat_service_api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package gopay
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/sha256"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "encoding/xml"
  13. "errors"
  14. "github.com/parnurzeal/gorequest"
  15. "io/ioutil"
  16. "net/http"
  17. "reflect"
  18. "strings"
  19. )
  20. //解析微信支付异步通知的结果到BodyMap
  21. // req:*http.Request
  22. // 返回参数bm:Notify请求的参数
  23. // 返回参数err:错误信息
  24. func ParseWeChatNotifyResultToBodyMap(req *http.Request) (bm BodyMap, err error) {
  25. bs, err := ioutil.ReadAll(req.Body)
  26. defer req.Body.Close()
  27. if err != nil {
  28. return nil, err
  29. }
  30. //获取Notify请求参数
  31. bm = make(BodyMap)
  32. err = xml.Unmarshal(bs, &bm)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return
  37. }
  38. //通过BodyMap验证微信支付异步通知的Sign值
  39. // apiKey:API秘钥值
  40. // signType:签名类型 MD5 或 HMAC-SHA256(默认请填写 MD5)
  41. // bm:通过 gopay.ParseWeChatNotifyResult() 得到的BodyMap
  42. // 返回参数ok:是否验证通过
  43. // 返回参数sign:计算出的sign值,非微信返回参数中的Sign
  44. func VerifyWeChatResultSignByBodyMap(apiKey string, signType string, bm BodyMap) (ok bool, sign string) {
  45. //验证Sign值的BodyMap
  46. bmNew := make(BodyMap)
  47. for key := range bm {
  48. if key != "sign" {
  49. vStr := bm.Get(key)
  50. bmNew.Set(key, vStr)
  51. }
  52. }
  53. //验证Sign值
  54. sign = getLocalSign(apiKey, signType, bmNew)
  55. ok = sign == bm.Get("sign")
  56. return
  57. }
  58. //解析微信支付异步通知的参数
  59. // req:*http.Request
  60. // 返回参数notifyReq:Notify请求的参数
  61. // 返回参数err:错误信息
  62. func ParseWeChatNotifyResult(req *http.Request) (notifyReq *WeChatNotifyRequest, err error) {
  63. notifyReq = new(WeChatNotifyRequest)
  64. defer req.Body.Close()
  65. err = xml.NewDecoder(req.Body).Decode(notifyReq)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return
  70. }
  71. //验证微信支付异步通知的Sign值
  72. // apiKey:API秘钥值
  73. // signType:签名类型 MD5 或 HMAC-SHA256(默认请填写 MD5)
  74. // notifyReq:利用 gopay.ParseWeChatNotifyResult() 得到的结构体
  75. // 返回参数ok:是否验证通过
  76. // 返回参数sign:根据参数计算的sign值,非微信返回参数中的Sign
  77. func VerifyWeChatResultSign(apiKey string, signType string, notifyReq *WeChatNotifyRequest) (ok bool, sign string) {
  78. body := make(BodyMap)
  79. body.Set("return_code", notifyReq.ReturnCode)
  80. body.Set("return_msg", notifyReq.ReturnMsg)
  81. body.Set("appid", notifyReq.Appid)
  82. body.Set("mch_id", notifyReq.MchId)
  83. body.Set("device_info", notifyReq.DeviceInfo)
  84. body.Set("nonce_str", notifyReq.NonceStr)
  85. body.Set("sign_type", notifyReq.SignType)
  86. body.Set("result_code", notifyReq.ResultCode)
  87. body.Set("err_code", notifyReq.ErrCode)
  88. body.Set("err_code_des", notifyReq.ErrCodeDes)
  89. body.Set("openid", notifyReq.Openid)
  90. body.Set("is_subscribe", notifyReq.IsSubscribe)
  91. body.Set("trade_type", notifyReq.TradeType)
  92. body.Set("bank_type", notifyReq.BankType)
  93. body.Set("total_fee", notifyReq.TotalFee)
  94. body.Set("settlement_total_fee", notifyReq.SettlementTotalFee)
  95. body.Set("fee_type", notifyReq.FeeType)
  96. body.Set("cash_fee", notifyReq.CashFee)
  97. body.Set("cash_fee_type", notifyReq.CashFeeType)
  98. body.Set("coupon_fee", notifyReq.CouponFee)
  99. body.Set("coupon_count", notifyReq.CouponCount)
  100. body.Set("coupon_type_0", notifyReq.CouponType0)
  101. body.Set("coupon_type_1", notifyReq.CouponType1)
  102. body.Set("coupon_id_0", notifyReq.CouponId0)
  103. body.Set("coupon_id_1", notifyReq.CouponId1)
  104. body.Set("coupon_fee_0", notifyReq.CouponFee0)
  105. body.Set("coupon_fee_1", notifyReq.CouponFee1)
  106. body.Set("transaction_id", notifyReq.TransactionId)
  107. body.Set("out_trade_no", notifyReq.OutTradeNo)
  108. body.Set("attach", notifyReq.Attach)
  109. body.Set("time_end", notifyReq.TimeEnd)
  110. newBody := make(BodyMap)
  111. for key := range body {
  112. vStr := body.Get(key)
  113. if vStr != null && vStr != "0" {
  114. newBody.Set(key, vStr)
  115. }
  116. }
  117. sign = getLocalSign(apiKey, signType, newBody)
  118. ok = sign == notifyReq.Sign
  119. return
  120. }
  121. type WeChatNotifyResponse struct {
  122. ReturnCode string `xml:"return_code"`
  123. ReturnMsg string `xml:"return_msg"`
  124. }
  125. //返回数据给微信
  126. func (this *WeChatNotifyResponse) ToXmlString() (xmlStr string) {
  127. buffer := new(bytes.Buffer)
  128. buffer.WriteString("<xml><return_code><![CDATA[")
  129. buffer.WriteString(this.ReturnCode)
  130. buffer.WriteString("]]></return_code>")
  131. buffer.WriteString("<return_msg><![CDATA[")
  132. buffer.WriteString(this.ReturnMsg)
  133. buffer.WriteString("]]></return_msg></xml>")
  134. xmlStr = buffer.String()
  135. return
  136. }
  137. //JSAPI支付,统一下单获取支付参数后,再次计算出小程序用的paySign
  138. // appId:APPID
  139. // nonceStr:随即字符串
  140. // prepayId:统一下单成功后得到的值
  141. // signType:签名类型
  142. // timeStamp:时间
  143. // apiKey:API秘钥值
  144. //
  145. // 微信小程序支付API:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
  146. func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
  147. buffer := new(bytes.Buffer)
  148. buffer.WriteString("appId=")
  149. buffer.WriteString(appId)
  150. buffer.WriteString("&nonceStr=")
  151. buffer.WriteString(nonceStr)
  152. buffer.WriteString("&package=")
  153. buffer.WriteString(prepayId)
  154. buffer.WriteString("&signType=")
  155. buffer.WriteString(signType)
  156. buffer.WriteString("&timeStamp=")
  157. buffer.WriteString(timeStamp)
  158. buffer.WriteString("&key=")
  159. buffer.WriteString(apiKey)
  160. signStr := buffer.String()
  161. var hashSign []byte
  162. if signType == SignType_HMAC_SHA256 {
  163. hash := hmac.New(sha256.New, []byte(apiKey))
  164. hash.Write([]byte(signStr))
  165. hashSign = hash.Sum(nil)
  166. } else {
  167. hash := md5.New()
  168. hash.Write([]byte(signStr))
  169. hashSign = hash.Sum(nil)
  170. }
  171. paySign = strings.ToUpper(hex.EncodeToString(hashSign))
  172. return
  173. }
  174. //微信内H5支付,统一下单获取支付参数后,再次计算出微信内H5支付需要用的paySign
  175. // appId:APPID
  176. // nonceStr:随即字符串
  177. // prepayId:统一下单成功后得到的值
  178. // signType:签名类型
  179. // timeStamp:时间
  180. // apiKey:API秘钥值
  181. //
  182. // 微信内H5支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/external/jsapi.php?chapter=7_7&index=6
  183. func GetH5PaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
  184. buffer := new(bytes.Buffer)
  185. buffer.WriteString("appId=")
  186. buffer.WriteString(appId)
  187. buffer.WriteString("&nonceStr=")
  188. buffer.WriteString(nonceStr)
  189. buffer.WriteString("&package=")
  190. buffer.WriteString(prepayId)
  191. buffer.WriteString("&signType=")
  192. buffer.WriteString(signType)
  193. buffer.WriteString("&timeStamp=")
  194. buffer.WriteString(timeStamp)
  195. buffer.WriteString("&key=")
  196. buffer.WriteString(apiKey)
  197. signStr := buffer.String()
  198. var hashSign []byte
  199. if signType == SignType_HMAC_SHA256 {
  200. hash := hmac.New(sha256.New, []byte(apiKey))
  201. hash.Write([]byte(signStr))
  202. hashSign = hash.Sum(nil)
  203. } else {
  204. hash := md5.New()
  205. hash.Write([]byte(signStr))
  206. hashSign = hash.Sum(nil)
  207. }
  208. paySign = strings.ToUpper(hex.EncodeToString(hashSign))
  209. return
  210. }
  211. //APP支付,统一下单获取支付参数后,再次计算APP支付所需要的的sign
  212. // appId:APPID
  213. // partnerid:partnerid
  214. // nonceStr:随即字符串
  215. // prepayId:统一下单成功后得到的值
  216. // signType:此处签名方式,务必与统一下单时用的签名方式一致
  217. // timeStamp:时间
  218. // apiKey:API秘钥值
  219. //
  220. // APP支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12
  221. func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, apiKey string) (paySign string) {
  222. buffer := new(bytes.Buffer)
  223. buffer.WriteString("appid=")
  224. buffer.WriteString(appid)
  225. buffer.WriteString("&noncestr=")
  226. buffer.WriteString(noncestr)
  227. buffer.WriteString("&package=Sign=WXPay")
  228. buffer.WriteString("&partnerid=")
  229. buffer.WriteString(partnerid)
  230. buffer.WriteString("&prepayid=")
  231. buffer.WriteString(prepayid)
  232. buffer.WriteString("&timestamp=")
  233. buffer.WriteString(timestamp)
  234. buffer.WriteString("&key=")
  235. buffer.WriteString(apiKey)
  236. signStr := buffer.String()
  237. var hashSign []byte
  238. if signType == SignType_HMAC_SHA256 {
  239. hash := hmac.New(sha256.New, []byte(apiKey))
  240. hash.Write([]byte(signStr))
  241. hashSign = hash.Sum(nil)
  242. } else {
  243. hash := md5.New()
  244. hash.Write([]byte(signStr))
  245. hashSign = hash.Sum(nil)
  246. }
  247. paySign = strings.ToUpper(hex.EncodeToString(hashSign))
  248. return
  249. }
  250. //解密开放数据
  251. // encryptedData:包括敏感数据在内的完整用户信息的加密数据
  252. // iv:加密算法的初始向量
  253. // sessionKey:会话密钥
  254. // beanPtr:需要解析到的结构体指针
  255. // 文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
  256. func DecryptOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr interface{}) (err error) {
  257. //验证参数类型
  258. beanValue := reflect.ValueOf(beanPtr)
  259. if beanValue.Kind() != reflect.Ptr {
  260. return errors.New("传入beanPtr类型必须是以指针形式")
  261. }
  262. //验证interface{}类型
  263. if beanValue.Elem().Kind() != reflect.Struct {
  264. return errors.New("传入interface{}必须是结构体")
  265. }
  266. aesKey, _ := base64.StdEncoding.DecodeString(sessionKey)
  267. ivKey, _ := base64.StdEncoding.DecodeString(iv)
  268. cipherText, _ := base64.StdEncoding.DecodeString(encryptedData)
  269. if len(cipherText)%len(aesKey) != 0 {
  270. return errors.New("encryptedData is error")
  271. }
  272. //fmt.Println("cipherText:", cipherText)
  273. block, err := aes.NewCipher(aesKey)
  274. if err != nil {
  275. return err
  276. }
  277. //解密
  278. blockMode := cipher.NewCBCDecrypter(block, ivKey)
  279. plainText := make([]byte, len(cipherText))
  280. blockMode.CryptBlocks(plainText, cipherText)
  281. //fmt.Println("plainText1:", plainText)
  282. if len(plainText) > 0 {
  283. plainText = PKCS7UnPadding(plainText)
  284. }
  285. //fmt.Println("plainText:", plainText)
  286. //解析
  287. err = json.Unmarshal(plainText, beanPtr)
  288. if err != nil {
  289. return err
  290. }
  291. return nil
  292. }
  293. //获取微信小程序用户的OpenId、SessionKey、UnionId
  294. // appId:APPID
  295. // appSecret:AppSecret
  296. // wxCode:小程序调用wx.login 获取的code
  297. // 文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
  298. func Code2Session(appId, appSecret, wxCode string) (sessionRsp *Code2SessionRsp, err error) {
  299. sessionRsp = new(Code2SessionRsp)
  300. url := "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + wxCode + "&grant_type=authorization_code"
  301. agent := HttpAgent()
  302. _, _, errs := agent.Get(url).EndStruct(sessionRsp)
  303. if len(errs) > 0 {
  304. return nil, errs[0]
  305. } else {
  306. return sessionRsp, nil
  307. }
  308. }
  309. //获取小程序全局唯一后台接口调用凭据(AccessToken:157字符)
  310. // appId:APPID
  311. // appSecret:AppSecret
  312. // 获取access_token文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
  313. func GetAccessToken(appId, appSecret string) (accessToken *AccessToken, err error) {
  314. accessToken = new(AccessToken)
  315. url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret
  316. agent := HttpAgent()
  317. _, _, errs := agent.Get(url).EndStruct(accessToken)
  318. if len(errs) > 0 {
  319. return nil, errs[0]
  320. } else {
  321. return accessToken, nil
  322. }
  323. }
  324. //授权码查询openid(AccessToken:157字符)
  325. // appId:APPID
  326. // mchId:商户号
  327. // apiKey:ApiKey
  328. // authCode:用户授权码
  329. // nonceStr:随即字符串
  330. // 文档:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_13&index=9
  331. func GetOpenIdByAuthCode(appId, mchId, apiKey, authCode, nonceStr string) (openIdRsp *OpenIdByAuthCodeRsp, err error) {
  332. url := "https://api.mch.weixin.qq.com/tools/authcodetoopenid"
  333. body := make(BodyMap)
  334. body.Set("appid", appId)
  335. body.Set("mch_id", mchId)
  336. body.Set("auth_code", authCode)
  337. body.Set("nonce_str", nonceStr)
  338. sign := getLocalSign(apiKey, SignType_MD5, body)
  339. body.Set("sign", sign)
  340. reqXML := generateXml(body)
  341. //===============发起请求===================
  342. agent := gorequest.New()
  343. agent.Post(url)
  344. agent.Type("xml")
  345. agent.SendString(reqXML)
  346. _, bs, errs := agent.EndBytes()
  347. if len(errs) > 0 {
  348. return nil, errs[0]
  349. }
  350. openIdRsp = new(OpenIdByAuthCodeRsp)
  351. err = xml.Unmarshal(bs, openIdRsp)
  352. if err != nil {
  353. return nil, err
  354. }
  355. return openIdRsp, nil
  356. }
  357. //微信小程序用户支付完成后,获取该用户的 UnionId,无需用户授权。
  358. // accessToken:接口调用凭据
  359. // openId:用户的OpenID
  360. // transactionId:微信支付订单号
  361. // 文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/user-info/auth.getPaidUnionId.html
  362. func GetPaidUnionId(accessToken, openId, transactionId string) (unionId *PaidUnionId, err error) {
  363. unionId = new(PaidUnionId)
  364. url := "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=" + accessToken + "&openid=" + openId + "&transaction_id=" + transactionId
  365. agent := HttpAgent()
  366. _, _, errs := agent.Get(url).EndStruct(unionId)
  367. if len(errs) > 0 {
  368. return nil, errs[0]
  369. } else {
  370. return unionId, nil
  371. }
  372. }
  373. //获取用户基本信息(UnionID机制)
  374. // accessToken:接口调用凭据
  375. // openId:用户的OpenID
  376. // lang:默认为 zh_CN ,可选填 zh_CN 简体,zh_TW 繁体,en 英语
  377. // 获取用户基本信息(UnionID机制)文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
  378. func GetWeChatUserInfo(accessToken, openId string, lang ...string) (userInfo *WeChatUserInfo, err error) {
  379. userInfo = new(WeChatUserInfo)
  380. var url string
  381. if len(lang) > 0 {
  382. url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=" + lang[0]
  383. } else {
  384. url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN"
  385. }
  386. agent := HttpAgent()
  387. _, _, errs := agent.Get(url).EndStruct(userInfo)
  388. if len(errs) > 0 {
  389. return nil, errs[0]
  390. } else {
  391. return userInfo, nil
  392. }
  393. }