PHP code example of dsweixin / api-auth
1. Go to this page and download the library: Download dsweixin/api-auth library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dsweixin / api-auth example snippets
ApiAuth\ServiceProvider::class,
php artisan vendor:publish --provider="ApiAuth\ApiServiceProvider"
protected $routeMiddleware = [
'api_auth' => \App\Http\Middleware\ApiAuth::class,
// other ...
];
php artisan api_auth
'roles' => [
'{access_key}' => [
'name' => '{role_name}', // 角色名字,例如 android
'secret_key' => '{secret_key}',
],
],
/**
* @param $secret_key
* @param $echostr
* @param $timestamp
* @return string
*/
function encrypting($secret_key, $echostr, $timestamp) {
return md5($secret_key . $echostr . $timestamp);
}
/**
* @param $secret_key
* @param $signature
* @param $server_signature
* @return bool
*/
function rule($secret_key, $signature, $server_signature)
{
return $signature === $server_signature;
}
/**
* @param Request $request
* @param int $code
* @return \Illuminate\Http\JsonResponse
*/
public static function error_handler($msg , $status = 200)
{
$data = array(
"msg" => isset($msg) ? self::_lang($msg) : "参数错误",
"error" => $msg,
"data" => new \stdClass()
);
return response()->json($data, $status, ["Content-Type" => "application/json;charset=utf-8"]);
}
Route::get('api/example', function(Request $request){
// $request->get('client_role');
// todo...
})->middleware(['api_auth']);
\\ or
Route::group(['middleware'=>'api_auth'], function(){
// routes...
});
javascript
import axios from 'axios';
const access_key = '{access_key}'; // 服务端生成的 access_key
const secret_key = '{secret_key}'; // 服务端生成的 secret_key
const timestamp = Date.parse(new Date()) / 1000; // 取时间戳
const echostr = 'abcdef'; // 随机字符串自行生成
function encrypting(secret_key, echostr, timestamp){
return md5(secret_key + echostr + timestamp); // md5 库自行引入
}
const requestConfig = {
headers: {
"signature": encrypting(secret_key, echostr, timestamp),
"echostr": echostr,
"timestamp": timestamp,
"access-key": access_key
}
};
axios.post('/api/example',{},requestConfig).then(res=>{
// todo
});