日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

微信小程序前后端授权登陆

發布時間:2024/1/8 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 微信小程序前后端授权登陆 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文目錄

  • 一、微信小程序前端
    • 1.1 小程序前端準備
      • 1、api封裝
      • 2、授權獨立頁面
  • 二、微信小程序后端(laravel)
    • 2.1 小程序后端準備
      • 1、項目安裝dingo/api以及jwt認證
      • 2、創建小程序用戶表和模型
      • 3、安裝easywechat插件
      • 4、創建小程序授權登陸認證控制器
      • 5、授權登陸路由
  • 三、測試效果

一、微信小程序前端

1.1 小程序前端準備

由于用到了 weapp-vant所以還未安裝或者不懂安裝到可以參考我的這篇博客。

上微信公眾平臺注冊一個小程序,注冊完成之后你就有APPID和SECRET。

1、api封裝

根目錄下定義wxapi文件夾,我們將api請求獨立出來封裝,在wxapi文件夾下寫入request.js:

const requestObj = require('./request.config.js')requestObj.request = ({url,method,data = '',token = '' }) => {let _url = requestObj.API_BASE_URL + urlreturn new Promise((resolve, reject) => {wx.showLoading({title: '加載中...',})wx.request({url: _url,method: method,data,header: {// 'content-type': 'application/x-www-form-urlencoded','Content-Type': 'application/json','Authorization': 'Bearer ' + token},success(request) {console.log(request)if (request.data.code == 401) {wx.navigateTo({url: '/pages/authpage/authpage',})wx.showToast({title: '請重新登錄',icon: 'none'})}resolve(request.data)},fail(error) {reject(error)wx.navigateTo({url: '../networkerror/networkerror',})},complete() {// 加載完成wx.hideLoading()}})}) } /*** 小程序的promise擴展finally方法*/ Promise.prototype.finally = function (callback) {var Promise = this.constructor;return this.then(function (value) {Promise.resolve(callback()).then(function () {return value;});},function (reason) {Promise.resolve(callback()).then(function () {throw reason;});}); }module.exports = requestObj

我們將相關的配置寫入request.config.js(與request.js同層目錄):

const requestObj = {API_BASE_URL: 'http://jtminiprogramapi.com/api', // 小程序接口線上地址// API_BASE_URL: 'http://192.168.91.112:8085/', // 小程序接口線下地址 }module.exports = requestObj

再在wxapi文件夾創建api文件夾,里面寫我們各個模塊的apis,apis文件夾下寫入userApi.js(我們將用戶相關的接口全部寫在這這里只演示用戶登陸):

const requestObj = require('../request')let userApi = {/* 微信登錄獲取token */getToken: (data, method) => requestObj.request({url: '/wxlogin', method: method, data}),}module.exports = userApi;

在wxapi文件夾下寫入index.js:

const userApi = require('./apis/userApi'); module.exports = {userApi, }

api分模塊封裝完畢,它的目錄結構如下:


2、授權獨立頁面

微信開發者工具中寫入獨立授權頁面:
authpage.wxml:

<view class='headView'><open-data class='icon' mode="aspectFit" type="userAvatarUrl"></open-data><view class='icon'></view> </view> <view class="auth-btn"><button bindtap="getUserProfile">授權登錄</button> </view> <view class="cancel-btn" bindtap="cancelAuth">取消授權登錄</view> <van-toast id="van-toast" />

authpage.js:

import Toast from '@vant/weapp/toast/index'; const WXAPI = require('../../wxapi/index'); Page({/*** 頁面的初始數據*/data: {},// 點擊取消授權cancelAuth () {wx.switchTab({url: '../index/index'})},getUserProfile () {wx.getUserProfile({desc: '完善個人資料', // 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中,請謹慎填寫success: (newWes) => {let userInfo = newWes.userInfowx.setStorageSync('userInfo', newWes.userInfo)wx.login({success (res) {let code = res.codeif (code) {wx.showLoading({title: '加載中',})WXAPI.userApi.getToken({userInfo,code}, 'POST').then((res) => {console.log(res)wx.setStorageSync('authFlag', true)wx.setStorageSync('token', res.access_token)wx.navigateBack({delta: 1})}, (err) => {console.log(err)}).finally(() => {wx.hideLoading({})})}}})},fail: (err) => {console.log(err)}})},/*** 生命周期函數--監聽頁面加載*/onLoad: function (options) {},/*** 生命周期函數--監聽頁面初次渲染完成*/onReady: function () {},/*** 生命周期函數--監聽頁面顯示*/onShow: function () {},/*** 生命周期函數--監聽頁面隱藏*/onHide: function () {},/*** 生命周期函數--監聽頁面卸載*/onUnload: function () {},/*** 頁面相關事件處理函數--監聽用戶下拉動作*/onPullDownRefresh: function () {},/*** 頁面上拉觸底事件的處理函數*/onReachBottom: function () {},/*** 用戶點擊右上角分享*/onShareAppMessage: function () {} })

authpage.wxss:

.headView {display: flex;justify-content: center;align-items:center;margin-top: 50rpx;height:300rpx;width:750rpx;position:relative;margin-bottom: 50rpx;}/** *open-data 的頭像做不了圓角 *這里是覆蓋一個鏤空的view在上面 鏤空view的邊界做成與周圍背景顏色一樣 做了偽圓角 **/ .headView .icon {position: absolute;height: 200rpx;width: 200rpx;border-radius: 50%;border: 50rpx solid #f1f1f1; } .cancel-btn {display: block;margin-left: auto;margin-right: auto;padding-left: 14px;padding-right: 14px;box-sizing: border-box;font-size: 18px;text-align: center;text-decoration: none;line-height: 2.55555556;border-radius: 5px;-webkit-tap-highlight-color: transparent;overflow: hidden;cursor: pointer;color: #000;background-color: #f8f8f8;margin-top: 50rpx;padding: 8px 24px;line-height: 1.41176471;border-radius: 4px;font-weight: 700;font-size: 17px;width: 184px;margin-left: auto;margin-right: auto;position: relative; } .auth-btn {width: 184px;margin: 0 auto;height: 40px; } button {height: 100%;line-height: 40px;font-weight: normal;background-color: #546D7A;color: #fff; } button::after {border: none; } .cancel-btn {font-weight: normal; }

authpage.json:

{"usingComponents": {"van-toast": "@vant/weapp/toast/index"},"navigationBarTitleText": "授權登錄" }

二、微信小程序后端(laravel)

2.1 小程序后端準備

1、項目安裝dingo/api以及jwt認證

可以參考我的這篇文章。

2、創建小程序用戶表和模型

運行命令php artisan make:Model miniProgram/mpUser -m:

遷移文件寫入字段:

Schema::create('mp_users', function (Blueprint $table) {$table->id();$table->string('openid')->comment('用戶小程序唯一id');$table->string('nickname')->comment('用戶小程序昵稱');$table->string('avatar')->comment('用戶小程序頭像');$table->string('country')->comment('用戶小程序國家');$table->string('province')->comment('用戶小程序省份');$table->string('city')->comment('用戶小程序城市');$table->string('weixin_session_key')->comment('用戶登陸session');$table->string('gender')->comment('用戶性別: 1 -> 男,0 -> 女');$table->string('name')->nullable()->comment('用戶真實姓名');$table->string('email')->nullable()->comment('用戶郵箱');$table->timestamps();});


運行遷移命令php artisan migrate:


3、安裝easywechat插件

這個插件讓你更快的對接微信的接口。
運行命令composer require "overtrue/laravel-wechat:^6.0":


在中間件 App\Http\Middleware\VerifyCsrfToken 排除微信相關的路由:


運行命令php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"發布相關配置。
在config/wechat.php中將小程序的配置打開:

然后在.env文件下寫入:


4、創建小程序授權登陸認證控制器

運行命令php artisan make:controller Auth/mpAuthorizationsController:

寫入方法:

<?phpnamespace App\Http\Controllers\Auth;use App\Http\Controllers\Controller; use App\Models\miniProgram\mpUser; use GrahamCampbell\ResultType\Result; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log;class mpAuthorizationsController extends Controller {/*** name:SWT用戶登錄,小程序微信登錄*/public function store(Request $request){Log::debug($request->all());$code = $request->code;$nick_name = $request->userInfo['nickName'];$avatar = $request->userInfo['avatarUrl'];$gender = $request->userInfo['gender'];$country = $request->userInfo['country'];$province = $request->userInfo['province'];$city = $request->userInfo['city'];// 根據 code 獲取微信 openid 和 session_key$miniProgram = \EasyWeChat::miniProgram();$data = $miniProgram->auth->session($code);// 如果結果錯誤,說明 code 已過期或不正確,返回 401 錯誤if (isset($data['errcode'])) {return Result::fail('code不正確');}// 找到 openid 對應的用戶$userInfo = mpUser::where('openid', $data['openid'])->first();$attributes['weixin_session_key'] = $data['session_key'];if(!$userInfo){//更新用戶信息$userInfo = new mpUser();$userInfo->openid = $data['openid'];$userInfo->weixin_session_key = $data['session_key'];$userInfo->nickname = $nick_name;$userInfo->avatar = $avatar;$userInfo->gender = $gender;$userInfo->country = $country;$userInfo->province = $province;$userInfo->city = $city;$userInfo->save();}else{// 更新用戶數據$userInfo->update($attributes);}// 為對應用戶創建 JWT$token = auth('api')->login($userInfo);return $this->respondWithToken($token)->setStatusCode(201);}/*** Get the token array structure.** @param string $token** @return \Illuminate\Http\JsonResponse*/protected function respondWithToken($token){return response()->json(['status_code' => '1','msg' => '登陸成功!','access_token' => $token,'token_type' => 'Bearer','expires_in' => auth('api')->factory()->getTTL() * 60]);}}

5、授權登陸路由

routes/api.php:

<?phpuse App\Http\Controllers\Auth\mpAuthorizationsController;$api = app('Dingo\Api\Routing\Router');$api->version('v1', function ($api) {// 需要登陸的路由$api->group(['middleware' => 'api.auth'], function($api) {$api->get('users', [\App\Http\Controllers\TestController::class, 'users']);});// 執行登陸$api->any('wxlogin', [mpAuthorizationsController::class, 'store']); });

三、測試效果



小程序端已發送請求并且拿到了token。
接著我們去看下數據庫中是否有我們登陸小程序的用戶信息,以及需要和微信服務器打交道的session_key:

可以看到這邊我們相關的用戶信息基本都有了,頭像昵稱openid、session_key。

在學習實戰的路上,如果你覺得本文對你有所幫助的話,那就請關注點贊評論三連吧,謝謝,你的肯定是我寫博的另一個支持。

總結

以上是生活随笔為你收集整理的微信小程序前后端授权登陆的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。