cqp 10 mesi fa
parent
commit
8442a832d3

+ 18 - 0
app/Http/Controllers/Api/MayCurController.php

@@ -0,0 +1,18 @@
+<?php
+namespace App\Http\Controllers\Api;
+
+use App\Service\MayCurServerService;
+use Illuminate\Http\Request;
+
+class MayCurController extends BaseController
+{
+    public function getToken(Request $request){
+        list($bool, $data) = (new MayCurServerService())->getToken($request->all());
+
+        if($bool){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+}

+ 10 - 0
app/Providers/RouteServiceProvider.php

@@ -49,6 +49,8 @@ class RouteServiceProvider extends ServiceProvider
         $this->mapWeixinRoutes();
 
         $this->mapAssetApiRoutes();
+
+        $this->mapMaycurRoutes();
         //
     }
 
@@ -96,4 +98,12 @@ class RouteServiceProvider extends ServiceProvider
             ->namespace($this->namespace)
             ->group(base_path('routes/weixin.php'));
     }
+
+    protected function mapMaycurRoutes()
+    {
+        Route::prefix('maycur')
+            ->middleware('api')
+            ->namespace($this->namespace)
+            ->group(base_path('routes/maycur.php'));
+    }
 }

+ 136 - 0
app/Service/MayCurServerService.php

@@ -0,0 +1,136 @@
+<?php
+
+namespace App\Service;
+
+
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
+
+class MayCurServerService extends Service
+{
+    protected $param = "";
+    protected $domain_url = "";
+
+    public function __construct()
+    {
+        $this->param = config("maycur");
+        $this->domain_url = $this->param['zs_url'];
+    }
+
+    public function getToken($data){
+        //每刻所有配置
+        $url_array = $this->param;
+
+        //redis 存储的token
+        $key = $this->domain_url . $url_array['login_redis_topic'];
+        $token = Redis::get($key);
+        if(! empty($token))  return [true, json_decode($token,true)];
+
+        //获取token的参数
+        $appcode = env('maycur_appcode');
+        $appsercet = env('maycur_appsercet');
+        if(empty($appcode) || empty($appsercet)) return [false, '每刻鉴权认证参数不能为空'];
+
+        //组织获取参数
+        $url = $this->domain_url . $url_array['login'];
+        $time = microtime(true);
+        $timeStamp = round($time * 1000);
+        //生成secret
+        $secret = $this->getSecret($appcode, $appsercet, $timeStamp);
+
+        $post = [
+            "secret" => $secret,
+            "appCode" => $appcode,
+            "timestamp" => $timeStamp
+        ];
+        $header = ['Content-Type:application/json'];
+        list($status, $result) = $this->post_helper($url,$post, $header);
+        if(! $status) return [$status, $result];
+        if(empty($result['data']['entCode']) || empty($result['data']['tokenId'])) return [false, $result['message'] ?? '鉴权失败,请联系开发者'];
+
+        $token_array = [
+            'entCode' => $result['data']['entCode'],
+            'tokenId' => $result['data']['tokenId'],
+        ];
+        Redis::setex($key, $url_array['login_expire_time'], json_encode($token_array));
+
+        return [true, $token_array];
+    }
+
+    private function getSecret($appCode, $appSecret, $timeStamp) {
+        // 拼接字符串并计算 SHA-256 哈希值
+        $stringToHash = $appSecret . ":" . $appCode . ":" . $timeStamp;
+        $hashedString = hash('sha256', $stringToHash);
+
+        return $hashedString;
+    }
+
+    public function post_helper($url, $data, $header = [], $timeout = 20){
+        Log::channel('apiLog')->info('每刻POST', ["api" => $url , "param" => $data ,"header" => $header]);
+
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch,  CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_ENCODING, '');
+        curl_setopt($ch, CURLOPT_POST, 1);
+        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
+
+        if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
+        $r = curl_exec($ch);
+
+        if ($r === false) {
+            // 获取错误号
+            $errorNumber = curl_errno($ch);
+            // 获取错误信息
+            $errorMessage = curl_error($ch);
+            $message = "cURL Error #{$errorNumber}: {$errorMessage}";
+
+            Log::channel('apiLog')->info('每刻POST结果', ["message" => $message]);
+            return [false, $message];
+        }
+        curl_close($ch);
+
+        $return = json_decode($r, true);
+        Log::channel('apiLog')->info('每刻POST结果', ["message" => $return]);
+
+        return [true, $return];
+    }
+
+    public function get_helper($url,$header=[],$timeout = 20){
+        Log::channel('apiLog')->info('每刻GET', ["api" => $url ,"header" => $header]);
+        $ch = curl_init();
+        curl_setopt_array($ch, array(
+            CURLOPT_URL => $url,
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_ENCODING => '',
+            CURLOPT_MAXREDIRS => 10,
+            CURLOPT_TIMEOUT => $timeout,
+            CURLOPT_FOLLOWLOCATION => true,
+            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+            CURLOPT_CUSTOMREQUEST => 'GET',
+            CURLOPT_SSL_VERIFYPEER => false,
+            CURLOPT_HTTPHEADER => $header,
+        ));
+        $r = curl_exec($ch);
+
+        if ($r === false) {
+            // 获取错误号
+            $errorNumber = curl_errno($ch);
+            // 获取错误信息
+            $errorMessage = curl_error($ch);
+            $message = "cURL Error #{$errorNumber}: {$errorMessage}";
+            Log::channel('apiLog')->info('每刻GET', ["message" => $message]);
+            return [false, $message];
+        }
+
+        curl_close($ch);
+
+        $return = json_decode($r, true);
+        Log::channel('apiLog')->info('每刻GET', ["message" => $return]);
+
+        return [true, $return];
+    }
+}

+ 20 - 0
app/Service/Service.php

@@ -3,6 +3,8 @@
 namespace App\Service;
 
 
+use Illuminate\Support\Facades\Redis;
+
 /**
  * 公用的公共服务
  * @package App\Models
@@ -247,4 +249,22 @@ class Service
 
         return $formattedDate;
     }
+
+    //后台端 某些需要限制请求频率的接口
+    //需要主动删除  Redis::del($key)
+    public function limitingSendRequestBackgNeed($key,$value=0){
+        $prefix = config('app.name') . ':';
+        $key = $prefix . $key;
+        if(! empty($value)) $value = 1;
+        // 使用Redis Facade设置,当键名不存在时才设置成功
+        if (Redis::setnx($key, $value)) return [true, ''];
+
+        return [false,'操作频繁!'];
+    }
+
+    public function dellimitingSendRequestBackgNeed($key){
+        $prefix = config('app.name') . ':';
+        $key = $prefix . $key;
+        Redis::del($key);
+    }
 }

+ 1 - 1
config/cors.php

@@ -21,7 +21,7 @@ return [
      * You can enable CORS for 1 or multiple paths.
      * Example: ['api/*']
      */
-    'paths' => ['api/*','assetapi/*'],
+    'paths' => ['api/*','assetapi/*','maycur/*'],
 
     /*
     * Matches the request method. `[*]` allows all methods.

+ 14 - 0
config/maycur.php

@@ -0,0 +1,14 @@
+<?php
+//状态码
+return [
+    //测试
+    'cs_url' => 'https://ng-uat.maycur.com',
+    //正式
+    'zs_url' => 'https://ng.maycur.com',
+    //登录标识
+    'login_redis_topic' => 'MAYCURLOGIN',
+    //登录过期时间
+    'login_expire_time' => 1750, // 1800
+    //登录
+    'login' => '/api/openapi/auth/login',
+];

+ 0 - 30
phpunit.xml

@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
-         bootstrap="vendor/autoload.php"
-         colors="true">
-    <testsuites>
-        <testsuite name="Unit">
-            <directory suffix="Test.php">./tests/Unit</directory>
-        </testsuite>
-
-        <testsuite name="Feature">
-            <directory suffix="Test.php">./tests/Feature</directory>
-        </testsuite>
-    </testsuites>
-    <filter>
-        <whitelist processUncoveredFilesFromWhitelist="true">
-            <directory suffix=".php">./app</directory>
-        </whitelist>
-    </filter>
-    <php>
-        <server name="APP_ENV" value="testing"/>
-        <server name="BCRYPT_ROUNDS" value="4"/>
-        <server name="CACHE_DRIVER" value="array"/>
-        <server name="DB_CONNECTION" value="sqlite"/>
-        <server name="DB_DATABASE" value=":memory:"/>
-        <server name="MAIL_DRIVER" value="array"/>
-        <server name="QUEUE_CONNECTION" value="sync"/>
-        <server name="SESSION_DRIVER" value="array"/>
-    </php>
-</phpunit>

+ 20 - 0
routes/maycur.php

@@ -0,0 +1,20 @@
+<?php
+
+use Illuminate\Http\Request;
+
+/*
+|--------------------------------------------------------------------------
+| API Routes
+|--------------------------------------------------------------------------
+|
+| Here is where you can register API routes for your application. These
+| routes are loaded by the RouteServiceProvider within a group which
+| is assigned the "api" middleware group. Enjoy building your API!
+|
+*/
+
+Route::middleware('auth:api')->get('/user', function (Request $request) {
+    return $request->user();
+});
+
+Route::any('getToken', 'Api\MayCurController@getToken');