後臺管理員認證 (admins表)
首先建立資料庫和表(admins),在 routes/api.php
中,寫上如下路由並建立對應控制器和方法。
Route::namespace('Api')->group(function () {
/***
* 管理員後臺介面路由
*/
Route::prefix('admin')->namespace('Admin')->group(function () {
Route::post('register', 'AdminController@register');
Route::post('login', 'AdminController@login');
});
Route::prefix('admin')->namespace('Admin')->group(function () {
Route::get('/', 'HomeController@index'); //後臺首頁
});
});
1、安裝 jwt-auth
composer require tymon/jwt-auth:dev-develop
2、在 config/app.php
中註冊服務提供者
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
3、生成配置檔案
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
此命令會在 config
目錄下生成一個 jwt.php
配置檔案
4、生成金鑰
php artisan jwt:secret
此命令會在你的 .env
檔案中新增一行 JWT_SECRET=secret
5、建立 admins
表遷移檔案
php artisan make:migration create_admins_table
新增如下程式碼:
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
執行遷移:
php artisan migrate
此時檢視資料庫,對應的 admins
表已生成。
6、建立模型
由於我們這裡後臺管理員設定的是 admins
表,所以需建立對應模型,執行如下命令:
php artisan make:model Models/Admin
裡面新增如下程式碼:
<?php
namespace App\Models;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
7、配置 Auth guard
在 config/auth.php
檔案中,新增 guard
和 Providers
,程式碼如下:
'admins' => [
'driver' => 'jwt',
'provider' => 'admins'
]
*************************
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
]
8、在 AdminController
中新增如下程式碼:
<?php
namespace App\Http\Controllers\Api\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Hash;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth:admins', ['except' => ['register', 'login']]);
}
/***
* 後臺管理員註冊
* @param Request $request
*/
public function register(Request $request)
{
$name = $request->name;
$email = $request->email;
$password = $request->password;
$check_password = $request->check_password;
if (!$name || !$password) {
return response()->json(['success' => false, 'message' => '使用者名稱、郵箱或密碼必填!']);
}
$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
if (!preg_match($pattern, $email)) {
return response()->json(['success' => false, 'message' => '郵箱格式不正確!']);
}
if ($check_password != $password) {
return response()->json(['success' => false, 'message' => '兩次密碼輸入不一致!']);
}
$admin = Admin::where('name', $name)->first();
if ($admin) {
return response()->json(['success' => false, 'message' => '使用者名稱已被註冊!']);
}
$password = Hash::make($password);
$admin = Admin::create([
'name' => $name,
'email' => $email,
'password' => $password
]);
return response()->json(['success' => true, 'message' => '註冊成功!', 'admin' => $admin]);
}
/***
* 後臺管理員登入
* @param Request $request
*/
public function login(Request $request)
{
$email = $request->email;
$password = $request->password;
if (!$email || !$password) {
return response()->json(['success' => false, 'message' => '郵箱或密碼填寫錯誤!']);
}
$admin = Admin::where('email', $email)->first();
if (!$admin) {
return response()->json(['success' => false, 'message' => '此郵箱不存在!']);
}
if (!Hash::check($password, $admin->password)) {
return response()->json(['success' => false, 'message' => '密碼填寫錯誤!']);
}
$credentials = request(['email', 'password']);
if (!$token = auth('admins')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Log the admin out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth('admins')->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
'expires_in' => auth('admins')->factory()->getTTL() * 60
]);
}
}
測試:
先註冊一個後臺賬號,在postman
中,如圖所示:
9、使用中介軟體,修改之前的路由如下:
Route::namespace('Api')->group(function () {
/***
* 管理員後臺介面路由
*/
Route::prefix('admin')->namespace('Admin')->group(function () {
Route::post('register', 'AdminController@register');
Route::post('login', 'AdminController@login');
});
Route::prefix('admin')->namespace('Admin')->middleware('auth:admins')->group(function () {
Route::get('/', 'HomeController@index'); //後臺首頁
});
});
測試:
實現登入,在postman
中,如圖所示:
12、獲取管理員資訊,在後臺首頁控制器中寫入如下程式碼:
public function index()
{
return response()->json(auth('admins')->user());
}
至此,後臺介面認證已完成!
商戶後臺認證 (merchants表)
這裡的商戶後臺認證其實是重複上面的步驟,只是換了一張表而已,所以自行完成!
小程式前端使用者認證 (users表)
1、在 api.php
中新增路由並建立對應控制器和方法,users
表增加欄位 openid
/***
* 小程式使用者認證介面路由
*/
Route::any('/auth', 'MiniController@auth');
2、在 config/auth.php
檔案中,修改 guard
裡面的 api
那欄,程式碼如下:
'users' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
3、修改模型 User.php
程式碼如下:
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'openid'
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
4、使用中介軟體,修改之前的路由如下:
/***
* 小程式使用者認證介面路由
*/
Route::any('/auth', 'MiniController@auth');
Route::middleware('auth:users')->group(function () {
Route::get('/', 'HomeController@index'); //首頁介面
});
5、安裝 easyWeChat
第三方包
composer require "overtrue/laravel-wechat:~5.0" #安裝包檔案
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider" #生成配置檔案
開啟配置檔案 wechat.php
裡面的小程式配置和支付配置,在 .env
檔案中配置支付的相關引數,如下:
WECHAT_MINI_PROGRAM_APPID=*******
WECHAT_MINI_PROGRAM_SECRET=*******
WECHAT_PAYMENT_MCH_ID=*******
WECHAT_PAYMENT_APPID=*******
WECHAT_PAYMENT_KEY=*******
6、在 MiniController
控制器中新增如下程式碼:
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use JWTAuth;
use EasyWeChat;
use Auth;
class MiniController extends Controller
{
public function auth(Request $request)
{
$app = EasyWeChat::miniProgram();
$session = $app->auth->session($request->code);
$openid = $session['openid'];
// return $openid;
//用openid查詢資料庫,是否已經有了,沒有就建立。
$user = User::firstOrCreate(compact('openid'));
//生成token
$token = JWTAuth::fromUser($user);
return response()->json(['token' => 'Bearer ' . $token]);
}
}
7、建立一個小程式測試專案,在 app.js
中,刷出 code
。然後 postman
測試如圖:
8、最後一步獲取小程式使用者 id
。在首頁介面控制器中寫入如下程式碼,用來列印小程式使用者的 openid
public function index()
{
return response()->json(auth('users')->user()->openid);
}