Skip to content

Commit

Permalink
add gopay.GetOpenIdByAuthCode(),授权码查询openid
Browse files Browse the repository at this point in the history
  • Loading branch information
Jerry committed Jul 12, 2019
1 parent 9d77045 commit a582040
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
16 changes: 16 additions & 0 deletions wechat_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
12 changes: 12 additions & 0 deletions wechat_rsp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"` //用户唯一标识
}
34 changes: 34 additions & 0 deletions wechat_servier_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit a582040

Please sign in to comment.