Commit de75d67a by lujunyi

小程序登录示例,搭建小程序api基础结构

parent 7ded0420
<?php
namespace App\Api\Controllers;
use App\Http\Controllers\BaseApiController;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends BaseApiController
{
public function userInfo()
{
$userId = auth('api')->user()->id;
$data = ['abcde' => 111, 'role' => '问诊人', 'id' => $userId];
return $this->success($data);
}
// 小程序静默登录,如果没有记录则生成一条
public function login(Request $request)
{
$code = $request->input('code');
$credentials = app('wechat.mini_program')->auth->session($code);
if ($credentials['openid'] ?? '') {
$user = User::firstOrCreate(['miniapp_openid', $credentials['openid']]);
$token = auth('api')->claims(['role' => '问诊人'])->fromUser($user);
// $data = $this->respondWithToken($token)->original;
$data = ['token' => $token];
return $this->success($data);
} else {
return $this->fail('登录错误~');
}
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth('api')->logout();
return response()->json(['message' => '退出成功~']);
}
/**
* Refresh a token.
* 刷新token,如果开启黑名单,以前的token便会失效。
* 值得注意的是用上面的getToken再获取一次Token并不算做刷新,两次获得的Token是并行的,即两个都可用。
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth('api')->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('api')->factory()->getTTL() * 60,
]);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
class BaseApiController extends Controller
{
/**
* 返回成功信息
*
* @param mixed $data
*/
public function success($data = [], string $message = 'success', int $code = Response::HTTP_OK): \Illuminate\Http\JsonResponse
{
return response()->json(['status' => true, 'code' => $code, 'message' => $message, 'data' => $data]);
}
/**
* 返回失败信息
*
* @param bool $status
*/
public function failed($data = [], string $message = 'fail', int $code = Response::HTTP_INTERNAL_SERVER_ERROR): \Illuminate\Http\JsonResponse
{
return response()->json(['status' => false, 'code' => $code, 'message' => $message, 'data' => $data]);
}
}
...@@ -12,6 +12,6 @@ class VerifyCsrfToken extends Middleware ...@@ -12,6 +12,6 @@ class VerifyCsrfToken extends Middleware
* @var array<int, string> * @var array<int, string>
*/ */
protected $except = [ protected $except = [
// 'wechat',
]; ];
} }
...@@ -7,8 +7,9 @@ ...@@ -7,8 +7,9 @@
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable class User extends Authenticatable implements JWTSubject
{ {
use HasApiTokens, HasFactory, Notifiable; use HasApiTokens, HasFactory, Notifiable;
...@@ -42,4 +43,25 @@ class User extends Authenticatable ...@@ -42,4 +43,25 @@ class User extends Authenticatable
'email_verified_at' => 'datetime', 'email_verified_at' => 'datetime',
'password' => 'hashed', 'password' => 'hashed',
]; ];
// 下面是jwt-aut必须要实现的方法
/**
* 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 [];
}
} }
...@@ -17,8 +17,10 @@ ...@@ -17,8 +17,10 @@
"laravel/tinker": "^2.8", "laravel/tinker": "^2.8",
"overtrue/laravel-filesystem-cos": "^3.5", "overtrue/laravel-filesystem-cos": "^3.5",
"overtrue/laravel-query-logger": "^3.1", "overtrue/laravel-query-logger": "^3.1",
"overtrue/laravel-wechat": "^6.0",
"predis/predis": "^2.2", "predis/predis": "^2.2",
"sparkinzy/dcat-viewer": "^1.0" "sparkinzy/dcat-viewer": "^1.0",
"tymon/jwt-auth": "^2.1"
}, },
"require-dev": { "require-dev": {
"barryvdh/laravel-ide-helper": "^2.13", "barryvdh/laravel-ide-helper": "^2.13",
...@@ -98,7 +100,8 @@ ...@@ -98,7 +100,8 @@
"preferred-install": "dist", "preferred-install": "dist",
"sort-packages": true, "sort-packages": true,
"allow-plugins": { "allow-plugins": {
"pestphp/pest-plugin": true "pestphp/pest-plugin": true,
"easywechat-composer/easywechat-composer": true
} }
}, },
"minimum-stability": "dev", "minimum-stability": "dev",
......
...@@ -40,6 +40,11 @@ ...@@ -40,6 +40,11 @@
'driver' => 'session', 'driver' => 'session',
'provider' => 'users', 'provider' => 'users',
], ],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
], ],
/* /*
......
This diff is collapsed. Click to expand it.
<?php
/*
* This file is part of the overtrue/laravel-wechat.
*
* (c) overtrue <i@overtrue.me>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
return [
/*
* 默认配置,将会合并到各模块中
*/
'defaults' => [
/*
* 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
*/
'response_type' => 'array',
/*
* 使用 Laravel 的缓存系统
*/
'use_laravel_cache' => true,
/**
* 日志配置
*
* level: 日志级别, 可选为:
* debug/info/notice/warning/error/critical/alert/emergency
* path:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'default' => env('APP_DEBUG', false) ? 'dev' : 'prod', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'single',
'path' => storage_path('logs/wechat.log'),
'level' => 'debug',
],
// 生产环境
'prod' => [
'driver' => 'daily',
'path' => storage_path('logs/wechat.log'),
'level' => 'debug',
],
],
],
],
/*
* 路由配置
*/
'route' => [
/*
* 开放平台第三方平台路由配置
*/
// 'open_platform' => [
// 'uri' => 'serve',
// 'action' => Overtrue\LaravelWeChat\Controllers\OpenPlatformController::class,
// 'attributes' => [
// 'prefix' => 'open-platform',
// 'middleware' => null,
// ],
// ],
],
/*
* 公众号
*/
'official_account' => [
'default' => [
'app_id' => env('WECHAT_OFFICIAL_ACCOUNT_APPID', 'your-app-id'), // AppID
'secret' => env('WECHAT_OFFICIAL_ACCOUNT_SECRET', 'your-app-secret'), // AppSecret
'token' => env('WECHAT_OFFICIAL_ACCOUNT_TOKEN', 'your-token'), // Token
'aes_key' => env('WECHAT_OFFICIAL_ACCOUNT_AES_KEY', ''), // EncodingAESKey
/*
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址(如果使用中间件,则随便填写。。。)
* enforce_https:是否强制使用 HTTPS 跳转
*/
// 'oauth' => [
// 'scopes' => array_map('trim', explode(',', env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_SCOPES', 'snsapi_userinfo'))),
// 'callback' => env('WECHAT_OFFICIAL_ACCOUNT_OAUTH_CALLBACK', '/examples/oauth_callback.php'),
// 'enforce_https' => true,
// ],
],
],
/*
* 开放平台第三方平台
*/
// 'open_platform' => [
// 'default' => [
// 'app_id' => env('WECHAT_OPEN_PLATFORM_APPID', ''),
// 'secret' => env('WECHAT_OPEN_PLATFORM_SECRET', ''),
// 'token' => env('WECHAT_OPEN_PLATFORM_TOKEN', ''),
// 'aes_key' => env('WECHAT_OPEN_PLATFORM_AES_KEY', ''),
// ],
// ],
/*
* 小程序
*/
'mini_program' => [
'default' => [
'app_id' => env('WECHAT_MINI_PROGRAM_APPID', ''),
'secret' => env('WECHAT_MINI_PROGRAM_SECRET', ''),
'token' => env('WECHAT_MINI_PROGRAM_TOKEN', ''),
'aes_key' => env('WECHAT_MINI_PROGRAM_AES_KEY', ''),
],
],
/*
* 微信支付
*/
// 'payment' => [
// 'default' => [
// 'sandbox' => env('WECHAT_PAYMENT_SANDBOX', false),
// 'app_id' => env('WECHAT_PAYMENT_APPID', ''),
// 'mch_id' => env('WECHAT_PAYMENT_MCH_ID', 'your-mch-id'),
// 'key' => env('WECHAT_PAYMENT_KEY', 'key-for-signature'),
// 'cert_path' => env('WECHAT_PAYMENT_CERT_PATH', 'path/to/cert/apiclient_cert.pem'), // XXX: 绝对路径!!!!
// 'key_path' => env('WECHAT_PAYMENT_KEY_PATH', 'path/to/cert/apiclient_key.pem'), // XXX: 绝对路径!!!!
// 'notify_url' => 'http://example.com/payments/wechat-notify', // 默认支付结果通知地址
// ],
// // ...
// ],
/*
* 企业微信
*/
// 'work' => [
// 'default' => [
// 'corp_id' => 'xxxxxxxxxxxxxxxxx',
// 'agent_id' => 100020,
// 'secret' => env('WECHAT_WORK_AGENT_CONTACTS_SECRET', ''),
// //...
// ],
// ],
];
...@@ -14,6 +14,16 @@ ...@@ -14,6 +14,16 @@
| |
*/ */
Route::middleware('auth:sanctum')->get('/user', function (Request $request) { // Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user(); // return $request->user();
// });
// 不需要登录的组
// 小程序静默登录
Route::post('login', 'App\Api\Controllers\UserController@login');
// 需要验证是否登录的路由组
Route::middleware(['jwt.auth'])->group(function () {
// 获取用户信息
Route::get('/users', 'App\Api\Controllers\UserController@userInfo');
}); });
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment