授权登录
小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系
登录流程时序
1、通过wx.login接口获取code
2、再通过wx.request()接口把code发送到后端获取登录凭证
3、后端通过appid,appsecret和code发送请求到auth.code2Session接口
4、后端获取接口返回来的信息后再把它返回前端
5、前端获取返回的信息判断是否登录
1、通过wx.login接口获取code
<view class="container">
<button bindtap="onlogin">授权登录</button>
</view>
onlogin(){
wx.login({
success:function(res){
const code = res.code;
})
}
2、再通过wx.request()接口把code发送到后端获取登录凭证
onlogin(){
wx.login({
success:function(res){
const code = res.code;
wx.request({
url: 'http://www.kk.com/admin/admin.php',
data:{
code:code
},
header:{// 设置头部信息
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',// 提交方法
success:function(res){
console.log(res)
}
})
}
})
}
3、后端通过appid,appsecret和code发送请求到auth.code2Session接口
4、后端获取接口返回来的信息后再把它返回前端
// 接口地址:https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
$code = $_POST['code'];
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=填写自己appid&secret=填写自己的密钥&js_code=$code&grant_type=authorization_code";
$json = https_request($url);
$data = json_decode($json,true);
// 返回数据
if($data['errcode'] == 0){
echo json_encode($data);
exit;
}
function https_request($url,$data = null)
{
if(function_exists('curl_init')){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}else{
return false;
}
}
5、前端获取返回的信息判断是否登录
onlogin(){
wx.login({
success:function(res){
const code = res.code;
wx.request({
url: 'http://www.kk.com/admin/admin.php',
data:{
code:code
},
header:{// 设置头部信息
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',// 提交方法
success:function(res){
console.log(res)
if(res.data=''){
wx.showToast({
title: '登录成功',
})
}else{
wx.showToast({
title: '登录失败',
})
}
}
})
}
})
}