起初的实现思路:
1.通过appid以及secret(秘钥)获取openid;
2.由于前段自己设定的appid和secret,无法通过审核,所以需要后端接口返appid和secret字段名,返的值需要在微信公众号平台获取;
3.面临的问题:微信开发者工具的真机调试可以获取openid,但是预览的不到openid,原因是起前端无法调用外部接口,导致无法获取openid
起初的具体操作步骤:
在data 中声明openId:“”,在mounted中调用:this.getOpenid()
// 获取openid
getOpenid() {
this.$http.get("后端接口返appid和秘钥").then(res => {
console.log(res, 'openid的获取111');
this.appid = res.data.result.appid
this.secret = res.data.result.secret
this.getOpenValue(this.appid, this.secret)
})
},
getOpenValue(appid, secret) {
uni.login({
success: res => {
//code值(5分钟失效)
let code = res.code;
//小程序appid
// let appid = appid; //小程序id
// //小程序secret
// let secret = secret; //密钥
//wx接口路径
let url = 'https://api.weixin.qq.com/sns/jscode2session';
uni.request({
url: url, // 请求路径
data: {
appid: appid,
secret: secret,
js_code: code,
grant_type: 'authorization_code'
}, // 请求体
method: 'GET', //请求方法,
header: {}, //请求头
success: result => {
//响应成功
//这里就获取到了openid了
this.openId = result.data.openid
// uni.setStorage({
// key: 'openId',
// data: result.data.openid
// })
console.log(this.openId, '打印this.openId');
},
fail: err => {} //失败
});
}
});
},
改进的解决方法(已验证,方法可行):
直接影响就是开发环境和生产环境在代码相同的情况下,体现的效果不一样,微信官方也没有任何合理解释,经过很长时间的查找资料,获取openid不能直接在微信客户端来获取,应该改用后端来获取openid然后再返回给前端。
所以应该用Django来获取openid
def getopenid(request):
res = {}
appId = request.GET.get('appId')#开发者appid
secret = request.GET.get('secret')#开发者AppSecret(小程序密钥)
grant_type = "authorization_code" #默认authorization_code
js_code = request.GET.get('js_code')#wx.login登录获取的code值
data = {'appId':appId,'secret':secret,"grant_type":grant_type,"js_code":js_code}
url = "https://api.weixin.qq.com/sns/jscode2session"
jscode = requests.get(url,data)
res = jscode.json()
return JsonResponse(res,safe=False,json_dumps_params={'ensure_ascii':False})
而前端获取openid的方法改造成请求本地接口
每个用户登录的code是不一样的,将code传递给后端,后端调用微信的接口(传递appid、secret、grant_typr、js_code)
// 获取openid
getOpenValue() {
uni.login({
success: res => {
//code值(5分钟失效)
let code = res.code;
//小程序appid
//let appid = appid; //小程序id
//小程序secret
//let secret = secret; //密钥
//wx接口路径
let url = '后端提供的接口getOpenid?code='+code;
uni.request({
url: url, // 请求路径
method: 'GET', //请求方法,
header: {}, //请求头
success: result => {
console.log(result.data.result,'result.data.openid微信');
//响应成功
//这里就获取到了openid了
this.openId = result.data.result
if(this.openId!==""){
this.eventList(this.openId)
}
console.log(this.openId, '打印下下2222');
},
fail: err => {} //失败
});
}
});
},