You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.7 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. <?php
  2. namespace App\Common;
  3. use Illuminate\Support\Facades\DB;
  4. class Token
  5. {
  6. const TYPE_APP = 0;
  7. const TYPE_ADMIN = 1;
  8. const TYPE_WEIXIN = 2;
  9. const TYPE_WAP = 3;
  10. const TYPE_PC = 4;
  11. // 已验证的type
  12. public static $type;
  13. // 验证为token时的uid
  14. public static $uid;
  15. // 验证为sign时的app.id
  16. public static $app;
  17. // 已验证的data
  18. public static $data = array();
  19. /**
  20. * 验证token
  21. *
  22. * @param $token
  23. *
  24. * @return bool
  25. */
  26. public static function checkToken($token)
  27. {
  28. $token = DB::table('token')->where('token', $token)->first();
  29. if ($token)
  30. {
  31. self::$type = $token->type;
  32. self::$uid = $token->uid;
  33. self::$data = $token->data ? json_decode($token->data, true) : array();
  34. }
  35. return $token ? true : false;
  36. }
  37. /**
  38. * 验证sign,
  39. * sign生成方式:md5(app_key + app_secret + time)
  40. * 必传参数:app_key, sign, sign_time
  41. *
  42. * @param $appKey
  43. * @param $signTime
  44. * @param $sign
  45. *
  46. * @return bool
  47. */
  48. public static function checkSign($appKey, $signTime, $sign)
  49. {
  50. if (!$appRes = DB::table('appsign')->where('app_key', $appKey)->first())
  51. {
  52. return false;
  53. }
  54. //验证sign
  55. $newSign = md5($appKey . $appRes->app_secret . $signTime);
  56. if ($sign == $newSign)
  57. {
  58. self::$type = self::TYPE_ADMIN;
  59. self::$app = $appRes;
  60. return true;
  61. }
  62. return false;
  63. }
  64. /**
  65. * 生成token
  66. *
  67. * @param $type
  68. * @param $uid
  69. * @param $data
  70. *
  71. * @return string
  72. */
  73. public static function getToken($type, $uid, $data = array())
  74. {
  75. //支持多账号登录
  76. if ($token = DB::table('token')->where(array('type' => $type, 'uid' => $uid))->orderBy('id', 'desc')->first())
  77. {
  78. if($data == $token->data && strtotime($token->expired_at)>time())
  79. {
  80. return array('access_token'=>$token->token,'expired_at'=>$token->expired_at);
  81. }
  82. }
  83. //生成新token
  84. $token = md5($type . '-' . $uid . '-' . microtime() . rand(0, 9999));
  85. $expired_at = date("Y-m-d H:i:s",(time()+3600*24*30)); //token 30天过期
  86. DB::table('token')->insert(array(
  87. 'token' => $token,
  88. 'type' => $type,
  89. 'uid' => $uid,
  90. 'data' => $data ? json_encode($data) : '',
  91. 'expired_at' => $expired_at
  92. ));
  93. return array('access_token'=>$token,'expired_at'=>$expired_at,'uid'=>$uid,'type'=>$type);
  94. }
  95. }