wxml
<button type="primary" bindtap="login">授权登录</button>
js
// pages/login/login.js
Page({
/**
* 页面的初始数据
*/
data: {
openid: ""
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this
wx.login({
success: (res) => {
wx.request({
url: 'http://www.cs.com/api/demo/openid',
method: "GET",
data: {
code: res.code
},
success: (result) => {
that.setData({
openid: result.data.data
})
}
})
}
})
},
login(){
var that=this
var openid=that.data.openid
wx.getUserProfile({
desc: '授权登录',
success:(res)=>{
var nick_name=res.userInfo.nickName
var avatar_url=res.userInfo.avatarUrl
wx.request({
url: 'http://www.cs.com/api/demo/login',
method:"POST",
data:{nick_name,avatar_url,openid},
success:(result)=>{
wx.setStorageSync('token',result.data.data)
}
})
}
})
}
})
.php 获取openid,composer 安装 :"guzzlehttp/guzzle": "~6.0",
public function openid(Request $request)
{
$code = $request->get("code");
$appid = "";
$secret = "";
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
$client = new Client(['timeout' => 2.0, 'verify' => false]);
$response = $client->get($url);
$res = (string)$response->getBody();
$result = json_decode($res, true);
return json(["error_code"=>0,"data"=>$result["openid"],"msg"=>"返回openid"]);
}
.php 登录处理:
public function login(Request $request){
$data=$request->post();
$res=UserModel::getInfo(["openid"=>$data["openid"]]);
if (!$res){
$result=UserModel::saveInfo($data);
$userInfo=UserModel::getInfo(["id",$result]);
// jwt 获取Token
$token=Token::signToken($userInfo["id"]);
return json(["error_code"=>0,"data"=>$token,"msg"=>"登录成功"]);
}elseif ($res){
$token=Token::signToken($res["id"]);
return json(["error_code"=>0,"data"=>$token,"msg"=>"登录成功"]);
}else{
return json(["error_code"=>1,"data"=>"","msg"=>"登录失败"]);
}
}
jwt请参考: