簽名驗證

<?php

namespace app\app\controller;

use app\common\approve\Approvehistory;
use think\Config;
use think\Controller;

class Base extends Controller
{
    public function _initialize()
    {
        // 客戶端驗證簽名,除了帳密登錄,發送短信,短信接口驗證,其餘接口都須要驗證
        $arr = ['sendmsg','checkmsg','invitecodevalidate','wechatbind','wechatscan','getusercompany','choosecompany','mobilevalidate','editusermobile'];
        $action = request()->action();
        if (!in_array($action, $arr)) {
//            $this->verifyClient();
        }
    }

 
    /**
     * 客戶端驗證簽名
     */
    private function verifyClient()
    {
        //刪除用戶後不能在進行操做
        $uid = request()->header('uid');
        if (empty($uid)) return $this->api_result(['msg' => '登陸信息錯誤','flag' => false,'code' => 10001,'data' => 'nologin']);
        $result = db('user')
            ->field('expire_time,status,is_delete')
            ->where('id',$uid)
            ->find();
        if (empty($result['status']) || !empty($result['is_delete'])) return $this->api_result(['msg' => '您已被離職','flag' => false,'code' => 10001,'data' => 'nologin']);

        $key = "kindle_law";
        $post = request()->param();
        if (isset($post['signature'])) {
            $sign = $this->getSign($post, $key);
            if ($sign != substr($post['signature'], 0, -10)) {
                return $this->apiResult(['msg' => '簽名驗證失敗', 'code' => 10001]);
            } else {
                $time = substr($post['signature'], -10);
                $current_time = time();
                if (abs($current_time - $time) > 5) {
                    return $this->apiResult(['msg' => '無效簽名', 'code' => 10001]);
                }
            }
        } else {
            return $this->apiResult(['msg' => '缺乏簽名', 'code' => 10001]);
        }
    }

    /**
     * 獲取簽名
     */
    private function getSign($post, $key)
    {
        unset($post['signature']);
        ksort($post);
        $temp = [];
        foreach ($post as $k => $v) {
            $temp[] = $k;
        }
        $sign = sha1($key . implode("&", $temp));
        return $sign;
    }

}
相關文章
相關標籤/搜索