BaseController.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace frontend\controllers;
  3. use Yii;
  4. use yii\web\Controller;
  5. use yii\web\Response;
  6. abstract class BaseController extends Controller
  7. {
  8. /**
  9. * @inheritdoc
  10. */
  11. public function init()
  12. {
  13. parent::init();
  14. $this->enableCsrfValidation = false;
  15. }
  16. /**
  17. * @inheritdoc
  18. */
  19. public function beforeAction($action)
  20. {
  21. if (parent::beforeAction($action)) {
  22. //检验签名
  23. if (true || $this->checkRequestToken()) {
  24. return true;
  25. } else {
  26. $this->outJson(0, '', '验签失败');
  27. return false;
  28. }
  29. }
  30. return false;
  31. }
  32. /**
  33. * json 输出方法
  34. * @param int $code api code 码 0 失败 1 正常
  35. * @param array $data 输出信息
  36. * @param string $msg 提示语
  37. * @return Response
  38. */
  39. public function outJson($code = 0, $data = array(), $msg = null)
  40. {
  41. $data = [
  42. 'code' => $code,
  43. 'message' => $msg,
  44. 'data' => $data,
  45. 'timestamp' => time()
  46. ];
  47. return $this->asJson($data);
  48. }
  49. /**
  50. * 验证签名
  51. * @return bool true验证成功 false验证失败
  52. */
  53. private function checkRequestToken()
  54. {
  55. $strOauth = '';
  56. $params = array_merge(Yii::$app->getRequest()->get(), Yii::$app->getRequest()->post());
  57. $secret = Yii::$app->params['appSignSecret'];//密钥
  58. //去掉sign值
  59. $token = isset($params['token']) ? trim($params['token']) : '';
  60. if ($token == '') {
  61. return false;
  62. }
  63. unset($params['token']);
  64. ksort($params);//升序排序
  65. foreach ($params as $key => $val) {
  66. if ($key == 'token' || is_array($val) || $val === null) {
  67. continue;
  68. }
  69. $strOauth .= $key . '=' . $val . '&';//&符拼接
  70. }
  71. $strOauth = rtrim($strOauth, '&') . $secret;//加上密钥
  72. //md5后验证签名
  73. if (strcmp(md5($strOauth), $token) !== 0) {
  74. return false;
  75. }
  76. return true;
  77. }
  78. }