php接口签名服务

<?php
/**
 * Created by PhpStorm.
 * User: zrj
 * Date: 18-10-11
 * Time: 上午11:44
 */

namespace App\Http\Services;

trait SignatureService
{
    public static $requestParamArr = [];

    /**
     * 初始化服务
     * @param array $requestParamArr
     * @return mixed
     */
    public static function init(array $requestParamArr)
    {
        self::$requestParamArr = $requestParamArr;
    }

    /**
     * 校验请求参数
     * @param array $requestParamArr
     * @param bool $isInit
     * @return array
     */
    public static function validateQueryParam(array $requestParamArr = [], bool $isInit = true): array
    {
        try {
            if (empty($requestParamArr)) {
                $requestParamArr = self::$requestParamArr;
            }

            if (!isset($requestParamArr['sign_type'])) throw new \Exception('缺少签名类型参数');
            if (!in_array($requestParamArr['sign_type'], ['MD5', 'HMAC-SHA256'])) throw new \Exception('签名类型错误');
            if (!isset($requestParamArr['timestamp'])) throw new \Exception('缺少时间戳参数');
            if (empty($requestParamArr['timestamp'])) throw new \Exception('时间戳不能为空');
            if (!isset($requestParamArr['nonce_str'])) throw new \Exception('缺少随机字符串参数');
            if (empty($requestParamArr['nonce_str'])) throw new \Exception('随机字符串不能为空');

            if (!$isInit) {
                if (!isset($requestParamArr['key'])) throw new \Exception('缺少密钥参数');
                if (empty($requestParamArr['key'])) throw new \Exception('密钥不能为空');
                if (!isset($requestParamArr['signature'])) throw new \Exception('缺少签名参数');
                if (empty($requestParamArr['signature'])) throw new \Exception('签名不能为空');
            }

            return ['status' => 1, 'data' => [], 'message' => ''];
        } catch (\Exception $e) {
            return ['status' => 0, 'data' => [], 'message' => $e->getMessage()];
        }
    }

    /**
     * 产生随机字符串,不长于32位
     * @param int $length
     * @return string
     */
    public static function createNonceStr(int $length = 32): string
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 产生请求参数的排序后的字符串
     * @param array $requestParamArr
     * @return string
     */
    public static function createSortQueryString(array $requestParamArr): string
    {
        if (isset($requestParamArr['key'])) unset($requestParamArr['key']);
        if (isset($requestParamArr['signature'])) unset($requestParamArr['signature']);

        ksort($requestParamArr);
        return http_build_query($requestParamArr);
    }

    /**
     * 创建签名串
     * @param string $sortQueryString 排序字符串
     * @param string $signType 签名类型:MD5;HMAC-SHA256;
     * @param string $key
     * @return string
     * @throws \Exception
     */
    public static function createSignatureString(string $sortQueryString, string $signType, string $key): string
    {
        $returnStr = '';
        if ($signType == 'MD5') {
            $sortQueryString .= '&key=' . $key;
            $returnStr = md5($sortQueryString);
        } elseif ($signType == 'HMAC-SHA256') {
            $returnStr = hash_hmac('sha256', $sortQueryString, $key);
        } else {
            throw new \Exception('签名类型不支持');
        }
        return $returnStr;
    }

    /**
     * 验证外部请求
     * @param array $originRequestParamArr
     * @return array
     */
    public static function validateRequest(array $originRequestParamArr): array
    {
        try {
            $validate = self::validateQueryParam($originRequestParamArr, false);
            if (!$validate['status']) throw new \Exception($validate['message']);
            $now = time();
            if (($now - $originRequestParamArr['timestamp']) > 15) throw new \Exception('请求时间异常');

            $signType = $originRequestParamArr['sign_type'];
            $originKey = $originRequestParamArr['key'];
            $originSignature = $originRequestParamArr['signature'];
            unset($originRequestParamArr['key'], $originRequestParamArr['signature']);

            $newSignature = self::createSignatureString(self::createSortQueryString($originRequestParamArr), $signType, $originKey);
            if ($originSignature != $newSignature) throw new \Exception('签名错误');

            return ['status' => 1, 'data' => [], 'message' => ''];
        } catch (\Exception $e) {
            return ['status' => 0, 'data' => [], 'message' => $e->getMessage()];
        }
    }
}

使用

创新互联主要从事网站设计制作、做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务郯城,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108

//生成签名
$request = [
                'a' => 1,
                'b' => 2,
                'c' => 3,

                'sign_type' => 'HMAC-SHA256',
                'timestamp' => time() + 600,
                'nonce_str' => SignatureService::createNonceStr(),
        ];

            SignatureService::init($request);

            $result = SignatureService::validateQueryParam();

            if (!$result['status']) exit($result['message']);

            $key = 'helloworld';
            $signature = SignatureService::createSignatureString(SignatureService::createSortQueryString($request), $request['sign_type'], $key);
            $request['key'] = $key;
            $request['signature'] = $signature;

            echo "<pre>";
            print_r($request);

            //校验签名
            $validate = SignatureService::validateRequest($request, false);

必要参数:

  • 'sign_type' => 'HMAC-SHA256', //签名类型,当前支持SHA256、MD5
  • 'timestamp' => '1539255134', //时间戳
  • 'nonce_str' => 'n5ryqp0f9ur3u3u8lxfblxw9h03emyka',//随机数
  • 'key' => 'helloworld', //密钥
  • 'signature' => 'f0ca487612f15059c47aba5e8503c6400981fbed20d1af958003e3f798d1bbd2',//签名

当前名称:php接口签名服务
本文来源:https://www.cdcxhl.com/article32/geohsc.html

成都网站建设公司_创新互联,为您提供动态网站网站排名营销型网站建设外贸建站域名注册网页设计公司

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都定制网站网页设计