使用login code获取openid失败
appid:wxd4298cf3aff9db35
获取openid返回的错误;
errcode: 40029 errMsg: invalid code, hints: [ req_id: 9r2gBa0398ns84 ]
10 回复
//获取code var getCode = function (callback) { wx.login({ success: function (res){ if (res.code) { console.log( 'syslogin: ' , res) console.log( 'request id:' , res.code) typeof callback === "function" && callback(res.code) } else { console.log( '获取code失败!' + res.errMsg) } } }) } // 获取access_token function getToken (callback) { getCode((code) => { wx.getUserInfo({ success: function (res){ console.log( '用户允许授权' ) var request = "code=" + code wx.request({ url: Api.session, data: { code: request, }, method: 'GET' , header:{ "Content-Type" : "application/x-www-form-urlencoded" }, success: function (res){ typeof callback == "function" && callback(res.data) }, fail: function () { console.log( 'wx.request 请求失败' ) } }) }, fail: function (res) { if (res.errMsg) { console.log( '用户拒绝授权' , res) typeof callback == "function" && callback({errMsg : "userDenyed" }) } } }) }) } |
小程序端代码
/ / golang代码,服务端 func Login(ctx * context.Context) { ctx.Request.ParseForm() code : = ctx.Request.FormValue( "code" ) logs.Info( "client login code:" , code) / / 向微信服务器发起请求 tr : = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } appid : = "wxd4298cf3aff9db35" secret : = "XXXXX" //secret确认过,没有问题 url : = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code" client : = &http.Client{Transport: tr} resp, err : = client.Get(url) if err ! = nil { logs.Error(err.Error()) rets.WriteHttpErrMsgs(ctx.ResponseWriter, 500 , err.Error(), err) return } defer resp.Body.Close() if resp.StatusCode = = 200 { body, err : = ioutil.ReadAll(resp.Body) var data ZtgameLoginRt err = json.Unmarshal([]byte(body), &data) if err ! = nil { rets.WriteHttpErrMsgs(ctx.ResponseWriter, 500 , err.Error(), err) return } logs.Info( "errcode:" , data.ErrCode, "errMsg:" , data.ErrMsg) / / logs.Info( "winxin server login return: " , data.Openid) / / logs.Info(data.Session_key) .... } |