wechat_servier_api.go 10.0 KB

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