lzj500 3 years ago
parent
commit
26a28dcc60

+ 4 - 0
d2-admin/src/views/demo/page1/index.vue

@@ -17,6 +17,10 @@ export default {
   created() {},
   methods: {
     async testQuery() {
+      let a = "b";
+      let b = "1";
+      if (a == b) {
+      }
       let res = await Demo.getInstance().getList();
       console.log(tagInfo, "res", res);
 

+ 48 - 0
thinkphp6/app/api/ErrorCode.php

@@ -0,0 +1,48 @@
+<?php
+
+
+namespace app\api;
+
+
+class ErrorCode
+{
+
+    const CODE_DB_ERROR = "9005";//数据库写入失败
+    const CODE_RECORD_NOT_FOUND = "9404";//记录未找到或已被删除0
+
+    /**
+     * 返回错误代内容
+     * @param $code
+     * @return mixed
+     */
+    public static function getError($code)
+    {
+        $errArr = self::getErrorArr();
+        if (!key_exists($code, $errArr)) {
+            return "未知错误";
+        }
+        return $errArr[$code];
+    }
+
+    /**
+     * 获取错误码数组
+     * @return array
+     */
+    protected static function getErrorArr()
+    {
+        return [
+            "0" => "成功",
+            //100以内,需要重新登录
+            "11" => "token过期",
+            "12" => "token不正确或已失效",
+            "13" => "缺少token",
+            "14" => "token格式不正确",
+            "9001" => "缺少签名",
+            "9002" => "签名不正确",
+            "9004" => "请求已过期",
+            self::CODE_DB_ERROR => "数据写入失败,请稍后再试",
+            self::CODE_RECORD_NOT_FOUND => "记录未找到或已被删除",
+            "9999" => "系统错误",
+        ];
+    }
+}

+ 16 - 0
thinkphp6/app/api/common.php

@@ -0,0 +1,16 @@
+<?php
+if (!function_exists('arrayToDic')) {
+    /**
+     * 数组转键值对数组
+     * @param $array
+     */
+    function arrayToDic($array,$keyName="value",$valueName="label"){
+        $dic=[];
+        foreach ($array as $key=>$value){
+            $item[$keyName]=$key;
+            $item[$valueName]=$value;
+            $dic[]=$item;
+        }
+        return $dic;
+    }
+}

+ 158 - 0
thinkphp6/app/api/controller/Base.php

@@ -0,0 +1,158 @@
+<?php
+
+
+namespace app\api\controller;
+
+
+
+
+use app\api\ErrorCode;
+
+use app\BaseController;
+use think\exception\HttpResponseException;
+use think\exception\ValidateException;
+use think\facade\Log;
+use think\Response;
+
+class Base
+{
+
+    protected $checkTokenOpen = false;
+
+
+    public function __construct()
+    {
+        Log::record("---------------------------","info");
+        Log::record($_SERVER['REQUEST_METHOD'] . '  ' . getUrl(), 'info');
+        Log::record('REFERER  ' .(array_key_exists('HTTP_REFERER',$_SERVER)?$_SERVER['HTTP_REFERER']:""), 'info');
+        Log::record('GET  ' . json_encode($_GET, JSON_UNESCAPED_UNICODE), 'info');
+        Log::record('POST  ' . json_encode($_POST, JSON_UNESCAPED_UNICODE), 'info');
+        Log::record('cookie  ' . json_encode($_COOKIE, JSON_UNESCAPED_UNICODE), 'info');
+        Log::record('input  ' . json_encode(input('param.'), JSON_UNESCAPED_UNICODE), 'info');
+        $this->checkApiSign();
+        if($this->checkTokenOpen){
+            $this->checkToken();
+        }
+    }
+
+
+
+    /**
+     * 获取token
+     * @return array|mixed|string|null
+     */
+    protected  function getToken(){
+        $token=null;
+        if(!$token){
+            //from header
+            $token=request()->header("token");
+        }
+        if(!$token){
+            //from url
+            $token=input("token");
+        }
+        return $token;
+    }
+
+    /**
+     * 检测token
+     * token规则
+     * token由base64编码,解码后分为密文、主键、过期时间(时间戳)三部分,用竖线|隔开
+     */
+    public function checkToken()
+    {
+        $token=$this->getToken();
+        if(!$token){
+            $this->error(ErrorCode::getError(13),13);
+        }
+        $tokerReal=base64_decode($token);
+        $tokenArr=explode("|",$tokerReal);//拆分token
+
+        if(count($tokenArr)!=3){
+            $this->error(ErrorCode::getError(14),14);
+        }
+        //判断token有没有超时
+        if(time()>$tokenArr[2]){
+            $this->error(ErrorCode::getError(11),11);
+        }
+        //以下部分根据自己的业务实现
+
+    }
+
+    /**
+     * 返回成功信息
+     * @param $data
+     * @param string $msg
+     */
+    public function success($data,$msg=""){
+
+        $res=returnFormat(0,$msg,$data);
+
+        Log::record("response:" . mb_substr(json_encode($res, JSON_UNESCAPED_UNICODE), 0, 1000) . ",code:0" , "debug");
+        throw new HttpResponseException(Response::create($res,"json"));
+    }
+
+    /**
+     * 简易错误提示
+     * @param $code
+     */
+    public function errorSimple($code){
+        $this->error(ErrorCode::getError($code),$code);
+    }
+
+    /**
+     * 返回失败信息
+     * @param $msg
+     * @param int $code
+     * @param array $data
+     */
+    public function error($msg,$code=999,$data=[]){
+        $res=returnFormat($code,$msg,$data);
+        Log::record("response:" . mb_substr(json_encode($res, JSON_UNESCAPED_UNICODE), 0, 1000) . ",code:" . $code, "debug");
+        throw new HttpResponseException(Response::create($res,"json"));
+    }
+
+    /**
+     * 自动校验
+     * @param $class
+     * @param $param
+     */
+    public function autoValid($class,$param){
+        try {
+            validate($class)->check($param);
+        } catch (ValidateException $e) {
+            // 验证失败 输出错误信息
+            $this->error($e->getError());
+        }
+    }
+
+    /**
+     * 检查签名
+     */
+    public function checkApiSign(){
+
+        $timestampLimit=20;
+        $param = request()->param();
+
+        $this->autoValid([
+            "_timestamp"=>"require",
+            "_sign"=>"require",
+        ], $param);
+        if(!($param["_timestamp"]>=time()-$timestampLimit*60 && $param["_timestamp"]<=time()+$timestampLimit*60)){
+            $this->error("时间戳不合法,请刷新");
+        }
+        $sign=$param["_sign"];
+        unset($param["_sign"]);
+        ksort($param);
+
+        $param['_timestamp'] = $param['_timestamp'];
+        $secret=config("common.api_sign_secret");
+        $signStr=stripslashes(json_encode($param,JSON_UNESCAPED_UNICODE).$secret);
+
+        $sign2=md5($signStr);
+
+        if($sign!==$sign2){
+            $this->error("签名错误。".$signStr);
+        }
+    }
+}

+ 16 - 0
thinkphp6/app/api/controller/BaseAuthorized.php

@@ -0,0 +1,16 @@
+<?php
+
+
+namespace app\api\controller;
+
+
+/**
+ * 需要登录 的基类
+ * Class AuthBase
+ * @package app\api\controller
+ */
+class BaseAuthorized extends Base
+{
+    protected $checkTokenOpen = true;
+
+}

+ 12 - 0
thinkphp6/app/api/controller/Index.php

@@ -0,0 +1,12 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\api\controller;
+
+class Index
+{
+    public function index()
+    {
+        return '您好!这是一个[api]示例应用';
+    }
+}

+ 5 - 0
thinkphp6/app/api/event.php

@@ -0,0 +1,5 @@
+<?php
+// 这是系统自动生成的event定义文件
+return [
+
+];

+ 5 - 0
thinkphp6/app/api/middleware.php

@@ -0,0 +1,5 @@
+<?php
+// 这是系统自动生成的middleware定义文件
+return [
+
+];

+ 179 - 23
thinkphp6/app/common.php

@@ -2,29 +2,7 @@
 // 应用公共文件
 
 
-if (!function_exists('getSiteUrl')) {
-    /**
-     * 获取当前站点的访问路径根目录
-     * @return [type] [description]
-     */
-    function getSiteUrl()
-    {
-        $uri = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
-        return 'http://' . $_SERVER['HTTP_HOST'] . substr($uri, 0, strrpos($uri, '/') + 1);
-    }
-}
-if (!function_exists('getVirRootDir')) {
-    /**
-     * 获取虚拟目录路径
-     * @return bool|string
-     */
-    function getVirRootDir()
-    {
-        $url = $_SERVER['SCRIPT_NAME'];
-        $url = substr($url, 0, strripos($url, "/") );
-        return $url;
-    }
-}
+
 
 if (!function_exists('returnFormat')) {
     /**
@@ -43,6 +21,39 @@ if (!function_exists('returnFormat')) {
 }
 
 
+
+
+
+if (!function_exists('each_item')) {
+    function each_item(&$array)
+    {
+        $res = array();
+        $key = key($array);
+        if ($key !== null) {
+            next($array);
+            $res[1] = $res['value'] = $array[$key];
+            $res[0] = $res['key'] = $key;
+        } else {
+            $res = false;
+        }
+        return $res;
+    }
+}
+
+if (!function_exists('getVirRootDir')) {
+    /**
+     * 获取虚拟目录路径
+     * @return bool|string
+     */
+    function getVirRootDir()
+    {
+        $url = $_SERVER['SCRIPT_NAME'];
+        $url = substr($url, 0, strripos($url, "/"));
+        return $url;
+    }
+}
+
+
 if (!function_exists('getNow')) {
     /**
      * 获取当时时间
@@ -54,3 +65,148 @@ if (!function_exists('getNow')) {
         return date($fmt);
     }
 }
+
+if (!function_exists('getUrl')) {
+    /**
+     * 获取当前的访问路径
+     * @return [type] [description]
+     */
+    function getUrl()
+    {
+        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
+        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
+        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
+        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
+        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
+    }
+}
+
+if(!function_exists('number2chinese')){
+
+    function number2chinese($num)
+    {
+        $arr = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
+        $cny = array('', '拾', '佰', '仟', '', '萬', '亿', '兆');
+        //小数部分
+        $retval = '';
+        if (strpos($num, '.') !== false) {
+            list($num, $dec) = explode('.', $num);
+            $retval .= $arr[$dec[0]] . '角' . $arr[$dec[1]] . '分';
+        }
+        //整数部分
+        $str = $num != '0' ? strrev($num) : '';
+        $out = array();
+        for ($i = 0; $i < strlen($str); $i++) {
+            $out[$i] = $arr[$str[$i]];
+            $out[$i] .= $str[$i] != '0' ? $cny[$i % 4] : '';
+            if ($i > 1 && $str[$i] + $str[$i - 1] == 0) {
+                $out[$i] = '';
+            }
+            if ($i % 4 == 0) {
+                $out[$i] .= $cny[4 + floor($i / 4)];
+            }
+            //echo $out[$i].'<br>';
+        }
+        $retval = implode('', array_reverse($out)) . '元' . $retval;
+        return $retval;
+    }
+}
+
+
+if (!function_exists('toUnderScore')) {
+    /**
+     * 驼峰命名转下划线命名
+     * 思路:
+     * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
+     * @param $camelCaps
+     * @param string $separator
+     * @return string
+     * @author web
+     */
+    function toUnderScore($camelCaps, $separator = '_')
+    {
+        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
+    }
+}
+
+
+if (!function_exists('convertUTF8')) {
+    /**
+     * 解决中文乱码的问题
+     * @param $str
+     * @return string
+     */
+    function convertUTF8($str)
+    {
+        if (empty($str)) return '';
+        return iconv('utf-8', 'gb2312', $str);
+    }
+}
+if (!function_exists('isIdCardNo')) {
+    /**
+     * 判断是否为合法的身份证号码
+     * @param $mobile
+     * @return int
+     */
+    function isIdCardNo($vStr)
+    {
+        $vCity = array(
+            '11', '12', '13', '14', '15', '21', '22',
+            '23', '31', '32', '33', '34', '35', '36',
+            '37', '41', '42', '43', '44', '45', '46',
+            '50', '51', '52', '53', '54', '61', '62',
+            '63', '64', '65', '71', '81', '82', '91'
+        );
+
+        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
+        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
+        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
+        $vLength = strlen($vStr);
+        if ($vLength == 18) {
+            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
+        } else {
+            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
+            return false;//不考虑一代身份证了
+        }
+        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
+        if ($vLength == 18) {
+            $vSum = 0;
+            for ($i = 17; $i >= 0; $i--) {
+                $vSubStr = substr($vStr, 17 - $i, 1);
+                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
+            }
+            if ($vSum % 11 != 1) return false;
+        }
+        return true;
+    }
+}
+if (!function_exists('cleanEnter')) {
+    /**
+     * 清除回车换行和前后空格
+     * @param $str
+     * @return array|string|string[]
+     */
+    function cleanEnter($str)
+    {
+        $str = trim($str);
+        $str = str_replace("\n", "", $str);
+        $str = str_replace("\r", "", $str);
+        return $str;
+    }
+}
+
+if (!function_exists('randNum')) {
+    /**
+     * 获取数字随机数
+     * @param $length 数字长度
+     * @return int
+     */
+    function randNum($length = 8)
+    {
+        $min = pow(10, $length-1) + 1;
+        $max = pow(10, $length ) - 1;
+        $rand = rand($min, $max);
+//        echo "length: $length, min: $min ,max: $max ,rand: $rand \r\n <br/>";
+        return $rand;
+    }
+}

+ 1 - 1
thinkphp6/app/index/controller/Base.php

@@ -22,7 +22,7 @@ use think\Response;
  */
 class Base extends \app\common\controller\Base
 {
-    private $apikey = "32a1ff74699ff2d6ce4c497cb94cb5c8";//密钥
+
 
 
     /**

+ 3 - 0
thinkphp6/app/index/controller/Demo.php

@@ -9,9 +9,12 @@
 namespace app\index\controller;
 
 
+use app\Request;
+
 class Demo extends Base
 {
     public function index(){
+        \think\Request::getIntance().
         $demoM=new \app\common\model\Demo();
         $res=$demoM->getList();
         if($res['code']>0){

+ 2 - 0
thinkphp6/app/middleware.php

@@ -7,4 +7,6 @@ return [
     // \think\middleware\LoadLangPack::class,
     // Session初始化
     // \think\middleware\SessionInit::class
+    //跨域请求
+    app\middleware\AllowCrossDomain::class
 ];

+ 66 - 0
thinkphp6/app/middleware/AllowCrossDomain.php

@@ -0,0 +1,66 @@
+<?php
+
+declare (strict_types=1);
+
+namespace app\middleware;
+
+use Closure;
+use think\Config;
+use think\Request;
+use think\Response;
+
+/**
+ * 跨域中间件
+ * Class AllowCrossDomain
+ * @package app\middleware
+ */
+class AllowCrossDomain
+{
+
+    protected $cookieDomain;
+
+    // header头配置
+    protected $header = [
+        "Access-Control-Allow-Origin" => "*",//注意修改这里填写你的前端的域名
+        'Access-Control-Allow-Credentials' => 'true',
+        'Access-Control-Max-Age' => 1800,
+        'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
+        'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,
+        ,content-type,ignore',
+    ];
+
+
+    /**
+     * AllowCrossDomain constructor.
+     * @param Config $config
+     */
+    public function __construct(Config $config)
+    {
+        $this->cookieDomain = $config->get('cookie.domain', '');
+    }
+
+    /**
+     * 允许跨域请求
+     * @access public
+     * @param Request $request
+     * @param Closure $next
+     * @param array $header
+     * @return Response
+     */
+    public function handle($request, Closure $next, ?array $header = [])
+    {
+        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
+
+        if (!isset($header['Access-Control-Allow-Origin'])) {
+            $origin = $request->header('origin');
+
+            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
+                $header['Access-Control-Allow-Origin'] = $origin;
+            } else {
+                $header['Access-Control-Allow-Origin'] = '*';
+            }
+        }
+
+        return $next($request)->header($header);
+    }
+}

+ 8 - 2
thinkphp6/config/common.php

@@ -1,4 +1,10 @@
 <?php
+/**
+ * Created by PhpStorm.
+ * User: Wang
+ * Date: 2020-09-07
+ * Time: 14:39
+ */
 return [
-    "api_sign_secret"=>"32a1ff74699ff2d6ce4c497cb94cb5c8",//接口签名秘钥
-];
+    "api_sign_secret"=>md5("api_sign_secret"),//接口签名秘钥
+];

+ 1 - 1
uniapp/config.js

@@ -1,5 +1,5 @@
 const config = {
-	host: "http://local.lzj/yckj_framework/thinkphp6/public/index.php", //请求地址
+	host: "http://qq.com", //请求地址
 	api_sign_key:"32a1ff74699ff2d6ce4c497cb94cb5c8",//接口签名参数
 };
 if (process.env.NODE_ENV === 'development') {