您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關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>
感謝各位的閱讀!關于“Laravel、微信小程序后端如何實現用戶登錄”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。