微信小程序 授权登陆PHP tp5框架_孤单的时候狗作陪!的博客-CSDN博客
HTML页面
<button open-type="getUserInfo" bindtap="login" wx:if="{{ showThis }}">授权登录</button>
<image src="/pages/image/2.png" style="width: 150rpx;height: 150rpx;padding-left: 300rpx;" wx:if="{{ pic }}"></image>
<text>\r\n</text>
<text wx:if="{{ pic }}" style="padding-left: 330rpx;">姓名</text>
JS:解说
// pages/login/login.js
Page({
// 页面的初始数据
data: {
showThis:true,
pic:false
},
onLoad: function (options) {
},
login(){
//通过wx.getUserProfile弹出授权框
let that = this;
wx.getUserProfile({
desc: 'desc',
success:res=>{
//通过wx.login获取code
wx.login({
success:d=>{
let code = d.code;
//发送ajax请求,并将code携带过去
wx.request({
url: 'http://www.weekpic.com/loginDo',
data:{code:code},
success:function(r){
if(r.data.code==200)
{
let id=r.data.data.id;
let token=r.data.data.token;
wx.setStorage({
key:"uid",
data:id
})
that.setData({
showThis:false,
pic:true
})
wx.setStorage({
key:"token",
data:token
})
wx.showToast({
title: '登录成功!',
})
wx.switchTab({
url: '/pages/type/type',
})
}
}
})
}
})
},
fail:res=>{
wx.showToast({
title: "授权失败",
})
}
})
}
})
php解说:
public function loginDo(Request $request)
{
$code=$request->get('code');
$SECRET="";//SECRET
$APPID="";//appid
$url="https://api.weixin.qq.com/sns/jscode2session?appid=$APPID&secret=$SECRET&js_code=$code&grant_type=authorization_code";
$url=json_decode(file_get_contents($url,true),true);
$findRes=login::where('appid',$APPID)->find();
if($findRes)
{
$token=Token::createToken(1);
$data=[
'token'=>$token,
'id'=>$findRes['id']
];
return ['code'=>200,'msg'=>'success','data'=>$data];
}
$createRes=login::create(['appid'=>$APPID]);
if($createRes)
{
// $token=Token::createToken($createRes['id']);
$data=[
'token'=>$token,
'id'=>$createRes['id']
];
return ['code'=>200,'msg'=>'success','data'=>$data];
}
}