当前位置:首页 > CMS教程 > 其它CMS > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2022-01-24 14:21:46 浏览: 评论:0 

这篇文章主要介绍了Laravel 微信小程序后端实现用户登录的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

接上篇微信小程序后端搭建:分享:Laravel 微信小程序后端搭建

后端搭建好后第一件事就是用户登录认证,简单实现微信小程序登录认证

1.user 模型

use Laravel\Passport\HasApiTokens; 新增

  1. use HasApiTokens, Notifiable; 
  2.  
  3. protected $fillable = [ 
  4.  'id'
  5.  'name'
  6.  'email'
  7.  'email_verified_at'
  8.  'username'
  9.  'phone'
  10.  'avatar',//我用来把微信头像的/0清晰图片,存到又拍云上 
  11.  'weapp_openid'
  12.  'nickname'
  13.  'weapp_avatar'
  14.  'country'
  15.  'province'
  16.  'city'
  17.  'language'
  18.  'location'
  19.  'gender'
  20.  'level',//用户等级 
  21.  'is_admin',//is管理员 
  22. ]; 

2. 新增一条路由

  1. //前端小程序拿到的地址:https://域名/api/v1/自己写的接口 
  2. Route::group(['prefix' => '/v1'], function () { 
  3.   Route::post('/user/login''UserController@weappLogin'); 
  4. }); 

3. 在 UserController 控制器里新建 function weappLogin (),别忘了 use 这些

  1. use App\User; 
  2. use Carbon\Carbon; 
  3. use Illuminate\Http\Request; 
  4. use Illuminate\Support\Facades\Storage; 

写两个 function weappLogin (),avatarUpyun ()

  1. public function weappLogin(Request $request
  2.   { 
  3.     $code = $request->code; 
  4.     // 根据 code 获取微信 openid 和 session_key 
  5.     $miniProgram = \EasyWeChat::miniProgram(); 
  6.     $data = $miniProgram->auth->session($code); 
  7.     if (isset($data['errcode'])) { 
  8.       return $this->response->errorUnauthorized('code已过期或不正确'); 
  9.     } 
  10.     $weappOpenid = $data['openid']; 
  11.     $weixinSessionKey = $data['session_key']; 
  12.     $nickname = $request->nickname; 
  13.     $avatar = str_replace('/132''/0'$request->avatar);//拿到分辨率高点的头像 
  14.     $country = $request->country?$request->country:''
  15.     $province = $request->province?$request->province:''
  16.     $city = $request->city?$request->city:''
  17.     $gender = $request->gender == '1' ? '1' : '2';//没传过性别的就默认女的吧,体验好些 
  18.     $language = $request->language?$request->language:''
  19.  
  20.     //找到 openid 对应的用户 
  21.     $user = User::where('weapp_openid'$weappOpenid)->first(); 
  22.     //没有,就注册一个用户 
  23.     if (!$user) { 
  24.       $user = User::create([ 
  25.         'weapp_openid' => $weappOpenid
  26.         'weapp_session_key' => $weixinSessionKey
  27.         'password' => $weixinSessionKey
  28.         'avatar' => $request->avatar?$this->avatarUpyun($avatar):''
  29.         'weapp_avatar' => $avatar
  30.         'nickname' => $nickname
  31.         'country' => $country
  32.         'province' => $province
  33.         'city' => $city
  34.         'gender' => $gender
  35.         'language' => $language
  36.       ]); 
  37.     } 
  38.     //如果注册过的,就更新下下面的信息 
  39.     $attributes['updated_at'] = now(); 
  40.     $attributes['weixin_session_key'] = $weixinSessionKey
  41.     $attributes['weapp_avatar'] = $avatar
  42.     if ($nickname) { 
  43.       $attributes['nickname'] = $nickname
  44.     } 
  45.     if ($request->gender) { 
  46.       $attributes['gender'] = $gender
  47.     } 
  48.     // 更新用户数据 
  49.     $user->update($attributes); 
  50.     // 直接创建token并设置有效期 
  51.     $createToken = $user->createToken($user->weapp_openid); 
  52.     $createToken->token->expires_at = Carbon::now()->addDays(30); 
  53.     $createToken->token->save(); 
  54.     $token = $createToken->accessToken; 
  55.  
  56.     return response()->json([ 
  57.       'access_token' => $token
  58.       'token_type' => "Bearer"
  59.       'expires_in' => Carbon::now()->addDays(30), 
  60.       'data' => $user
  61.     ], 200); 
  62.   } 
  63.  
  64.   //我保存到又拍云了,版权归腾讯所有。。。头条闹的 
  65.   private function avatarUpyun($avatar
  66.   { 
  67.     $avatarfile = file_get_contents($avatar); 
  68.     $filename = 'avatars/' . uniqid() . '.png';//微信的头像链接我也不知道怎么获取后缀,直接保存成png的了 
  69.     Storage::disk('upyun')->write($filename$avatarfile); 
  70.     $wexinavatar = config('filesystems.disks.upyun.protocol') . '://' . config('filesystems.disks.upyun.domain') . '/' . $filename
  71.     return $wexinavatar;//返回链接地址 
  72.   } 

微信的头像 / 0

Laravel微信小程序 Laravel用户登录

小头像默认 / 132

Laravel微信小程序 Laravel用户登录

4. 后端上面就写好了,再看下小程序端怎么做的哈,打开小程序的 app.json,添加 "pages/auth/auth",

  1.  "pages": [ 
  2.   "pages/index/index"
  3.   "pages/auth/auth",//做一个登录页面 
  4.   "pages/logs/logs" 
  5.  ], 
  6.  "window": { 
  7.   "backgroundTextStyle""light"
  8.   "navigationBarBackgroundColor""#fff"
  9.   "navigationBarTitleText""WeChat"
  10.   "navigationBarTextStyle""black" 
  11.  }, 
  12.  "sitemapLocation""sitemap.json"
  13.  "permission": { 
  14.   "scope.userLocation": { 
  15.    "desc""你的位置信息将用于小程序位置接口的效果展示" 
  16.   } 
  17.  } 

5. 打开 auth.js

  1. const app = getApp(); 
  2. Page({ 
  3.  /** 
  4.   * 页面的初始数据 
  5.   */ 
  6.  data: { 
  7.   UserData: [], 
  8.   isClick: false
  9.  }, 
  10.  /** 
  11.   * 生命周期函数--监听页面加载 
  12.   */ 
  13.  onLoad: function(options) { 
  14.  
  15.  }, 
  16.  login: function(e) { 
  17.   let that=this 
  18.   that.setData({ 
  19.    isClick: true 
  20.   }) 
  21.   wx.getUserInfo({ 
  22.    lang: "zh_CN"
  23.    success: response => { 
  24.     wx.login({ 
  25.      success: res => { 
  26.       let data = { 
  27.        code:res.code, 
  28.        nickname: response.userInfo.nickName, 
  29.        avatar: response.userInfo.avatarUrl, 
  30.        country: response.userInfo.country ? response.userInfo.country : ''
  31.        province: response.userInfo.province ? response.userInfo.province : ''
  32.        city: response.userInfo.city ? response.userInfo.city : ''
  33.        gender: response.userInfo.gender ? response.userInfo.gender : ''
  34.        language: response.userInfo.language ? response.userInfo.language : ''
  35.       } 
  36.       console.log(data) 
  37.       app.globalData.userInfo = data; 
  38.       wx.request({ 
  39.        url: '你的后端地址',//我用的valet,http://ak.name/api/v1/user/login 
  40.        method: 'POST'
  41.        data: data, 
  42.        header: { 
  43.         'Content-Type''application/x-www-form-urlencoded' 
  44.        }, 
  45.        success: function (res) { 
  46.         console.log(res) 
  47.         if (res.statusCode != '200') { 
  48.          return false
  49.         } 
  50.         wx.setStorageSync('access_token', res.data.access_token) 
  51.         wx.setStorageSync('UserData', res.data.data ? res.data.data : ''
  52.         wx.redirectTo({ 
  53.          url: '/pages/index/index'
  54.         }) 
  55.        }, 
  56.        fail: function (e) { 
  57.         wx.showToast({ 
  58.          title: '服务器错误'
  59.          duration: 2000 
  60.         }); 
  61.         that.setData({ 
  62.          isClick: false 
  63.         }) 
  64.        }, 
  65.       }); 
  66.      } 
  67.     }) 
  68.    }, 
  69.    fail: function (e) { 
  70.     that.setData({ 
  71.      isClick: false 
  72.     }) 
  73.    }, 
  74.   }) 
  75.  
  76.  } 
  77. }) 

6. 打开 auth.wxml

  1. <view class='padding-xl'> 
  2.  <button class='cu-btn margin-top bg-green shadow lg block' open-type="getUserInfo" bindgetuserinfo="login" disabled="{{isClick}}" type='success'> 
  3.   <text wx:if="{{isClick}}" class='cuIcon-loading2 iconfont-spin'></text> 微信登录</button> 
  4. </view>

Tags: Laravel小程序 Laravel用户登录

分享到: