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 读取文件的正确方法
Apr 29 PHP
Memcached常用命令以及使用说明详解
Jun 27 PHP
为PHP安装imagick时出现Cannot locate header file MagickWand.h错误的解决方法
Nov 03 PHP
php有道翻译api调用方法实例
Dec 22 PHP
php中关于socket的系列函数总结
May 18 PHP
[原创]php逐行读取txt文件写入数组的方法
Jul 02 PHP
php上传大文件失败的原因及应对策略
Oct 20 PHP
PHP实现四种基础排序算法的运行时间比较(推荐)
Aug 11 PHP
php中文字符串截取多种方法汇总
Oct 06 PHP
phpfpm的作用和用法
Oct 10 PHP
thinkphp5 + ajax 使用formdata提交数据(包括文件上传) 后台返回json完整实例
Mar 02 PHP
WordPress多语言翻译插件 - WPML使用教程
Apr 01 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
使用phpQuery采集网页的方法
2013/11/13 PHP
PHP源码分析之变量的存储过程分解
2014/07/03 PHP
全面解析PHP操作Memcache基本函数
2016/07/14 PHP
Laravel学习教程之View模块详解
2017/09/18 PHP
jQuery 表单验证扩展(四)
2010/10/20 Javascript
js/jQuery对象互转(快速操作dom元素)
2013/02/04 Javascript
node.js学习总结之调式代码的方法
2014/06/25 Javascript
JavaSciprt中处理字符串之sup()方法的使用教程
2015/06/08 Javascript
JS封装的选项卡TAB切换效果示例
2016/09/20 Javascript
使用vue.js编写蓝色拼图小游戏
2017/03/17 Javascript
JavaScript requestAnimationFrame动画详解
2017/09/14 Javascript
微信小程序获取手机网络状态的方法【附源码下载】
2017/12/08 Javascript
详解封装基础的angular4的request请求方法
2018/06/05 Javascript
vue 使用html2canvas将DOM转化为图片的方法
2018/09/11 Javascript
vue-cli 3.0 版本与3.0以下版本在搭建项目时的区别详解
2018/12/11 Javascript
Vue2(三)实现子菜单展开收缩,带动画效果实现方法
2019/04/28 Javascript
Vue打包后访问静态资源路径问题
2019/11/08 Javascript
解决echarts vue数据更新,视图不更新问题(echarts嵌在vue弹框中)
2020/07/20 Javascript
JS变量提升及函数提升实例解析
2020/09/03 Javascript
Python标准库urllib2的一些使用细节总结
2015/03/16 Python
使用C语言来扩展Python程序和Zope服务器的教程
2015/04/14 Python
详解使用Python处理文件目录的相关方法
2015/10/16 Python
Python读取csv文件实例解析
2019/12/30 Python
python从内存地址上加载python对象过程详解
2020/01/08 Python
解决pycharm中导入自己写的.py函数出错问题
2020/02/12 Python
python使用梯度下降和牛顿法寻找Rosenbrock函数最小值实例
2020/04/02 Python
美国孕妇装购物网站:Motherhood Maternity
2019/09/22 全球购物
P/Invoke是什么
2015/07/31 面试题
普师专业个人自荐信范文
2013/11/26 职场文书
法学专业大学生实习自我鉴定
2014/10/05 职场文书
辞职信如何写
2015/02/27 职场文书
看上去很美观后感
2015/06/10 职场文书
与死神共舞观后感
2015/06/15 职场文书
2016年第29个世界无烟日宣传活动总结
2016/04/06 职场文书
python基础之爬虫入门
2021/05/10 Python
MySQL中JOIN连接的基本用法实例
2022/06/05 MySQL