收藏
回答

app 微信快捷登录,获取code ,提示code 无效

前端部分代码:

uni.login({

provider: 'weixin',

success: function(loginRes) {

console.log(JSON.stringify(loginRes.authResult));

}

});

var weixinService = null;

// http://www.html5plus.org/doc/zh_cn/oauth.html#plus.oauth.getServices

plus.oauth.getServices(function(services) {

if (services && services.length) {

for (var i = 0, len = services.length; i < len; i++) {

if (services[i].id === 'weixin') {

weixinService = services[i];

// console.log('授权对象')

console.log(weixinService)

break;

}

}

plus.nativeUI.alert("认证0!")

if (!weixinService) {

plus.nativeUI.alert("认证1!")

//console.log('没有微信登录授权服务');

return;

}

console.log(res)

plus.nativeUI.alert("认证2!")

// http://www.html5plus.org/doc/zh_cn/oauth.html#plus.oauth.AuthService.authorize

weixinService.authorize(function(event) { //此处获取code的关键

plus.nativeUI.alert("认证3!")

console.log(event)

console.log(event.code, '这次是真的授权后返回的code')

plus.nativeUI.alert("认证4!"+event.code)

后端部分代码:

//微信授权获取OPENID

func (mpwxLoginService *MpwxLoginService) GetWxAppOpenID(authcode string) (string, string, string, string) {

usercorpID := global.GVA_CONFIG.Mini.AppAppid

usersecret := global.GVA_CONFIG.Mini.AppAppSecret

openIDUrl := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + usercorpID + "&secret=" + usersecret + "&code=" + authcode + "&grant_type=authorization_code"

resp, err := http.Get(openIDUrl)

if resp != nil {

defer resp.Body.Close()

}

if err != nil || resp.StatusCode != http.StatusOK {

return "", "", "", err.Error()

}


body, err2 := ioutil.ReadAll(resp.Body)

fmt.Println(openIDUrl, string(body), err2)

if err2 != nil {

return "", "", "", err.Error()

}

//Json Decoding

if bytes.Contains(body, []byte("openid")) {

opidinfo := OpenIDResponse{}

err = json.Unmarshal(body, &opidinfo)

if err != nil {

return "", "", "", err.Error()

}

return opidinfo.OpenID, opidinfo.NickName, opidinfo.SessionKey, ""

}

return "", "", "", string(body)

}

回答关注问题邀请回答
收藏

1 个回答

  • 高殿宝
    高殿宝
    发表于移动端
    2022-04-06
    `
    2022-04-06
    有用
    回复
登录 后发表内容