社攻联盟 - 大型多人在线游戏活动平台

社攻联盟 - 大型多人在线游戏活动平台

shape

配置IP白名单解决微信小程序服务端获取openid返回null问题

  • Home
  • 直播中心
  • 配置IP白名单解决微信小程序服务端获取openid返回null问题
  • 2026-11-09 04:38:18
  • admin

获取小程序 openid 返回 null

登录 wx.login() 获取到 code,为了安全 session_key 和 openid 不暴露在客户端,而且

https://api.weixin.qq.com

不能设置白名单,需要使用 code 在服务端换取 session_key 和 openid

之前小程序服务一直正常,无提交任何代码,突然获取openid失败,搜索各种文章解决,遇到各种问题 41004 ,40163,code 只能使用一次没问题,Peer certificate CN=miniapi.x.com' did not match expected CN=api.weixin.qq.com`DNS服务器无法连接,ping 过发现没有问题,etc/host 配置也没问题,关联公众号白名单也设置了,后端换两种写法也不行。设置关联小程序的公众号添加IP白名单

看以下步骤

先打印出来 app.js

globalData: {

appid: 'wx7db46aji5jf6',//小程序appid,需自己提供

secret: '9cb98jjk57okp245sd',//小程序密钥,需自己提供

hasLogin: false,

openid: null,

firstTime: true,

accessToken: null

},

getUserOpenId: function() {

var that = this;

//登录

wx.login({

success: function(res) {

console.log(res)//打印code

var d = that.globalData;//这里存储了appid、secret、token串

var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';

console.log(l)打印 curl

//以下代码会报错 https://api.weixin.qq.com 不在以下 request 合法域名列表中,也不能设置IP白名单,而且为了安全客户端不暴露 session_key 和 openid,只能服务端获取

wx.request({

url: l,

data: {

},

method: 'GET',

// header: {}, // 设置请求的 header

success: function (res) {

console.log(res)

var obj = {

};

obj.openid = res.data.openid;

obj.expires_in = Date.now() + res.data.expires_in;

console.log(obj);

//wx.setStorageSync('user', obj);//存储openid

}

});

/*

//code 获取 openid 的正确方式,code每次都是最新的而且只能使用一次

wx.request({

url: that.apis.domain + that.apis.login,

header: {

"Content-Type": "application/x-www-form-urlencoded"

},

method: 'POST',

data: {

code: res.code

},

success: function(res) {

if(res.data.status == 1){

//console.log('拉取openid成功', res);

console.log(res)

that.globalData.hasLogin = true;

that.globalData.openid = res.data.data.openid;

that.firstTime(res.data.data.openid);

} else {

that.globalData.hasLogin = false;

//console.log('拉取openID失败,将无法正常使用开放接口等服务',res);

}

},

fail: function(res) {

console.log('拉取用户openid失败,将无法正常使用开放接口等服务', res)

callback(res)

}

})

*/

},

fail: function(err) {

console.log('wx.login 接口调用失败,将无法正常使用开放接口等服务', err)

callback(err)

}

})

},

看打印结果 code 和 url

在 postman 测试,先使用 code 请求后端接口,返回 null

把 url 拿出来直接在 postman 请求每次都是成功的,确认是后端服务的问题

把 url 放在服务器直接 curl,各种报错来了 "errcode":41004,"errmsg":"appsecret missing 各种方法用过没有解决问题

最后设置关联小程序的公众号添加IP白名单后重启服务器问题解决了,没有更改任何代码

Previous Post
小雪被禁赛三天

Copyright © 2088 社攻联盟 - 大型多人在线游戏活动平台 All Rights Reserved.

友情链接