BackendToFrontendApi.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * 内部API助手类
  4. * Created by PhpStorm.
  5. * User: Ming
  6. * Date: 2018/3/13
  7. * Time: 10:21
  8. */
  9. namespace common\helpers\http;
  10. use common\helpers\Date;
  11. use Yii;
  12. class BackendToFrontendApi {
  13. /**
  14. * 通讯密钥
  15. */
  16. const AUTH_KEY = '';
  17. /**
  18. * 允许的时间差(秒)
  19. */
  20. const TIME_DIFF = '';
  21. /**
  22. * 请求方法
  23. */
  24. const HTTP_METHOD_POST = 'post';
  25. const HTTP_METHOD_GET = 'get';
  26. /**
  27. * 返回成功的标记
  28. */
  29. const RETURN_SUCCESS = 'success';
  30. /**
  31. * http client
  32. * @var null
  33. */
  34. /**
  35. * http response
  36. * @var null
  37. */
  38. protected static $response = null;
  39. /**
  40. * 获取密钥
  41. * @return string
  42. */
  43. public static function getAuthKey(){
  44. if(self::AUTH_KEY === ''){
  45. return Yii::$app->params['http']['backendToFrontendApi']['authKey'];
  46. }
  47. return self::AUTH_KEY;
  48. }
  49. /**
  50. * 获取允许的时间差
  51. * @return string
  52. */
  53. public static function getTimeDiff(){
  54. if(self::TIME_DIFF === ''){
  55. return Yii::$app->params['http']['backendToFrontendApi']['timeDiff'];
  56. }
  57. return self::TIME_DIFF;
  58. }
  59. /**
  60. * 生成签名
  61. * @param array $params
  62. * @return array
  63. */
  64. public static function paramsFormat(array $params){
  65. if(!isset($params['timestamp'])){
  66. $params['timestamp'] = time();
  67. }
  68. if(isset($params['signature'])){
  69. unset($params['signature']);
  70. }
  71. ksort($params);
  72. $string = '';
  73. foreach($params as $key=>$value){
  74. $string .= $key.'='.$value . '&';
  75. }
  76. $params['signature'] = sha1(trim($string,'&') . self::getAuthKey());
  77. return $params;
  78. }
  79. /**
  80. * 验证签名
  81. * @param $signature
  82. * @param array $params
  83. * @return bool
  84. */
  85. public static function checkSignature($signature, array $params){
  86. $params = self::paramsFormat($params);
  87. if($params['signature'] !== $signature){
  88. return false;
  89. }
  90. $timeDiff = (int)self::getTimeDiff();
  91. if($timeDiff > 0 && (Date::nowTime() - $params['timestamp']) > $timeDiff){
  92. return false;
  93. }
  94. return true;
  95. }
  96. }