wechat_servier_api.go 11 KB

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