Sign.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. $string = md5($string);
  16. $result = strtolower($string);
  17. return $result;
  18. }
  19. //检验sign是否正确
  20. public function verifySign($data) {
  21. //check sign
  22. if (!isset($data['sign']) || !$data['sign']) {
  23. return ['code'=>1,'msg'=>'发送的数据签名不存在'];
  24. }
  25. //check sign
  26. if (!isset($data['appid']) || !$data['appid']) {
  27. return ['code'=>1,'msg'=>'发送的应用参数不存在'];
  28. }
  29. if ($data['appid'] != $this->appId) {
  30. return ['code'=>1,'msg'=>'发送的应用参数错误'];
  31. }
  32. //check sign
  33. if (!isset($data['noce']) || !$data['noce']) {
  34. return ['code'=>1,'msg'=>'发送的应用参数不存在'];
  35. }
  36. //check timestamp
  37. if (!isset($data['timestamp']) || !$data['timestamp']) {
  38. return ['code'=>1,'msg'=>'发送的数据参数不合法'];
  39. }
  40. // 验证请求, 10分钟失效
  41. if (time() - $data['timestamp'] > 600) {
  42. return ['code'=>1,'msg'=>'验证超时, 请重新发送请求'];
  43. }
  44. $clientSign = $data['sign'];
  45. unset($data['sign']);
  46. $serverSign = $this->makeSign($data);
  47. if ($clientSign == $serverSign) {
  48. return ['code'=>0,'msg'=>'验证通过'];
  49. } else {
  50. return ['code'=>1,'msg'=>'请求不合法'];
  51. }
  52. }
  53. //生成url字符串
  54. private function toUrlParams($values){
  55. $buff = "";
  56. foreach ($values as $k => $v)
  57. {
  58. //&& $v != ""
  59. if($k != "sign" && !is_array($v)&& $v != ""){
  60. $buff .= $k . "=" .$v . "&";
  61. }
  62. }
  63. $buff = trim($buff, "&");
  64. return $buff;
  65. }
  66. }