签名验证

<?php

namespace appappcontroller;

use appcommonapproveApprovehistory;
use thinkConfig;
use thinkController;

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;
    }

}
原文地址:https://www.cnblogs.com/zwtqf/p/10740357.html