diff --git a/wechat_client_test.go b/wechat_client_test.go index f8878489..cf6a73b0 100644 --- a/wechat_client_test.go +++ b/wechat_client_test.go @@ -339,3 +339,19 @@ func TestDecryptOpenDataToStruct(t *testing.T) { fmt.Println("CountryCode:", phone.CountryCode) fmt.Println("Watermark:", phone.Watermark) } + +func TestGetOpenIdByAuthCode(t *testing.T) { + openIdRsp, err := GetOpenIdByAuthCode(AppID, MchID_iguiyu, "135127679952609396", ApiKey_iguiyu, GetRandomString(32)) + if err != nil { + fmt.Println("err:", err) + return + } + fmt.Println("ReturnCode:", openIdRsp.ReturnCode) + fmt.Println("ReturnMsg:", openIdRsp.ReturnMsg) + fmt.Println("ResultCode:", openIdRsp.ResultCode) + fmt.Println("Appid:", openIdRsp.Appid) + fmt.Println("MchId:", openIdRsp.MchId) + fmt.Println("NonceStr:", openIdRsp.NonceStr) + fmt.Println("err_code:", openIdRsp.ErrCode) + fmt.Println("Openid:", openIdRsp.Openid) +} diff --git a/wechat_rsp.go b/wechat_rsp.go index 547d8cf6..dadb9b91 100644 --- a/wechat_rsp.go +++ b/wechat_rsp.go @@ -268,3 +268,15 @@ type watermarkInfo struct { Appid string `json:"appid"` Timestamp int `json:"timestamp"` } + +type OpenIdByAuthCodeRsp struct { + ReturnCode string `xml:"return_code"` + ReturnMsg string `xml:"return_msg"` + Appid string `xml:"appid"` + MchId string `xml:"mch_id"` + NonceStr string `xml:"nonce_str"` + Sign string `xml:"sign"` + ResultCode string `xml:"result_code"` + ErrCode string `xml:"err_code"` + Openid string `xml:"openid"` //用户唯一标识 +} diff --git a/wechat_servier_api.go b/wechat_servier_api.go index 361d8f0b..10c5a590 100644 --- a/wechat_servier_api.go +++ b/wechat_servier_api.go @@ -299,6 +299,40 @@ func GetAccessToken(appId, appSecret string) (accessToken *AccessToken, err erro } } +//授权码查询openid(AccessToken:157字符) +// appId:APPID +// mchId:商户号 +// authCode:用户授权码 +// nonceStr:随即字符串 +func GetOpenIdByAuthCode(appId, mchId, authCode, apiKey, nonceStr string) (openIdRsp *OpenIdByAuthCodeRsp, err error) { + + url := "https://api.mch.weixin.qq.com/tools/authcodetoopenid" + body := make(BodyMap) + body.Set("appid", appId) + body.Set("mch_id", mchId) + body.Set("auth_code", authCode) + body.Set("nonce_str", nonceStr) + sign := getLocalSign(apiKey, SignType_MD5, body) + + body.Set("sign", sign) + reqXML := generateXml(body) + //===============发起请求=================== + agent := gorequest.New() + agent.Post(url) + agent.Type("xml") + agent.SendString(reqXML) + _, bs, errs := agent.EndBytes() + if len(errs) > 0 { + return nil, errs[0] + } + openIdRsp = new(OpenIdByAuthCodeRsp) + err = xml.Unmarshal(bs, openIdRsp) + if err != nil { + return nil, err + } + return openIdRsp, nil +} + //用户支付完成后,获取该用户的 UnionId,无需用户授权。 // accessToken:接口调用凭据 // openId:用户的OpenID