diff --git a/wechat_export.go b/wechat_servier_api.go similarity index 58% rename from wechat_export.go rename to wechat_servier_api.go index abe2a084..cec962d2 100644 --- a/wechat_export.go +++ b/wechat_servier_api.go @@ -12,11 +12,16 @@ import ( "crypto/sha256" "crypto/tls" "encoding/hex" - "fmt" "github.com/parnurzeal/gorequest" "strings" ) +func HttpAgent() (agent *gorequest.SuperAgent) { + agent = gorequest.New() + agent.TLSClientConfig(&tls.Config{InsecureSkipVerify: true}) + return +} + //JSAPI支付,支付参数后,再次计算出小程序用的paySign func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, secretKey string) (paySign string) { buffer := new(bytes.Buffer) @@ -92,20 +97,50 @@ func GetH5PaySign(appId, nonceStr, prepayId, signType, timeStamp, secretKey stri } //获取微信用户的OpenId、SessionKey、UnionId -func GetWeChatUserId(appId, secretKey, wxCode string) (userRsp *WeChatUserIdRsp, err error) { - userRsp = new(WeChatUserIdRsp) +// appId:APPID +// appSecret:AppSecret +// wxCode:小程序调用wx.login 获取的code +func Code2Session(appId, appSecret, wxCode string) (userRsp *Code2SessionRsp, err error) { + userRsp = new(Code2SessionRsp) + url := "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + wxCode + "&grant_type=authorization_code" + agent := HttpAgent() + _, _, errs := agent.Get(url).EndStruct(userRsp) + if len(errs) > 0 { + return nil, errs[0] + } else { + return userRsp, nil + } +} - url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%v&secret=%v&js_code=%v&grant_type=authorization_code", appId, secretKey, wxCode) +//获取小程序全局唯一后台接口调用凭据(AccessToken:157字符) +// appId:APPID +// appSecret:AppSecret +func GetAccessToken(appId, appSecret string) (rsp *GetAccessTokenRsp, err error) { + rsp = new(GetAccessTokenRsp) + url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret - agent := gorequest.New() - tlsCfg := &tls.Config{ - InsecureSkipVerify: true, + agent := HttpAgent() + _, _, errs := agent.Get(url).EndStruct(rsp) + if len(errs) > 0 { + return nil, errs[0] + } else { + return rsp, nil } - agent.TLSClientConfig(tlsCfg) - _, _, errs := agent.Get(url).EndStruct(userRsp) +} + +//用户支付完成后,获取该用户的 UnionId,无需用户授权。 +// accessToken:接口调用凭据 +// openId:用户的OpenID +// transactionId:微信支付订单号 +func GetPaidUnionId(accessToken, openId, transactionId string) (rsp *GetPaidUnionIdRsp, err error) { + rsp = new(GetPaidUnionIdRsp) + url := "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=" + accessToken + "&openid=" + openId + "&transaction_id=" + transactionId + + agent := HttpAgent() + _, _, errs := agent.Get(url).EndStruct(rsp) if len(errs) > 0 { return nil, errs[0] } else { - return userRsp, nil + return rsp, nil } }