AppInfo.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * 应用信息
  4. * @author solu
  5. */
  6. class AppInfo extends Model {
  7. protected $tableName = 'app_info';
  8. protected $dbKey = 'dw_chat';
  9. const REDIS_KEY_ACCESS_TOKEN = 'globals:app_access_token:%s:%s';
  10. const VERIFY_TIMEOUT = 20;
  11. const ACCESS_TOKEN_TTL = 86400;
  12. const STATE_CLOSE = 0; //不可用
  13. const STATE_OPEN = 1; // 可用
  14. /**
  15. * 校验app参数
  16. * @author solu
  17. * @param $appId
  18. * @param $ts
  19. * @param $sign
  20. * @return bool
  21. * @throws Exception
  22. */
  23. public function verify($appId, $ts, $sign) {
  24. $info = $this->objTable->getRow(['app_id' => $appId]);
  25. if (!$info || $info['state'] == self::STATE_CLOSE) {
  26. throw new Exception('app id not available', CODE_PARAM_ERROR);
  27. }
  28. if ($sign != self::doSign($appId, $info['app_secret'], $ts)) {
  29. throw new Exception('sign error!', CODE_SIGN_ERROR);
  30. }
  31. if (time() - self::VERIFY_TIMEOUT > $ts) {
  32. throw new Exception('request params timeout', CODE_PARAM_ERROR);
  33. }
  34. return true;
  35. }
  36. public static function doSign($appId, $appSecret, $ts) {
  37. return md5(sprintf('%s_%s_%s', $appId, $appSecret, $ts));
  38. }
  39. private static function _accessTokenKey($appId, $accessToken) {
  40. return sprintf(self::REDIS_KEY_ACCESS_TOKEN, $appId, $accessToken);
  41. }
  42. public static function genAccessToken($appId, $userId) {
  43. $accessToken = uuid16();
  44. if (!$accessToken) {
  45. return false;
  46. }
  47. $key = self::_accessTokenKey($appId, $accessToken);
  48. $objRedis = dwRedis::init(Eos::REDIS_SERV);
  49. $objRedis->setex($key, self::ACCESS_TOKEN_TTL, $userId);
  50. return $accessToken;
  51. }
  52. public static function checkAccessToken($appId, $userId, $accessToken) {
  53. $key = self::_accessTokenKey($appId, $accessToken);
  54. $objRedis = dwRedis::init(Eos::REDIS_SERV);
  55. $in = $objRedis->get($key);
  56. if (intval($in) === intval($userId)) {
  57. return true;
  58. }
  59. return false;
  60. }
  61. }