废话不多说直接上代码
小程序端
页面
<view class="container">
<view class="userinfo">
<block wx:if="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
</view>
js
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUseGetUserProfile: false,
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
wx.request({
url: '你的后台接口',
data:{
code:'你app.js里的login()方法里的res.code',
userinfo:this.data.userInfo,
},
success:res=>{
// console.log(res.data);
wx.setStorageSync('token', res.data.token)
}
})
}
})
},
})
如果出错就打印打印res 有可能是因为你的字段名和我的字段名有大小写区别
后台接口
在config里面创建一个wechatUrl.php的文件
<?php
return[
'appid'=>'微信公众平台获取',
'secret'=>'微信公众平台获取',
//%s 是占位符
'url'=>'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code'
];
controller方法里定义方法
public function 方法名(Request $request)
{
$code=$request->code;
$url=sprintf(config('wechatUrl.url'),config('url.appid'),config('wechatUrl.secret'),$code);
$client=new Client(['timeout'=>5,'verify'=>false]);
$res=$client->get($url);
$data=(string)$res->getBody();
$arr=json_decode($data,true);
$user=User::where('openid',$arr['openid'])->first();
if (empty($user)){
$user=User::create([
'openid'=>$arr['openid'],
'session_key'=>$arr['session_key']
]);
}
$userinfo=json_decode($request->get('userinfo'),true);
$user->update([
'nickname'=>$userinfo['nickName'],
'avatarurl'=>$userinfo['avatarUrl'],
'gender'=>$userinfo['gender']
]);
//jwt 生成token
$token=$user->createToken('api')->accessToken;
Cache::set($token,$user,7200);
return ['code'=>200,'msg'=>'ok','token'=>$token];
}
重点来了!!!
opneid和session_key
openid必须加密返回前台
session_key绝对不能返回前台
继续
模型成中
//像软删除一样
use HasApiTokens;
并且引入auth:如下
use Illuminate\Foundation\Auth\User as AuthUser;
config.php/auth.php
在guards数组中加入
'api' => [
'driver' => 'passport',
'provider' => 'apiusers',
'hash' => false,
]
在providers数组中
'apiusers' => [
'driver' => 'eloquent',
'model' => 模型层路径::class,
],
另外有的时候可能需要改一下框架的时间:
'timezone' => 'PRC',
这个在哪同学们应该知道吧
利用中间键判断header是否存在
差不多就出来了
举个例子请求的时候:
var token=wx.getStorageSync('token')
wx.request({
url: '你的接口',
header:{
'Authorization': `Bearer ${token}`
},
success:res=>{}
})
就完成了