1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace app\txx\common;
- class Sign {
- private $appId = "";
- private $appKey = "";
- public function __construct(string $appId,string $appKey) {
- $this->appId=$appId;
- $this->appKey=$appKey;
- }
- //创建sign
- public function makeSign($data) {
- ksort($data);
- $string = $this->toUrlParams($data);
- $string = $string . "&key=" . $this->appKey;
- $string = md5($string);
- $result = strtolower($string);
- return $result;
- }
- //检验sign是否正确
- public function verifySign($data) {
- //check sign
- if (!isset($data['sign']) || !$data['sign']) {
- return ['code'=>1,'msg'=>'发送的数据签名不存在'];
- }
- //check sign
- if (!isset($data['appid']) || !$data['appid']) {
- return ['code'=>1,'msg'=>'发送的应用参数不存在'];
- }
- if ($data['appid'] != $this->appId) {
- return ['code'=>1,'msg'=>'发送的应用参数错误'];
- }
- //check sign
- if (!isset($data['noce']) || !$data['noce']) {
- return ['code'=>1,'msg'=>'发送的应用参数不存在'];
- }
- //check timestamp
- if (!isset($data['timestamp']) || !$data['timestamp']) {
- return ['code'=>1,'msg'=>'发送的数据参数不合法'];
- }
- // 验证请求, 10分钟失效
- if (time() - $data['timestamp'] > 600) {
- return ['code'=>1,'msg'=>'验证超时, 请重新发送请求'];
- }
- $clientSign = $data['sign'];
- unset($data['sign']);
- $serverSign = $this->makeSign($data);
- if ($clientSign == $serverSign) {
- return ['code'=>0,'msg'=>'验证通过'];
- } else {
- return ['code'=>1,'msg'=>'请求不合法'];
- }
- }
- //生成url字符串
- private function toUrlParams($values){
- $buff = "";
- foreach ($values as $k => $v)
- {
- //&& $v != ""
- if($k != "sign" && !is_array($v)&& $v != ""){
- $buff .= $k . "=" .$v . "&";
- }
- }
- $buff = trim($buff, "&");
- return $buff;
- }
- }
|