Laravel 微信小程序后端实现用户登录的示例代码


Posted in PHP onNovember 26, 2019

接上篇微信小程序后端搭建:分享: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

Laravel 微信小程序后端实现用户登录的示例代码

小头像默认 / 132

Laravel 微信小程序后端实现用户登录的示例代码

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
php购物网站支付paypal使用方法
Nov 28 PHP
php max_execution_time执行时间问题
Jul 17 PHP
PHP中usort在值相同时改变原始位置问题的解决方法
Nov 27 PHP
thinkphp项目如何自定义微信分享描述内容
Feb 20 PHP
PHP读取CSV大文件导入数据库的实例
Jul 24 PHP
PHP+Redis 消息队列 实现高并发下注册人数统计的实例
Jan 29 PHP
PHP依赖注入原理与用法分析
Aug 21 PHP
浅谈PHP无限极分类原理
Mar 14 PHP
PHP时间函数使用详解
Mar 21 PHP
CentOS7编译安装php7.1的教程详解
Apr 18 PHP
Laravel第三方包报class not found的解决方法
Oct 13 PHP
PHP后门隐藏的一些技巧总结
Nov 04 PHP
Laravel 微信小程序后端搭建步骤详解
Nov 26 #PHP
php 使用expat方式解析xml文件操作示例
Nov 26 #PHP
thinkphp框架类库扩展操作示例
Nov 26 #PHP
如何在Laravel5.8中正确地应用Repository设计模式
Nov 26 #PHP
PHP 进程池与轮询调度算法实现多任务的示例代码
Nov 26 #PHP
PHP PDO和消息队列的个人理解与应用实例分析
Nov 25 #PHP
Laravel Eloquent分表方法并使用模型关联的实现
Nov 25 #PHP
You might like
PHP 选项及相关信息函数库
2006/12/04 PHP
基于PHP编程注意事项的小结
2013/04/27 PHP
基于Zend的Captcha机制的应用
2013/05/02 PHP
PHP微信公众号开发之微信红包实现方法分析
2017/07/14 PHP
php微信公众号开发之简答题
2018/10/20 PHP
PHP ob缓存以及ob函数原理实例解析
2020/11/13 PHP
Aster vs Newbee BO5 第二场2.19
2021/03/10 DOTA
jQuery 通过事件委派一次绑定多种事件,以减少事件冗余
2010/06/30 Javascript
编写自己的jQuery提示框(Tip)插件
2015/02/05 Javascript
jQuery实现文本展开收缩特效
2015/06/03 Javascript
jqueryMobile使用示例分享
2016/01/12 Javascript
Angularjs中使用Filters详解
2016/03/11 Javascript
checkbox批量选中,获取选中项的值的简单实例
2016/06/28 Javascript
Vue 2.5 Level E 发布了: 新功能特性一览
2017/10/24 Javascript
详解封装基础的angular4的request请求方法
2018/06/05 Javascript
vue模块移动组件的实现示例
2020/05/20 Javascript
Python自定义线程池实现方法分析
2018/02/07 Python
Python内置模块ConfigParser实现配置读写功能的方法
2018/02/12 Python
python中abs&amp;map&amp;reduce简介
2018/02/20 Python
Python实现输出某区间范围内全部素数的方法
2018/05/02 Python
Python中的取模运算方法
2018/11/10 Python
python实现kmp算法的实例代码
2019/04/03 Python
python实现简单日期工具类
2019/04/24 Python
利用Pandas和Numpy按时间戳将数据以Groupby方式分组
2019/07/22 Python
Python aiohttp百万并发极限测试实例分析
2019/10/26 Python
2021年值得向Python开发者推荐的VS Code扩展插件
2021/01/25 Python
AE美国鹰美国官方网站:American Eagle Outfitters
2016/08/22 全球购物
介绍一下Cookie和Session及他们之间的区别
2012/11/20 面试题
酒店服务与管理毕业生求职信
2013/11/02 职场文书
公司市场部岗位职责
2013/12/02 职场文书
《最佳路径》教学反思
2014/04/13 职场文书
2014年作风建设剖析材料
2014/10/23 职场文书
2015年度员工自我评价范文
2015/03/11 职场文书
2015教师个人工作总结范文
2015/03/31 职场文书
致三级跳运动员加油稿
2015/07/21 职场文书
立秋之描写立秋的作文(五年级)
2019/08/08 职场文书