正常开发中肯定都是通过后台获取调用微信公众平台接口获取openid,说白了就是为了保护一些敏感信息,appid,secret密钥不被泄露,
但我们平时自己测试的时候前端也是一样可以拿到,来达到某种功能实现的
微信官方提供的接口进行调用 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
// 获取openid
getOpenId(){
wx.login({
success: function (res) {
var appid = "wxxxxxxxxxxxxxxxx" // 这里填写appid
var secret = "af71xxxxxxxxxxxxxxxxxxxxxxx" // 密钥
var openid = ""
var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + res.code + '&grant_type=authorization_code';
wx.request({
url: url,
data: {},
method: 'GET',
success: function (res) {
// 不出意外在控制台就能获取到了
console.log(res)
openid = res.openid
}
});
}
})
},
好了,这样就获取到了,非常的简单
自己做一些小东西,但是又不想整后台的时候可以使用哈,项目中就不要这样写了
网友评论