service_api.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. package wechat
  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. "fmt"
  14. "hash"
  15. "io"
  16. "io/ioutil"
  17. "net/http"
  18. "reflect"
  19. "strings"
  20. "github.com/iGoogle-ink/gopay/v2"
  21. )
  22. // 获取微信支付所需参数里的Sign值(通过支付参数计算Sign值)
  23. // 注意:BodyMap中如无 sign_type 参数,默认赋值 sign_type 为 MD5
  24. // appId:应用ID
  25. // mchId:商户ID
  26. // ApiKey:API秘钥值
  27. // 返回参数 sign:通过Appid、MchId、ApiKey和BodyMap中的参数计算出的Sign值
  28. func GetParamSign(appId, mchId, apiKey string, bm gopay.BodyMap) (sign string) {
  29. bm.Set("appid", appId)
  30. bm.Set("mch_id", mchId)
  31. var (
  32. signType string
  33. h hash.Hash
  34. )
  35. signType = bm.Get("sign_type")
  36. if signType == gopay.NULL {
  37. bm.Set("sign_type", SignType_MD5)
  38. }
  39. if signType == SignType_HMAC_SHA256 {
  40. h = hmac.New(sha256.New, []byte(apiKey))
  41. } else {
  42. h = md5.New()
  43. }
  44. h.Write([]byte(bm.EncodeWeChatSignParams(apiKey)))
  45. sign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  46. return
  47. }
  48. // 获取微信支付沙箱环境所需参数里的Sign值(通过支付参数计算Sign值)
  49. // 注意:沙箱环境默认 sign_type 为 MD5
  50. // appId:应用ID
  51. // mchId:商户ID
  52. // ApiKey:API秘钥值
  53. // 返回参数 sign:通过Appid、MchId、ApiKey和BodyMap中的参数计算出的Sign值
  54. func GetSanBoxParamSign(appId, mchId, apiKey string, bm gopay.BodyMap) (sign string, err error) {
  55. bm.Set("appid", appId)
  56. bm.Set("mch_id", mchId)
  57. bm.Set("sign_type", SignType_MD5)
  58. bm.Set("total_fee", 101)
  59. var (
  60. sandBoxApiKey string
  61. hashMd5 hash.Hash
  62. )
  63. if sandBoxApiKey, err = getSanBoxKey(mchId, gopay.GetRandomString(32), apiKey, SignType_MD5); err != nil {
  64. return
  65. }
  66. hashMd5 = md5.New()
  67. hashMd5.Write([]byte(bm.EncodeWeChatSignParams(sandBoxApiKey)))
  68. sign = strings.ToUpper(hex.EncodeToString(hashMd5.Sum(nil)))
  69. return
  70. }
  71. // 解析微信支付异步通知的结果到BodyMap
  72. // req:*http.Request
  73. // 返回参数bm:Notify请求的参数
  74. // 返回参数err:错误信息
  75. func ParseNotifyResultToBodyMap(req *http.Request) (bm gopay.BodyMap, err error) {
  76. bs, err := ioutil.ReadAll(io.LimitReader(req.Body, int64(2<<20))) // default 2MB change the size you want;
  77. if err != nil {
  78. return nil, fmt.Errorf("ioutil.ReadAll:%w", err)
  79. }
  80. bm = make(gopay.BodyMap)
  81. if err = xml.Unmarshal(bs, &bm); err != nil {
  82. return nil, fmt.Errorf("xml.Unmarshal(%s):%w", string(bs), err)
  83. }
  84. return
  85. }
  86. // 解析微信支付异步通知的参数
  87. // req:*http.Request
  88. // 返回参数notifyReq:Notify请求的参数
  89. // 返回参数err:错误信息
  90. func ParseNotifyResult(req *http.Request) (notifyReq *NotifyRequest, err error) {
  91. notifyReq = new(NotifyRequest)
  92. if err = xml.NewDecoder(req.Body).Decode(notifyReq); err != nil {
  93. return nil, fmt.Errorf("xml.NewDecoder.Decode:%w", err)
  94. }
  95. return
  96. }
  97. // 解析微信退款异步通知的参数
  98. // req:*http.Request
  99. // 返回参数notifyReq:Notify请求的参数
  100. // 返回参数err:错误信息
  101. func ParseRefundNotifyResult(req *http.Request) (notifyReq *RefundNotifyRequest, err error) {
  102. notifyReq = new(RefundNotifyRequest)
  103. if err = xml.NewDecoder(req.Body).Decode(notifyReq); err != nil {
  104. return nil, fmt.Errorf("xml.NewDecoder.Decode:%w", err)
  105. }
  106. return
  107. }
  108. // 解密微信退款异步通知的加密数据
  109. // reqInfo:gopay.ParseRefundNotifyResult() 方法获取的加密数据 req_info
  110. // apiKey:API秘钥值
  111. // 返回参数refundNotify:RefundNotify请求的加密数据
  112. // 返回参数err:错误信息
  113. // 文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_16&index=10
  114. func DecryptRefundNotifyReqInfo(reqInfo, apiKey string) (refundNotify *RefundNotify, err error) {
  115. if reqInfo == gopay.NULL || apiKey == gopay.NULL {
  116. return nil, errors.New("reqInfo or apiKey is null")
  117. }
  118. var (
  119. encryptionB, bs []byte
  120. block cipher.Block
  121. blockSize int
  122. )
  123. if encryptionB, err = base64.StdEncoding.DecodeString(reqInfo); err != nil {
  124. return nil, err
  125. }
  126. h := md5.New()
  127. h.Write([]byte(apiKey))
  128. key := strings.ToLower(hex.EncodeToString(h.Sum(nil)))
  129. if len(encryptionB)%aes.BlockSize != 0 {
  130. return nil, errors.New("encryptedData is error")
  131. }
  132. if block, err = aes.NewCipher([]byte(key)); err != nil {
  133. return nil, err
  134. }
  135. blockSize = block.BlockSize()
  136. func(dst, src []byte) {
  137. if len(src)%blockSize != 0 {
  138. panic("crypto/cipher: input not full blocks")
  139. }
  140. if len(dst) < len(src) {
  141. panic("crypto/cipher: output smaller than input")
  142. }
  143. for len(src) > 0 {
  144. block.Decrypt(dst, src[:blockSize])
  145. src = src[blockSize:]
  146. dst = dst[blockSize:]
  147. }
  148. }(encryptionB, encryptionB)
  149. bs = gopay.PKCS7UnPadding(encryptionB)
  150. refundNotify = new(RefundNotify)
  151. if err = xml.Unmarshal(bs, refundNotify); err != nil {
  152. return nil, fmt.Errorf("xml.Unmarshal(%s):%w", string(bs), err)
  153. }
  154. return
  155. }
  156. // 微信同步返回参数验签或异步通知参数验签
  157. // ApiKey:API秘钥值
  158. // signType:签名类型(调用API方法时填写的类型)
  159. // bean:微信同步返回的结构体 wxRsp 或 异步通知解析的结构体 notifyReq
  160. // 返回参数ok:是否验签通过
  161. // 返回参数err:错误信息
  162. func VerifySign(apiKey, signType string, bean interface{}) (ok bool, err error) {
  163. if bean == nil {
  164. return false, errors.New("bean is nil")
  165. }
  166. kind := reflect.ValueOf(bean).Kind()
  167. if kind == reflect.Map {
  168. bm := bean.(gopay.BodyMap)
  169. bodySign := bm.Get("sign")
  170. bm.Remove("sign")
  171. sign := getReleaseSign(apiKey, signType, bm)
  172. return sign == bodySign, nil
  173. }
  174. bs, err := json.Marshal(bean)
  175. if err != nil {
  176. return false, fmt.Errorf("json.Marshal(%s):%w", string(bs), err)
  177. }
  178. bm := make(gopay.BodyMap)
  179. if err = json.Unmarshal(bs, &bm); err != nil {
  180. return false, fmt.Errorf("json.Marshal(%s):%w", string(bs), err)
  181. }
  182. bodySign := bm.Get("sign")
  183. bm.Remove("sign")
  184. sign := getReleaseSign(apiKey, signType, bm)
  185. return sign == bodySign, nil
  186. }
  187. type NotifyResponse struct {
  188. ReturnCode string `xml:"return_code"`
  189. ReturnMsg string `xml:"return_msg"`
  190. }
  191. // 返回数据给微信
  192. func (w *NotifyResponse) ToXmlString() (xmlStr string) {
  193. var buffer strings.Builder
  194. buffer.WriteString("<xml><return_code><![CDATA[")
  195. buffer.WriteString(w.ReturnCode)
  196. buffer.WriteString("]]></return_code>")
  197. buffer.WriteString("<return_msg><![CDATA[")
  198. buffer.WriteString(w.ReturnMsg)
  199. buffer.WriteString("]]></return_msg></xml>")
  200. xmlStr = buffer.String()
  201. return
  202. }
  203. // JSAPI支付,统一下单获取支付参数后,再次计算出小程序用的paySign
  204. // appId:APPID
  205. // nonceStr:随即字符串
  206. // prepayId:统一下单成功后得到的值
  207. // signType:签名类型
  208. // timeStamp:时间
  209. // ApiKey:API秘钥值
  210. // 微信小程序支付API:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
  211. // 微信小程序支付PaySign计算文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3
  212. func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string) {
  213. var (
  214. buffer strings.Builder
  215. h hash.Hash
  216. )
  217. buffer.WriteString("appId=")
  218. buffer.WriteString(appId)
  219. buffer.WriteString("&nonceStr=")
  220. buffer.WriteString(nonceStr)
  221. buffer.WriteString("&package=")
  222. buffer.WriteString(prepayId)
  223. buffer.WriteString("&signType=")
  224. buffer.WriteString(signType)
  225. buffer.WriteString("&timeStamp=")
  226. buffer.WriteString(timeStamp)
  227. buffer.WriteString("&key=")
  228. buffer.WriteString(apiKey)
  229. if signType == SignType_HMAC_SHA256 {
  230. h = hmac.New(sha256.New, []byte(apiKey))
  231. } else {
  232. h = md5.New()
  233. }
  234. h.Write([]byte(buffer.String()))
  235. return strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  236. }
  237. // 微信内H5支付,统一下单获取支付参数后,再次计算出微信内H5支付需要用的paySign
  238. // appId:APPID
  239. // nonceStr:随即字符串
  240. // packages:统一下单成功后拼接得到的值
  241. // signType:签名类型
  242. // timeStamp:时间
  243. // ApiKey:API秘钥值
  244. // 微信内H5支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/external/jsapi.php?chapter=7_7&index=6
  245. func GetH5PaySign(appId, nonceStr, packages, signType, timeStamp, apiKey string) (paySign string) {
  246. var (
  247. buffer strings.Builder
  248. h hash.Hash
  249. )
  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. if signType == SignType_HMAC_SHA256 {
  263. h = hmac.New(sha256.New, []byte(apiKey))
  264. } else {
  265. h = md5.New()
  266. }
  267. h.Write([]byte(buffer.String()))
  268. paySign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  269. return
  270. }
  271. // APP支付,统一下单获取支付参数后,再次计算APP支付所需要的的sign
  272. // appId:APPID
  273. // partnerid:partnerid
  274. // nonceStr:随即字符串
  275. // prepayId:统一下单成功后得到的值
  276. // signType:此处签名方式,务必与统一下单时用的签名方式一致
  277. // timeStamp:时间
  278. // ApiKey:API秘钥值
  279. // APP支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12
  280. func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, apiKey string) (paySign string) {
  281. var (
  282. buffer strings.Builder
  283. h hash.Hash
  284. )
  285. buffer.WriteString("appid=")
  286. buffer.WriteString(appid)
  287. buffer.WriteString("&noncestr=")
  288. buffer.WriteString(noncestr)
  289. buffer.WriteString("&package=Sign=WXPay")
  290. buffer.WriteString("&partnerid=")
  291. buffer.WriteString(partnerid)
  292. buffer.WriteString("&prepayid=")
  293. buffer.WriteString(prepayid)
  294. buffer.WriteString("&timestamp=")
  295. buffer.WriteString(timestamp)
  296. buffer.WriteString("&key=")
  297. buffer.WriteString(apiKey)
  298. if signType == SignType_HMAC_SHA256 {
  299. h = hmac.New(sha256.New, []byte(apiKey))
  300. } else {
  301. h = md5.New()
  302. }
  303. h.Write([]byte(buffer.String()))
  304. paySign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  305. return
  306. }
  307. // 解密开放数据到结构体
  308. // encryptedData:包括敏感数据在内的完整用户信息的加密数据,小程序获取到
  309. // iv:加密算法的初始向量,小程序获取到
  310. // sessionKey:会话密钥,通过 gopay.Code2Session() 方法获取到
  311. // beanPtr:需要解析到的结构体指针,操作完后,声明的结构体会被赋值
  312. // 文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
  313. func DecryptOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr interface{}) (err error) {
  314. if encryptedData == gopay.NULL || iv == gopay.NULL || sessionKey == gopay.NULL {
  315. return errors.New("input params can not null")
  316. }
  317. var (
  318. cipherText, aesKey, ivKey, plainText []byte
  319. block cipher.Block
  320. blockMode cipher.BlockMode
  321. )
  322. beanValue := reflect.ValueOf(beanPtr)
  323. if beanValue.Kind() != reflect.Ptr {
  324. return errors.New("传入beanPtr类型必须是以指针形式")
  325. }
  326. if beanValue.Elem().Kind() != reflect.Struct {
  327. return errors.New("传入interface{}必须是结构体")
  328. }
  329. cipherText, _ = base64.StdEncoding.DecodeString(encryptedData)
  330. aesKey, _ = base64.StdEncoding.DecodeString(sessionKey)
  331. ivKey, _ = base64.StdEncoding.DecodeString(iv)
  332. if len(cipherText)%len(aesKey) != 0 {
  333. return errors.New("encryptedData is error")
  334. }
  335. if block, err = aes.NewCipher(aesKey); err != nil {
  336. return fmt.Errorf("aes.NewCipher:%w", err)
  337. }
  338. blockMode = cipher.NewCBCDecrypter(block, ivKey)
  339. plainText = make([]byte, len(cipherText))
  340. blockMode.CryptBlocks(plainText, cipherText)
  341. if len(plainText) > 0 {
  342. plainText = gopay.PKCS7UnPadding(plainText)
  343. }
  344. if err = json.Unmarshal(plainText, beanPtr); err != nil {
  345. return fmt.Errorf("json.Marshal(%s):%w", string(plainText), err)
  346. }
  347. return
  348. }
  349. // 解密开放数据到 BodyMap
  350. // encryptedData:包括敏感数据在内的完整用户信息的加密数据,小程序获取到
  351. // iv:加密算法的初始向量,小程序获取到
  352. // sessionKey:会话密钥,通过 gopay.Code2Session() 方法获取到
  353. // 文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
  354. func DecryptOpenDataToBodyMap(encryptedData, iv, sessionKey string) (bm gopay.BodyMap, err error) {
  355. if encryptedData == gopay.NULL || iv == gopay.NULL || sessionKey == gopay.NULL {
  356. return nil, errors.New("input params can not null")
  357. }
  358. var (
  359. cipherText, aesKey, ivKey, plainText []byte
  360. block cipher.Block
  361. blockMode cipher.BlockMode
  362. )
  363. cipherText, _ = base64.StdEncoding.DecodeString(encryptedData)
  364. aesKey, _ = base64.StdEncoding.DecodeString(sessionKey)
  365. ivKey, _ = base64.StdEncoding.DecodeString(iv)
  366. if len(cipherText)%len(aesKey) != 0 {
  367. return nil, errors.New("encryptedData is error")
  368. }
  369. if block, err = aes.NewCipher(aesKey); err != nil {
  370. return nil, fmt.Errorf("aes.NewCipher:%w", err)
  371. } else {
  372. blockMode = cipher.NewCBCDecrypter(block, ivKey)
  373. plainText = make([]byte, len(cipherText))
  374. blockMode.CryptBlocks(plainText, cipherText)
  375. if len(plainText) > 0 {
  376. plainText = gopay.PKCS7UnPadding(plainText)
  377. }
  378. bm = make(gopay.BodyMap)
  379. if err = json.Unmarshal(plainText, &bm); err != nil {
  380. return nil, fmt.Errorf("json.Marshal(%s):%w", string(plainText), err)
  381. }
  382. return
  383. }
  384. }
  385. // App应用微信第三方登录,code换取access_token
  386. // appId:应用唯一标识,在微信开放平台提交应用审核通过后获得
  387. // appSecret:应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
  388. // code:App用户换取access_token的code
  389. func GetAppLoginAccessToken(appId, appSecret, code string) (accessToken *AppLoginAccessToken, err error) {
  390. accessToken = new(AppLoginAccessToken)
  391. url := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"
  392. _, errs := gopay.NewHttpClient().Get(url).EndStruct(accessToken)
  393. if len(errs) > 0 {
  394. return nil, errs[0]
  395. }
  396. return accessToken, nil
  397. }
  398. // 刷新App应用微信第三方登录后,获取的 access_token
  399. // appId:应用唯一标识,在微信开放平台提交应用审核通过后获得
  400. // appSecret:应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
  401. // code:App用户换取access_token的code
  402. func RefreshAppLoginAccessToken(appId, refreshToken string) (accessToken *RefreshAppLoginAccessTokenRsp, err error) {
  403. accessToken = new(RefreshAppLoginAccessTokenRsp)
  404. url := "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appId + "&grant_type=refresh_token&refresh_token=" + refreshToken
  405. _, errs := gopay.NewHttpClient().Get(url).EndStruct(accessToken)
  406. if len(errs) > 0 {
  407. return nil, errs[0]
  408. }
  409. return accessToken, nil
  410. }
  411. // 获取微信小程序用户的OpenId、SessionKey、UnionId
  412. // appId:APPID
  413. // appSecret:AppSecret
  414. // wxCode:小程序调用wx.login 获取的code
  415. // 文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
  416. func Code2Session(appId, appSecret, wxCode string) (sessionRsp *Code2SessionRsp, err error) {
  417. sessionRsp = new(Code2SessionRsp)
  418. url := "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + wxCode + "&grant_type=authorization_code"
  419. _, errs := gopay.NewHttpClient().Get(url).EndStruct(sessionRsp)
  420. if len(errs) > 0 {
  421. return nil, errs[0]
  422. }
  423. return sessionRsp, nil
  424. }
  425. // 获取微信小程序全局唯一后台接口调用凭据(AccessToken:157字符)
  426. // appId:APPID
  427. // appSecret:AppSecret
  428. // 获取access_token文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
  429. func GetAppletAccessToken(appId, appSecret string) (accessToken *AccessToken, err error) {
  430. accessToken = new(AccessToken)
  431. url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret
  432. _, errs := gopay.NewHttpClient().Get(url).EndStruct(accessToken)
  433. if len(errs) > 0 {
  434. return nil, errs[0]
  435. }
  436. return accessToken, nil
  437. }
  438. // 授权码查询openid(AccessToken:157字符)
  439. // appId:APPID
  440. // mchId:商户号
  441. // ApiKey:apiKey
  442. // authCode:用户授权码
  443. // nonceStr:随即字符串
  444. // 文档:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_13&index=9
  445. func GetOpenIdByAuthCode(appId, mchId, apiKey, authCode, nonceStr string) (openIdRsp *OpenIdByAuthCodeRsp, err error) {
  446. var (
  447. url string
  448. bm gopay.BodyMap
  449. )
  450. url = "https://api.mch.weixin.qq.com/tools/authcodetoopenid"
  451. bm = make(gopay.BodyMap)
  452. bm.Set("appid", appId)
  453. bm.Set("mch_id", mchId)
  454. bm.Set("auth_code", authCode)
  455. bm.Set("nonce_str", nonceStr)
  456. bm.Set("sign", getReleaseSign(apiKey, SignType_MD5, bm))
  457. openIdRsp = new(OpenIdByAuthCodeRsp)
  458. _, errs := gopay.NewHttpClient().Type(gopay.TypeXML).Post(url).SendString(generateXml(bm)).EndStruct(openIdRsp)
  459. if len(errs) > 0 {
  460. return nil, errs[0]
  461. }
  462. return openIdRsp, nil
  463. }
  464. // 微信小程序用户支付完成后,获取该用户的 UnionId,无需用户授权。
  465. // accessToken:接口调用凭据
  466. // openId:用户的OpenID
  467. // transactionId:微信支付订单号
  468. // 文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/user-info/auth.getPaidUnionId.html
  469. func GetAppletPaidUnionId(accessToken, openId, transactionId string) (unionId *PaidUnionId, err error) {
  470. unionId = new(PaidUnionId)
  471. url := "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=" + accessToken + "&openid=" + openId + "&transaction_id=" + transactionId
  472. _, errs := gopay.NewHttpClient().Get(url).EndStruct(unionId)
  473. if len(errs) > 0 {
  474. return nil, errs[0]
  475. }
  476. return unionId, nil
  477. }
  478. // 获取用户基本信息(UnionID机制)
  479. // accessToken:接口调用凭据
  480. // openId:用户的OpenID
  481. // lang:默认为 zh_CN ,可选填 zh_CN 简体,zh_TW 繁体,en 英语
  482. // 获取用户基本信息(UnionID机制)文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
  483. func GetUserInfo(accessToken, openId string, lang ...string) (userInfo *UserInfo, err error) {
  484. userInfo = new(UserInfo)
  485. url := "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN"
  486. if len(lang) > 0 {
  487. url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=" + lang[0]
  488. }
  489. _, errs := gopay.NewHttpClient().Get(url).EndStruct(userInfo)
  490. if len(errs) > 0 {
  491. return nil, errs[0]
  492. }
  493. return userInfo, nil
  494. }