Sign.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace app\txx\common;
  3. class Sign {
  4. private $appId = "";
  5. private $appKey = "";
  6. public function __construct(string $appId,string $appKey) {
  7. $this->appId=$appId;
  8. $this->appKey=$appKey;
  9. }
  10. //创建sign
  11. public function makeSign($data) {
  12. ksort($data);
  13. $string = $this->toUrlParams($data);
  14. $string = $string . "&key=" . $this->appKey;
  15. // \think\facade\Log::write("string:".$string,"info");
  16. $string = md5($string);
  17. $result = strtolower($string);
  18. return $result;
  19. }
  20. //检验sign是否正确
  21. public function verifySign($data) {
  22. //check sign
  23. if (!isset($data['sign']) || !$data['sign']) {
  24. return ['code'=>1,'msg'=>'发送的数据签名不存在'];
  25. }
  26. //check sign
  27. if (!isset($data['appid']) || !$data['appid']) {
  28. return ['code'=>1,'msg'=>'发送的应用参数不存在'];
  29. }
  30. if ($data['appid'] != $this->appId) {
  31. return ['code'=>1,'msg'=>'发送的应用参数错误'];
  32. }
  33. //check sign
  34. if (!isset($data['noce']) || !$data['noce']) {
  35. return ['code'=>1,'msg'=>'发送的应用参数不存在'];
  36. }
  37. //check timestamp
  38. if (!isset($data['timestamp']) || !$data['timestamp']) {
  39. return ['code'=>1,'msg'=>'发送的数据参数不合法'];
  40. }
  41. // 验证请求, 10分钟失效
  42. if (time() - $data['timestamp'] > 600) {
  43. return ['code'=>1,'msg'=>'验证超时, 请重新发送请求'];
  44. }
  45. $clientSign = $data['sign'];
  46. unset($data['sign']);
  47. $serverSign = $this->makeSign($data);
  48. // \think\facade\Log::write("string:".$serverSign."----".$clientSign,"info");
  49. if ($clientSign == $serverSign) {
  50. return ['code'=>0,'msg'=>'验证通过'];
  51. } else {
  52. return ['code'=>1,'msg'=>'请求不合法'];
  53. }
  54. }
  55. //生成url字符串
  56. private function toUrlParams($values){
  57. $buff = "";
  58. foreach ($values as $k => $v)
  59. {
  60. //&& $v != ""
  61. if($k != "sign" && !is_array($v)&& $v != ""){
  62. $buff .= $k . "=" .$v . "&";
  63. }
  64. }
  65. $buff = trim($buff, "&");
  66. return $buff;
  67. }
  68. }