VerifyTicket.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace EasyWeChat\OpenPlatform\Auth;
  11. use EasyWeChat\Kernel\Exceptions\RuntimeException;
  12. use EasyWeChat\Kernel\Traits\InteractsWithCache;
  13. use EasyWeChat\OpenPlatform\Application;
  14. /**
  15. * Class VerifyTicket.
  16. *
  17. * @author mingyoung <mingyoungcheung@gmail.com>
  18. */
  19. class VerifyTicket
  20. {
  21. use InteractsWithCache;
  22. /**
  23. * @var \EasyWeChat\OpenPlatform\Application
  24. */
  25. protected $app;
  26. /**
  27. * Constructor.
  28. *
  29. * @param \EasyWeChat\OpenPlatform\Application $app
  30. */
  31. public function __construct(Application $app)
  32. {
  33. $this->app = $app;
  34. }
  35. /**
  36. * Put the credential `component_verify_ticket` in cache.
  37. *
  38. * @param string $ticket
  39. *
  40. * @return $this
  41. *
  42. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  43. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  44. * @throws \Psr\SimpleCache\InvalidArgumentException
  45. */
  46. public function setTicket(string $ticket)
  47. {
  48. $this->getCache()->set($this->getCacheKey(), $ticket, 3600);
  49. if (!$this->getCache()->has($this->getCacheKey())) {
  50. throw new RuntimeException('Failed to cache verify ticket.');
  51. }
  52. return $this;
  53. }
  54. /**
  55. * Get the credential `component_verify_ticket` from cache.
  56. *
  57. * @return string
  58. *
  59. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  60. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  61. * @throws \Psr\SimpleCache\InvalidArgumentException
  62. */
  63. public function getTicket(): string
  64. {
  65. if ($cached = $this->getCache()->get($this->getCacheKey())) {
  66. return $cached;
  67. }
  68. throw new RuntimeException('Credential "component_verify_ticket" does not exist in cache.');
  69. }
  70. /**
  71. * Get cache key.
  72. *
  73. * @return string
  74. */
  75. protected function getCacheKey(): string
  76. {
  77. return 'easywechat.open_platform.verify_ticket.'.$this->app['config']['app_id'];
  78. }
  79. }