审查视图

application/common/controller/Api.php 12.9 KB
王智 authored
1 2 3
<?php

namespace app\common\controller;
王智 authored
4
王智 authored
5
use EasyWeChat\Foundation\Application;
王智 authored
6 7 8 9 10 11 12 13 14 15 16
use app\common\library\Auth;
use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
王智 authored
17
use think\Db;
王智 authored
18
王智 authored
19
//use EasyWeChat\Factory;
王智 authored
20
王智 authored
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        //跨域请求检测
        check_cors_request();

        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), null, 401);
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'), null, 403);
                }
            }
        } else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name = Loader::parseName($name);
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
王智 authored
162 163 164 165 166
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码,默认为1
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
王智 authored
167 168 169 170 171 172 173 174
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
王智 authored
175 176 177 178 179
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码,默认为0
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
王智 authored
180 181 182 183 184 185 186 187 188
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
王智 authored
189 190 191 192 193
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码,默认为0
     * @param string $type 输出类型,支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
王智 authored
194 195 196 197 198 199 200
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
王智 authored
201
            'msg' => $msg,
王智 authored
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
王智 authored
222 223
     * @param string $method 前置操作方法名
     * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
王智 authored
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
王智 authored
265
     * @param array $data 数据
王智 authored
266
     * @param string|array $validate 验证器名或者验证规则数组
王智 authored
267 268 269
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @param mixed $callback 回调方法(闭包)
王智 authored
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }
        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }

    /**
     * 刷新Token
     */
    protected function token()
    {
        $token = $this->request->param('__token__');

        //验证Token
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
            $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }
王智 authored
328 329 330 331 332

    //检查Token
    protected function IsToken($token)
    {
        if (empty($token['token'])) {
王智 authored
333
            $this->error('请登录后在操作', '', 401);
王智 authored
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        }
        $is_token = Db::name('user')->where(['token' => $token['token']])->find();
        if (!$is_token) {
            $this->error('登陆已过期,请重新登陆');
        }
        return $is_token['id'];
    }

    //接收全部参数
    public function MyParams()
    {
        $params = $this->request->param();
        unset($params['applyinstCode']);
        unset($params['verifyMobilePhone']);
        return $params;
    }

    //Res
    public function Res($res)
    {
        if ($res) {
            $this->success('成功', 1);
        } else {
            $this->error('失败', 0);
        }
    }

    //验证申请是否唯一
    public function OnlySeller($UserId)
    {
        $SellerArr = Db::name('seller')->where('user_id', $UserId)->find();
        if (!empty($SellerArr)) {
            $this->error('重复申请', 0);
        }
    }
王智 authored
369 370 371 372 373

    //订单号生成
    public function order_sn()
    {
        @date_default_timezone_set("PRC");
王智 authored
374
        $order_id_main = date('YmdHis') . rand(10000, 99999);
王智 authored
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码(YYYYMMDDHHIISSNNNNNNNNCC)
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }

    //生成支付单号
    public function PayOrder()
    {
        //生成订单号
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $PayOrder = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $PayOrder;
    }
王智 authored
394 395 396 397


    public function Tuikuan($OrderSn)
    {
王智 authored
398 399 400 401 402 403 404 405
        $PayOrderInfo = Db::name('pay_order')->where('OrderSn', $OrderSn)->where('type', 1)->find();
        $TuiMoney = $PayOrderInfo['UpMoney'] + $PayOrderInfo['Money'];
        //配置
        $config = [
            'app_id' => 'wx6a9080f20326f817',
            'payment' => [
                'merchant_id' => '1603658973',
                'key' => '8695A8185xyzKcdEVfreewayShenzhen',
王智 authored
406 407
                'cert_path' => '/home/wwwroot/fast/kcd/addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径!!!!
                'key_path' => '/home/wwwroot/fast/kcd/addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径!!!!
王智 authored
408 409
            ],
        ];
王智 authored
410 411
        $app = new Application($config);
        $payment = $app->payment;
王智 authored
412
        try {
王智 authored
413
            $result = $payment->refundByTransactionId($PayOrderInfo['WeChatOrder'], $PayOrderInfo['PayOrder'], $PayOrderInfo['money'] * 100, $TuiMoney); // 总金额 100, 退款 80,操作员:商户号
王智 authored
414 415 416 417 418 419 420 421 422 423
            //更改订单状态为已退款
            Db::name('pay_order')->where('OrderSn', $OrderSn)->where('PayOrder', $PayOrderInfo['PayOrder'])->update(['type' => 0]);
        } catch (Exception $e) {
            $e->getMessage();
        }
        if (!$result) {
            $this->error('退款失败', 0);
            die;
        }
    }
王智 authored
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441


    /**
     * 生成名片二维码
     */
    function NameCarQrCode($ImageName, $url = '')
    {
        Vendor('phpqrcode.phpqrcode');
        $value = $url;                    //二维码内容
        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 2;            //生成图片大小
        $time = time();
        //生成二维码图片
        $path = "images/";
        $fileName = $path . $ImageName . '.png';
        $qr1 = new \QRcode();
        $qr1::png($value, $fileName, $errorCorrectionLevel, $matrixPointSize, 2);
    }
王智 authored
442
}