首先上微信小程序文档里边获取流程图,方便理解流程
我用的post的方法:
1.从小程序端获得用户临时登陆凭证code
2.用post方法从小程序发送获得的code给自己的服务器端
3.服务器端获取code并使用get方法发送appid,secret,code给腾讯解密,并获取openid和session_key,并返回到小程序端。
上代码
小程序端
js中的代码
bingGetUserInfo: function() {
wx.login({
success: function(data) {
console.log('获取登录 Code:' + data.code)
var code = data.code;
wx.request({
url: '输入你自己的网站',
data:{
code: code,
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
},
success: function(res) {
//回调处理
console.log("ok");
console.log(res.data);
},
fail: function(error) {
console.log(error);
}
})
},
fail: function() {
console('登录获取Code失败!');
}
})
},
wxml中的代码
在按钮中添加以下代码即可触发
bindgetuserinfo="bingGetUserInfo"
后台服务器中的代码
<?php
//声明CODE,获取小程序传过来的CODE
$code = $_POST["code"];
//配置appid
$appid = "填你自己的APPID";
//配置appscret
$secret = "填你自己的appscret";
//api接口
$api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
$html = file_get_contents($api);
echo $html;
?>
这些代码是我经过多次实验+搜到的代码拼凑起来的(花了将近一天的时间)分享给大家
另外大家可能遇到的问题也是我之前遇到的一些问题
返回值14001 err 可能是小程序向服务器传送code时,服务器未获取code,当然我已经改正过来了,当时的错误原因是:小程序端使用post方法,而我的服务器端获取时用的get方法。
不懂就问,努力学习。