濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > Laravel 微信小程序后端實(shí)現(xiàn)用戶(hù)登錄的示例代碼

Laravel 微信小程序后端實(shí)現(xiàn)用戶(hù)登錄的示例代碼

熱門(mén)標(biāo)簽:泊頭在哪里辦理400電話(huà) 江門(mén)回?fù)芡夂粝到y(tǒng) 江西電銷(xiāo)機(jī)器人收費(fèi) 高德地圖標(biāo)注位置怎么標(biāo)注 電銷(xiāo)機(jī)器人沒(méi)有效果怎么樣 天潤(rùn)融通外呼系統(tǒng)好嗎 杭州語(yǔ)音電銷(xiāo)機(jī)器人 欣思維地圖標(biāo)注 高德地圖標(biāo)注店鋪收費(fèi)嗎

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

后端搭建好后第一件事就是用戶(hù)登錄認(rèn)證,簡(jiǎn)單實(shí)現(xiàn)微信小程序登錄認(rèn)證

1.user 模型

use Laravel\Passport\HasApiTokens; 新增

use HasApiTokens, Notifiable;

protected $fillable = [
 'id',
 'name',
 'email',
 'email_verified_at',
 'username',
 'phone',
 'avatar',//我用來(lái)把微信頭像的/0清晰圖片,存到又拍云上
 'weapp_openid',
 'nickname',
 'weapp_avatar',
 'country',
 'province',
 'city',
 'language',
 'location',
 'gender',
 'level',//用戶(hù)等級(jí)
 'is_admin',//is管理員
];

2. 新增一條路由

//前端小程序拿到的地址:https://域名/api/v1/自己寫(xiě)的接口
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;

寫(xiě)兩個(gè) function weappLogin (),avatarUpyun ()

public function weappLogin(Request $request)
  {
    $code = $request->code;
    // 根據(jù) code 獲取微信 openid 和 session_key
    $miniProgram = \EasyWeChat::miniProgram();
    $data = $miniProgram->auth->session($code);
    if (isset($data['errcode'])) {
      return $this->response->errorUnauthorized('code已過(guò)期或不正確');
    }
    $weappOpenid = $data['openid'];
    $weixinSessionKey = $data['session_key'];
    $nickname = $request->nickname;
    $avatar = str_replace('/132', '/0', $request->avatar);//拿到分辨率高點(diǎn)的頭像
    $country = $request->country?$request->country:'';
    $province = $request->province?$request->province:'';
    $city = $request->city?$request->city:'';
    $gender = $request->gender == '1' ? '1' : '2';//沒(méi)傳過(guò)性別的就默認(rèn)女的吧,體驗(yàn)好些
    $language = $request->language?$request->language:'';

    //找到 openid 對(duì)應(yīng)的用戶(hù)
    $user = User::where('weapp_openid', $weappOpenid)->first();
    //沒(méi)有,就注冊(cè)一個(gè)用戶(hù)
    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,
      ]);
    }
    //如果注冊(cè)過(guò)的,就更新下下面的信息
    $attributes['updated_at'] = now();
    $attributes['weixin_session_key'] = $weixinSessionKey;
    $attributes['weapp_avatar'] = $avatar;
    if ($nickname) {
      $attributes['nickname'] = $nickname;
    }
    if ($request->gender) {
      $attributes['gender'] = $gender;
    }
    // 更新用戶(hù)數(shù)據(jù)
    $user->update($attributes);
    // 直接創(chuàng)建token并設(shè)置有效期
    $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);
  }

  //我保存到又拍云了,版權(quán)歸騰訊所有。。。頭條鬧的
  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

小頭像默認(rèn) / 132

4. 后端上面就寫(xiě)好了,再看下小程序端怎么做的哈,打開(kāi)小程序的 app.json,添加 "pages/auth/auth",

{
 "pages": [
  "pages/index/index",
  "pages/auth/auth",//做一個(gè)登錄頁(yè)面
  "pages/logs/logs"
 ],
 "window": {
  "backgroundTextStyle": "light",
  "navigationBarBackgroundColor": "#fff",
  "navigationBarTitleText": "WeChat",
  "navigationBarTextStyle": "black"
 },
 "sitemapLocation": "sitemap.json",
 "permission": {
  "scope.userLocation": {
   "desc": "你的位置信息將用于小程序位置接口的效果展示"
  }
 }
}

5. 打開(kāi) auth.js

const app = getApp();
Page({
 /**
  * 頁(yè)面的初始數(shù)據(jù)
  */
 data: {
  UserData: [],
  isClick: false,
 },
 /**
  * 生命周期函數(shù)--監(jiān)聽(tīng)頁(yè)面加載
  */
 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: '服務(wù)器錯(cuò)誤',
         duration: 2000
        });
        that.setData({
         isClick: false
        })
       },
      });
     }
    })
   },
   fail: function (e) {
    that.setData({
     isClick: false
    })
   },
  })

 }
})

6. 打開(kāi) 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>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • laravel 解決強(qiáng)制跳轉(zhuǎn) https的問(wèn)題
  • Laravel重定向,a鏈接跳轉(zhuǎn),控制器跳轉(zhuǎn)示例
  • Laravel 5.4重新登錄實(shí)現(xiàn)跳轉(zhuǎn)到登錄前頁(yè)面的原理和方法
  • laravel利用中間件防止未登錄用戶(hù)直接訪(fǎng)問(wèn)后臺(tái)的方法
  • Laravel 自帶的Auth驗(yàn)證登錄方法
  • Laravel實(shí)現(xiàn)登錄跳轉(zhuǎn)功能

標(biāo)簽:深圳 內(nèi)江 駐馬店 雙鴨山 江門(mén) 石嘴山 大同

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Laravel 微信小程序后端實(shí)現(xiàn)用戶(hù)登錄的示例代碼》,本文關(guān)鍵詞  Laravel,微信,小,程序,后端,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Laravel 微信小程序后端實(shí)現(xiàn)用戶(hù)登錄的示例代碼》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于Laravel 微信小程序后端實(shí)現(xiàn)用戶(hù)登錄的示例代碼的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    南阳市| 威信县| 西宁市| 四平市| 宝应县| 濉溪县| 收藏| 文山县| 醴陵市| 绥化市| 丰原市| 中江县| 勃利县| 达尔| 德兴市| 景泰县| 淳安县| 闻喜县| 安阳县| 民丰县| 通榆县| 日喀则市| 启东市| 璧山县| 奈曼旗| 牡丹江市| 贺州市| 芒康县| 成都市| 商城县| 石狮市| 蒙城县| 额敏县| 邹平县| 耿马| 古丈县| 汝阳县| 德惠市| 仙桃市| 昌平区| 东阳市|