wechat_service_api.go 16 KB

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