获取SessionKey:
// GetSessionKey 根据jsCode获取私钥
func GetSessionKey(jsCode string, appData map[string]interface{}) (*OpenidRule, string) {
url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
appID := appData["appId"].(string)
appSecret := appData["appSecret"].(string)
url = fmt.Sprintf(url, appID, appSecret, jsCode)
resp, err := http.Get(url)
if err != nil {
return nil, "openId获取失败"
}
defer resp.Body.Close()
wxResp := OpenidRule{}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&wxResp); err != nil {
return nil, "微信参数解析失败"
}
if wxResp.ErrCode != 0 {
return nil, wxResp.ErrMsg
}
if len(wxResp.SessionKey) == 0 || len(wxResp.OpenID) == 0 {
return nil, "微信参数获取失败"
}
return &wxResp, ""
}
解析秘钥中的手机号:
// GetPhone 获取手机号
func GetPhone(sessionKey, iv, encryptedData string) interface{} {
sessionKeyBase, sessionKeyErr := base64.StdEncoding.DecodeString(sessionKey)
if sessionKeyErr != nil {
return nil
}
encryptedDataBase, encryptedDataErr := base64.StdEncoding.DecodeString(encryptedData)
if encryptedDataErr != nil {
return nil
}
ivBase, ivErr := base64.StdEncoding.DecodeString(iv)
if ivErr != nil {
return nil
}
keyByteString := string(sessionKeyBase)
cipherBlock, cipherErr := aes.NewCipher([]byte(keyByteString))
if cipherErr != nil {
return nil
}
cipher.NewCBCDecrypter(cipherBlock, ivBase).CryptBlocks(encryptedDataBase, encryptedDataBase)
wechatUserPhone := string(PKCS5UnPadding(encryptedDataBase))
rawData := []byte(wechatUserPhone)
var phoneResp = map[string]interface{}{}
jsonErr := json.Unmarshal(rawData, &phoneResp)
if _, phoneOk := phoneResp["phoneNumber"]; jsonErr != nil || !phoneOk {
return nil
}
return phoneResp
}
// PKCS5UnPadding 解密OPENSLL数据
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
if length-unpadding < 0 {
return []byte("")
}
return src[:(length - unpadding)]
}