github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mch/tools/authcodetoopenid.go (about)

     1  package tools
     2  
     3  import (
     4  	"github.com/chanxuehong/wechat/mch/core"
     5  	"github.com/chanxuehong/wechat/util"
     6  )
     7  
     8  // AuthCodeToOpenId 授权码查询openid.
     9  func AuthCodeToOpenId(clt *core.Client, req map[string]string) (resp map[string]string, err error) {
    10  	return clt.PostXML(core.APIBaseURL()+"/tools/authcodetoopenid", req)
    11  }
    12  
    13  type AuthCodeToOpenIdRequest struct {
    14  	XMLName struct{} `xml:"xml" json:"-"`
    15  
    16  	// 必选参数
    17  	AuthCode string `xml:"auth_code"` // 扫码支付授权码,设备读取用户微信中的条码或者二维码信息
    18  
    19  	// 可选参数
    20  	NonceStr string `xml:"nonce_str"` // 随机字符串,不长于32位。NOTE: 如果为空则系统会自动生成一个随机字符串。
    21  	SignType string `xml:"sign_type"` // 签名类型,默认为MD5,支持HMAC-SHA256和MD5。
    22  }
    23  
    24  type AuthCodeToOpenIdResponse struct {
    25  	XMLName struct{} `xml:"xml" json:"-"`
    26  
    27  	// 必选返回
    28  	OpenId string `xml:"openid"` // 用户在商户appid下的唯一标识
    29  
    30  	// 下面字段都是可选返回的(详细见微信支付文档), 为空值表示没有返回, 程序逻辑里需要判断
    31  	SubOpenId string `xml:"sub_openid"` // 用户在子商户appid下的唯一标识
    32  }
    33  
    34  // AuthCodeToOpenId2 授权码查询openid.
    35  func AuthCodeToOpenId2(clt *core.Client, req *AuthCodeToOpenIdRequest) (resp *AuthCodeToOpenIdResponse, err error) {
    36  	m1 := make(map[string]string, 8)
    37  	m1["auth_code"] = req.AuthCode
    38  	if req.NonceStr != "" {
    39  		m1["nonce_str"] = req.NonceStr
    40  	} else {
    41  		m1["nonce_str"] = util.NonceStr()
    42  	}
    43  	if req.SignType != "" {
    44  		m1["sign_type"] = req.SignType
    45  	}
    46  
    47  	m2, err := AuthCodeToOpenId(clt, m1)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	resp = &AuthCodeToOpenIdResponse{
    53  		OpenId:    m2["openid"],
    54  		SubOpenId: m2["sub_openid"],
    55  	}
    56  	return resp, nil
    57  }