您好,登錄后才能下訂單哦!
<?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()];
}
}
}
使用
//生成簽名
$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',//簽名
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。