golang版微信小程序登录和ase解码微信公开数据
- 虽然微信提供了很多版语言的代码,但是没有go版,很简单的,大家想偷个懒就直接
copy 我的代码就好了
-
首选用code登录微信服务器,返回openID和session_key
type RespWXSmall struct {
Openid string `json:"openid"`
Sessionkey string `json:"session_key"`
Unionid string `json:"unionid"`
Errcode int `json:"errcode"`
ErrMsg string `json:"errMsg"`
}
func loginWXSmall(code string) (wxInfo RespWXSmall, err error) {
appId := "******"
appSecret := "***************"
url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
resp, err := http.Get(fmt.Sprintf(url, appId, appSecret, code))
if err != nil {
return wxInfo, err
}
defer resp.Body.Close()
err = tools.BindJson(resp.Body, &wxInfo)
if err != nil {
return wxInfo, err
}
if wxInfo.Errcode != 0 {
return wxInfo, errors.New(fmt.Sprintf("code: %d, errmsg: %s", wxInfo.Errcode, wxInfo.ErrMsg))
}
return wxInfo, nil
}
-
获得放回结果了,进入的业务代码,处理自己的逻辑后,在给小程序返回
-
aes解码微信的公开数据,我参考python的代码
func DecryptWXOpenData(sessionKey, encryptData, iv string) (map[string]interface{}, error) {
decodeBytes, err := base64.StdEncoding.DecodeString(encryptData)
if err != nil {
return nil, err
}
sessionKeyBytes, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return nil, err
}
ivBytes, err := base64.StdEncoding.DecodeString(iv)
if err != nil {
return nil, err
}
dataBytes, err := AesDecrypt(decodeBytes, sessionKeyBytes, ivBytes)
fmt.Println(string(dataBytes))
m := make(map[string]interface{})
err = json.Unmarshal(dataBytes, &m)
if err != nil {
fmt.Println(err)
return nil, err
}
temp := m["watermark"].(map[string]interface{})
appid := temp["appid"].(string)
if appid != setting.WxSmallConf.Appid {
return nil, fmt.Errorf("invalid appid, get !%s!", appid)
}
if err != nil {
return nil, err
}
return m, nil
}
func AesDecrypt(crypted, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, iv)
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
for i, ch := range origData {
if ch == '\x0e' {
origData[i] = ' '
}
}
return origData, nil
}
|
请发表评论