/
Ticket.php
executable file
·96 lines (79 loc) · 2.05 KB
/
Ticket.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
namespace Thenbsp\Wechat\Wechat\Jsapi;
use Thenbsp\Wechat\Bridge\Http;
use Thenbsp\Wechat\Bridge\CacheTrait;
use Thenbsp\Wechat\Wechat\AccessToken;
class Ticket
{
/*
* Cache Trait
*/
use CacheTrait;
/**
* @see http://mp.weixin.qq.com/wiki/11/74ad127cc054f6b80759c40f77ec03db.html(附录 1).
*/
const JSAPI_TICKET = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
/**
* Thenbsp\Wechat\Wechat\AccessToken.
*/
protected $accessToken;
/**
* 构造方法.
*/
public function __construct(AccessToken $accessToken)
{
$this->accessToken = $accessToken;
}
/**
* 获取 AccessToken.
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* 获取 Jsapi 票据(调用缓存,返回 String).
*/
public function getTicketString()
{
$cacheId = $this->getCacheId();
if ($this->cache && $data = $this->cache->fetch($cacheId)) {
return $data['ticket'];
}
$response = $this->getTicketResponse();
if ($this->cache) {
$this->cache->save($cacheId, $response, $response['expires_in']);
}
return $response['ticket'];
}
/**
* 获取 Jsapi 票据(不缓存,返回原始数据).
*/
public function getTicketResponse()
{
$response = Http::request('GET', static::JSAPI_TICKET)
->withAccessToken($this->accessToken)
->withQuery(['type' => 'jsapi'])
->send();
if (0 != $response['errcode']) {
throw new \Exception($response['errmsg'], $response['errcode']);
}
return $response;
}
/**
* 从缓存中清除.
*/
public function clearFromCache()
{
return $this->cache
? $this->cache->delete($this->getCacheId())
: false;
}
/**
* 获取缓存 ID.
*/
public function getCacheId()
{
return sprintf('%s_jsapi_ticket', $this->accessToken['appid']);
}
}