wechat_servier_api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. // appId:APPID
  105. // nonceStr:随即字符串
  106. // prepayId:统一下单成功后得到的值
  107. // signType:签名类型
  108. // timeStamp:时间
  109. // apiKey:API秘钥值
  110. func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
  111. buffer := new(bytes.Buffer)
  112. buffer.WriteString("appId=")
  113. buffer.WriteString(appId)
  114. buffer.WriteString("&nonceStr=")
  115. buffer.WriteString(nonceStr)
  116. buffer.WriteString("&package=")
  117. buffer.WriteString(prepayId)
  118. buffer.WriteString("&signType=")
  119. buffer.WriteString(signType)
  120. buffer.WriteString("&timeStamp=")
  121. buffer.WriteString(timeStamp)
  122. buffer.WriteString("&key=")
  123. buffer.WriteString(apiKey)
  124. signStr := buffer.String()
  125. var hashSign []byte
  126. if signType == SignType_HMAC_SHA256 {
  127. hash := hmac.New(sha256.New, []byte(apiKey))
  128. hash.Write([]byte(signStr))
  129. hashSign = hash.Sum(nil)
  130. } else {
  131. hash := md5.New()
  132. hash.Write([]byte(signStr))
  133. hashSign = hash.Sum(nil)
  134. }
  135. paySign = strings.ToUpper(hex.EncodeToString(hashSign))
  136. return
  137. }
  138. //JSAPI支付,统一下单获取支付参数后,再次计算出微信内H5支付需要用的paySign
  139. // appId:APPID
  140. // nonceStr:随即字符串
  141. // prepayId:统一下单成功后得到的值
  142. // signType:签名类型
  143. // timeStamp:时间
  144. // apiKey:API秘钥值
  145. func GetH5PaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
  146. buffer := new(bytes.Buffer)
  147. buffer.WriteString("appId=")
  148. buffer.WriteString(appId)
  149. buffer.WriteString("&nonceStr=")
  150. buffer.WriteString(nonceStr)
  151. buffer.WriteString("&package=")
  152. buffer.WriteString(prepayId)
  153. buffer.WriteString("&signType=")
  154. buffer.WriteString(signType)
  155. buffer.WriteString("&timeStamp=")
  156. buffer.WriteString(timeStamp)
  157. buffer.WriteString("&key=")
  158. buffer.WriteString(apiKey)
  159. signStr := buffer.String()
  160. var hashSign []byte
  161. if signType == SignType_HMAC_SHA256 {
  162. hash := hmac.New(sha256.New, []byte(apiKey))
  163. hash.Write([]byte(signStr))
  164. hashSign = hash.Sum(nil)
  165. } else {
  166. hash := md5.New()
  167. hash.Write([]byte(signStr))
  168. hashSign = hash.Sum(nil)
  169. }
  170. paySign = strings.ToUpper(hex.EncodeToString(hashSign))
  171. return
  172. }
  173. //APP支付,统一下单获取支付参数后,再次计算APP支付所需要的的sign
  174. // appId:APPID
  175. // partnerid:partnerid
  176. // nonceStr:随即字符串
  177. // prepayId:统一下单成功后得到的值
  178. // signType:此处签名方式,务必与统一下单时用的签名方式一致
  179. // timeStamp:时间
  180. // apiKey:API秘钥值
  181. func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, apiKey string) (paySign string) {
  182. buffer := new(bytes.Buffer)
  183. buffer.WriteString("appid=")
  184. buffer.WriteString(appid)
  185. buffer.WriteString("&nonceStr=")
  186. buffer.WriteString(noncestr)
  187. buffer.WriteString("&package=Sign=WXPay")
  188. buffer.WriteString("&partnerid=")
  189. buffer.WriteString(partnerid)
  190. buffer.WriteString("&prepayid=")
  191. buffer.WriteString(prepayid)
  192. buffer.WriteString("&timeStamp=")
  193. buffer.WriteString(timestamp)
  194. buffer.WriteString("&key=")
  195. buffer.WriteString(apiKey)
  196. signStr := buffer.String()
  197. var hashSign []byte
  198. if signType == SignType_HMAC_SHA256 {
  199. hash := hmac.New(sha256.New, []byte(apiKey))
  200. hash.Write([]byte(signStr))
  201. hashSign = hash.Sum(nil)
  202. } else {
  203. hash := md5.New()
  204. hash.Write([]byte(signStr))
  205. hashSign = hash.Sum(nil)
  206. }
  207. paySign = strings.ToUpper(hex.EncodeToString(hashSign))
  208. return
  209. }
  210. //解密开放数据
  211. // encryptedData:包括敏感数据在内的完整用户信息的加密数据
  212. // iv:加密算法的初始向量
  213. // sessionKey:会话密钥
  214. // beanPtr:需要解析到的结构体指针
  215. func DecryptOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr interface{}) (err error) {
  216. //验证参数类型
  217. beanValue := reflect.ValueOf(beanPtr)
  218. if beanValue.Kind() != reflect.Ptr {
  219. return errors.New("传入beanPtr类型必须是以指针形式")
  220. }
  221. //验证interface{}类型
  222. if beanValue.Elem().Kind() != reflect.Struct {
  223. return errors.New("传入interface{}必须是结构体")
  224. }
  225. aesKey, _ := base64.StdEncoding.DecodeString(sessionKey)
  226. ivKey, _ := base64.StdEncoding.DecodeString(iv)
  227. cipherText, _ := base64.StdEncoding.DecodeString(encryptedData)
  228. if len(cipherText)%len(aesKey) != 0 {
  229. return errors.New("encryptedData is error")
  230. }
  231. //fmt.Println("cipherText:", cipherText)
  232. block, err := aes.NewCipher(aesKey)
  233. if err != nil {
  234. return err
  235. }
  236. //解密
  237. blockMode := cipher.NewCBCDecrypter(block, ivKey)
  238. plainText := make([]byte, len(cipherText))
  239. blockMode.CryptBlocks(plainText, cipherText)
  240. //fmt.Println("plainText1:", plainText)
  241. plainText = PKCS7UnPadding(plainText)
  242. //fmt.Println("plainText:", plainText)
  243. //解析
  244. err = json.Unmarshal(plainText, beanPtr)
  245. if err != nil {
  246. return err
  247. }
  248. return nil
  249. }
  250. //获取微信用户的OpenId、SessionKey、UnionId
  251. // appId:APPID
  252. // appSecret:AppSecret
  253. // wxCode:小程序调用wx.login 获取的code
  254. func Code2Session(appId, appSecret, wxCode string) (sessionRsp *Code2SessionRsp, err error) {
  255. sessionRsp = new(Code2SessionRsp)
  256. url := "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + wxCode + "&grant_type=authorization_code"
  257. agent := HttpAgent()
  258. _, _, errs := agent.Get(url).EndStruct(sessionRsp)
  259. if len(errs) > 0 {
  260. return nil, errs[0]
  261. } else {
  262. return sessionRsp, nil
  263. }
  264. }
  265. //获取小程序全局唯一后台接口调用凭据(AccessToken:157字符)
  266. // appId:APPID
  267. // appSecret:AppSecret
  268. func GetAccessToken(appId, appSecret string) (accessToken *AccessToken, err error) {
  269. accessToken = new(AccessToken)
  270. url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret
  271. agent := HttpAgent()
  272. _, _, errs := agent.Get(url).EndStruct(accessToken)
  273. if len(errs) > 0 {
  274. return nil, errs[0]
  275. } else {
  276. return accessToken, nil
  277. }
  278. }
  279. //授权码查询openid(AccessToken:157字符)
  280. // appId:APPID
  281. // mchId:商户号
  282. // apiKey:ApiKey
  283. // authCode:用户授权码
  284. // nonceStr:随即字符串
  285. func GetOpenIdByAuthCode(appId, mchId, apiKey, authCode, nonceStr string) (openIdRsp *OpenIdByAuthCodeRsp, err error) {
  286. url := "https://api.mch.weixin.qq.com/tools/authcodetoopenid"
  287. body := make(BodyMap)
  288. body.Set("appid", appId)
  289. body.Set("mch_id", mchId)
  290. body.Set("auth_code", authCode)
  291. body.Set("nonce_str", nonceStr)
  292. sign := getLocalSign(apiKey, SignType_MD5, body)
  293. body.Set("sign", sign)
  294. reqXML := generateXml(body)
  295. //===============发起请求===================
  296. agent := gorequest.New()
  297. agent.Post(url)
  298. agent.Type("xml")
  299. agent.SendString(reqXML)
  300. _, bs, errs := agent.EndBytes()
  301. if len(errs) > 0 {
  302. return nil, errs[0]
  303. }
  304. openIdRsp = new(OpenIdByAuthCodeRsp)
  305. err = xml.Unmarshal(bs, openIdRsp)
  306. if err != nil {
  307. return nil, err
  308. }
  309. return openIdRsp, nil
  310. }
  311. //用户支付完成后,获取该用户的 UnionId,无需用户授权。
  312. // accessToken:接口调用凭据
  313. // openId:用户的OpenID
  314. // transactionId:微信支付订单号
  315. func GetPaidUnionId(accessToken, openId, transactionId string) (unionId *PaidUnionId, err error) {
  316. unionId = new(PaidUnionId)
  317. url := "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=" + accessToken + "&openid=" + openId + "&transaction_id=" + transactionId
  318. agent := HttpAgent()
  319. _, _, errs := agent.Get(url).EndStruct(unionId)
  320. if len(errs) > 0 {
  321. return nil, errs[0]
  322. } else {
  323. return unionId, nil
  324. }
  325. }
  326. //获取用户基本信息(UnionID机制)
  327. // accessToken:接口调用凭据
  328. // openId:用户的OpenID
  329. // lang:默认为 zh_CN ,可选填 zh_CN 简体,zh_TW 繁体,en 英语
  330. func GetWeChatUserInfo(accessToken, openId string, lang ...string) (userInfo *WeChatUserInfo, err error) {
  331. userInfo = new(WeChatUserInfo)
  332. var url string
  333. if len(lang) > 0 {
  334. url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=" + lang[0]
  335. } else {
  336. url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN"
  337. }
  338. agent := HttpAgent()
  339. _, _, errs := agent.Get(url).EndStruct(userInfo)
  340. if len(errs) > 0 {
  341. return nil, errs[0]
  342. } else {
  343. return userInfo, nil
  344. }
  345. }