本文主要是介绍golang版微信小程序登录和ase解码微信公开数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
golang版微信小程序登录和ase解码微信公开数据
- 虽然微信提供了很多版语言的代码,但是没有go版,很简单的,大家想偷个懒就直接
copy
我的代码就好了
-
首选用code登录微信服务器,返回openID和session_key
type RespWXSmall struct {Openid string `json:"openid"` //用户唯一标识Sessionkey string `json:"session_key"` //会话密钥Unionid string `json:"unionid"` //用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。Errcode int `json:"errcode"` //错误码ErrMsg string `json:"errMsg"` //错误信息 }func loginWXSmall(code string) (wxInfo RespWXSmall, err error) {//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_codeappId := "******"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}//blockSize := block.BlockSize()blockMode := cipher.NewCBCDecrypter(block, iv)origData := make([]byte, len(crypted))blockMode.CryptBlocks(origData, crypted)//获取的数据尾端有'/x0e'占位符,去除它for i, ch := range origData {if ch == '\x0e' {origData[i] = ' '}}//{"phoneNumber":"15082726017","purePhoneNumber":"15082726017","countryCode":"86","watermark":{"timestamp":1539657521,"appid":"wx4c6c3ed14736228c"}}//<nil>return origData, nil }
这篇关于golang版微信小程序登录和ase解码微信公开数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!