接上篇微信小程序后端搭建:分享:laravel 微信小程序后端搭建
后端搭建好后第一件事就是用户登录认证,简单实现微信小程序登录认证
1.user 模型
use laravel\passport\hasapitokens; 新增
use hasapitokens, notifiable; protected $fillable = [ 'id', 'name', 'email', 'email_verified_at', 'username', 'phone', 'avatar',//我用来把微信头像的/0清晰图片,存到又拍云上 'weapp_openid', 'nickname', 'weapp_avatar', 'country', 'province', 'city', 'language', 'location', 'gender', 'level',//用户等级 'is_admin',//is管理员 ];
2. 新增一条路由
//前端小程序拿到的地址:https://域名/api/v1/自己写的接口 route::group(['prefix' => '/v1'], function () { route::post('/user/login', 'usercontroller@weapplogin'); });
3. 在 usercontroller 控制器里新建 function weapplogin (),别忘了 use 这些
use app\user; use carbon\carbon; use illuminate\http\request; use illuminate\support\facades\storage;
写两个 function weapplogin (),avatarupyun ()
public function weapplogin(request $request) { $code = $request->code; // 根据 code 获取微信 openid 和 session_key $miniprogram = \easywechat::miniprogram(); $data = $miniprogram->auth->session($code); if (isset($data['errcode'])) { return $this->response->errorunauthorized('code已过期或不正确'); } $weappopenid = $data['openid']; $weixinsessionkey = $data['session_key']; $nickname = $request->nickname; $avatar = str_replace('/132', '/0', $request->avatar);//拿到分辨率高点的头像 $country = $request->country?$request->country:''; $province = $request->province?$request->province:''; $city = $request->city?$request->city:''; $gender = $request->gender == '1' ? '1' : '2';//没传过性别的就默认女的吧,体验好些 $language = $request->language?$request->language:''; //找到 openid 对应的用户 $user = user::where('weapp_openid', $weappopenid)->first(); //没有,就注册一个用户 if (!$user) { $user = user::create([ 'weapp_openid' => $weappopenid, 'weapp_session_key' => $weixinsessionkey, 'password' => $weixinsessionkey, 'avatar' => $request->avatar?$this->avatarupyun($avatar):'', 'weapp_avatar' => $avatar, 'nickname' => $nickname, 'country' => $country, 'province' => $province, 'city' => $city, 'gender' => $gender, 'language' => $language, ]); } //如果注册过的,就更新下下面的信息 $attributes['updated_at'] = now(); $attributes['weixin_session_key'] = $weixinsessionkey; $attributes['weapp_avatar'] = $avatar; if ($nickname) { $attributes['nickname'] = $nickname; } if ($request->gender) { $attributes['gender'] = $gender; } // 更新用户数据 $user->update($attributes); // 直接创建token并设置有效期 $createtoken = $user->createtoken($user->weapp_openid); $createtoken->token->expires_at = carbon::now()->adddays(30); $createtoken->token->save(); $token = $createtoken->accesstoken; return response()->json([ 'access_token' => $token, 'token_type' => "bearer", 'expires_in' => carbon::now()->adddays(30), 'data' => $user, ], 200); } //我保存到又拍云了,版权归腾讯所有。。。头条闹的 private function avatarupyun($avatar) { $avatarfile = file_get_contents($avatar); $filename = 'avatars/' . uniqid() . '.png';//微信的头像链接我也不知道怎么获取后缀,直接保存成png的了 storage::disk('upyun')->write($filename, $avatarfile); $wexinavatar = config('filesystems.disks.upyun.protocol') . '://' . config('filesystems.disks.upyun.domain') . '/' . $filename; return $wexinavatar;//返回链接地址 }
微信的头像 / 0
小头像默认 / 132
4. 后端上面就写好了,再看下小程序端怎么做的哈,打开小程序的 app.json,添加 “pages/auth/auth”,
{ "pages": [ "pages/index/index", "pages/auth/auth",//做一个登录页面 "pages/logs/logs" ], "window": { "backgroundtextstyle": "light", "navigationbarbackgroundcolor": "#fff", "navigationbartitletext": "wechat", "navigationbartextstyle": "black" }, "sitemaplocation": "sitemap.json", "permission": { "scope.userlocation": { "desc": "你的位置信息将用于小程序位置接口的效果展示" } } }
5. 打开 auth.js
const app = getapp(); page({ /** * 页面的初始数据 */ data: { userdata: [], isclick: false, }, /** * 生命周期函数--监听页面加载 */ onload: function(options) { }, login: function(e) { let that=this that.setdata({ isclick: true }) wx.getuserinfo({ lang: "zh_cn", success: response => { wx.login({ success: res => { let data = { code:res.code, nickname: response.userinfo.nickname, avatar: response.userinfo.avatarurl, country: response.userinfo.country ? response.userinfo.country : '', province: response.userinfo.province ? response.userinfo.province : '', city: response.userinfo.city ? response.userinfo.city : '', gender: response.userinfo.gender ? response.userinfo.gender : '', language: response.userinfo.language ? response.userinfo.language : '', } console.log(data) app.globaldata.userinfo = data; wx.request({ url: '你的后端地址',//我用的valet,http://ak.name/api/v1/user/login method: 'post', data: data, header: { 'content-type': 'application/x-www-form-urlencoded' }, success: function (res) { console.log(res) if (res.statuscode != '200') { return false; } wx.setstoragesync('access_token', res.data.access_token) wx.setstoragesync('userdata', res.data.data ? res.data.data : '') wx.redirectto({ url: '/pages/index/index', }) }, fail: function (e) { wx.showtoast({ title: '服务器错误', duration: 2000 }); that.setdata({ isclick: false }) }, }); } }) }, fail: function (e) { that.setdata({ isclick: false }) }, }) } })
6. 打开 auth.wxml
<view class='padding-xl'> <button class='cu-btn margin-top bg-green shadow lg block' open-type="getuserinfo" bindgetuserinfo="login" disabled="{{isclick}}" type='success'> <text wx:if="{{isclick}}" class='cuicon-loading2 iconfont-spin'></text> 微信登录</button> </view>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。
黄山市民网:https://www.huangshanshimin.com/