-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Application.php
261 lines (215 loc) · 8.35 KB
/
Application.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<?php
declare(strict_types=1);
namespace EasyWeChat\OfficialAccount;
use EasyWeChat\Kernel\Contracts\AccessToken as AccessTokenInterface;
use EasyWeChat\Kernel\Contracts\JsApiTicket as JsApiTicketInterface;
use EasyWeChat\Kernel\Contracts\RefreshableAccessToken as RefreshableAccessTokenInterface;
use EasyWeChat\Kernel\Contracts\RefreshableJsApiTicket as RefreshableJsApiTicketInterface;
use EasyWeChat\Kernel\Contracts\Server as ServerInterface;
use EasyWeChat\Kernel\Encryptor;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\HttpClient\AccessTokenAwareClient;
use EasyWeChat\Kernel\HttpClient\AccessTokenExpiredRetryStrategy;
use EasyWeChat\Kernel\HttpClient\RequestUtil;
use EasyWeChat\Kernel\HttpClient\Response;
use EasyWeChat\Kernel\Traits\InteractWithCache;
use EasyWeChat\Kernel\Traits\InteractWithClient;
use EasyWeChat\Kernel\Traits\InteractWithConfig;
use EasyWeChat\Kernel\Traits\InteractWithHttpClient;
use EasyWeChat\Kernel\Traits\InteractWithServerRequest;
use EasyWeChat\OfficialAccount\Contracts\Account as AccountInterface;
use EasyWeChat\OfficialAccount\Contracts\Application as ApplicationInterface;
use JetBrains\PhpStorm\Pure;
use Overtrue\Socialite\Contracts\ProviderInterface as SocialiteProviderInterface;
use Overtrue\Socialite\Providers\WeChat;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\HttpClient\Response\AsyncContext;
use Symfony\Component\HttpClient\RetryableHttpClient;
use function array_merge;
use function call_user_func;
use function sprintf;
use function str_contains;
class Application implements ApplicationInterface
{
use InteractWithCache;
use InteractWithClient;
use InteractWithConfig;
use InteractWithHttpClient;
use InteractWithServerRequest;
use LoggerAwareTrait;
protected ?Encryptor $encryptor = null;
protected ?ServerInterface $server = null;
protected ?AccountInterface $account = null;
protected AccessTokenInterface|RefreshableAccessTokenInterface|null $accessToken = null;
protected ?JsApiTicketInterface $ticket = null;
protected ?\Closure $oauthFactory = null;
public function getAccount(): AccountInterface
{
if (! $this->account) {
$this->account = new Account(
appId: (string) $this->config->get('app_id'), /** @phpstan-ignore-line */
secret: (string) $this->config->get('secret'), /** @phpstan-ignore-line */
token: (string) $this->config->get('token'), /** @phpstan-ignore-line */
aesKey: (string) $this->config->get('aes_key'),/** @phpstan-ignore-line */
);
}
return $this->account;
}
public function setAccount(AccountInterface $account): static
{
$this->account = $account;
return $this;
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
*/
public function getEncryptor(): Encryptor
{
if (! $this->encryptor) {
$token = $this->getAccount()->getToken();
$aesKey = $this->getAccount()->getAesKey();
if (empty($token) || empty($aesKey)) {
throw new InvalidConfigException('token or aes_key cannot be empty.');
}
$this->encryptor = new Encryptor(
appId: $this->getAccount()->getAppId(),
token: $token,
aesKey: $aesKey,
receiveId: $this->getAccount()->getAppId()
);
}
return $this->encryptor;
}
public function setEncryptor(Encryptor $encryptor): static
{
$this->encryptor = $encryptor;
return $this;
}
/**
* @throws \ReflectionException
* @throws InvalidArgumentException
* @throws \Throwable
*/
public function getServer(): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
request: $this->getRequest(),
encryptor: $this->getAccount()->getAesKey() ? $this->getEncryptor() : null
);
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function getAccessToken(): AccessTokenInterface|RefreshableAccessTokenInterface
{
if (! $this->accessToken) {
$this->accessToken = new AccessToken(
appId: $this->getAccount()->getAppId(),
secret: $this->getAccount()->getSecret(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
stable: $this->config->get('use_stable_access_token', false),
);
}
return $this->accessToken;
}
public function setAccessToken(AccessTokenInterface|RefreshableAccessTokenInterface $accessToken): static
{
$this->accessToken = $accessToken;
return $this;
}
public function setOAuthFactory(callable $factory): static
{
$this->oauthFactory = fn (Application $app): WeChat => $factory($app);
return $this;
}
/**
* @throws InvalidArgumentException
*/
public function getOAuth(): SocialiteProviderInterface
{
if (! $this->oauthFactory) {
$this->oauthFactory = fn (self $app): SocialiteProviderInterface => (new WeChat(
[
'client_id' => $this->getAccount()->getAppId(),
'client_secret' => $this->getAccount()->getSecret(),
'redirect_url' => $this->config->get('oauth.redirect_url'),
]
))->scopes((array) $this->config->get('oauth.scopes', ['snsapi_userinfo']));
}
$provider = call_user_func($this->oauthFactory, $this);
if (! $provider instanceof SocialiteProviderInterface) {
throw new InvalidArgumentException(sprintf(
'The factory must return a %s instance.',
SocialiteProviderInterface::class
));
}
return $provider;
}
public function getTicket(): JsApiTicketInterface|RefreshableJsApiTicketInterface
{
if (! $this->ticket) {
$this->ticket = new JsApiTicket(
appId: $this->getAccount()->getAppId(),
secret: $this->getAccount()->getSecret(),
cache: $this->getCache(),
httpClient: $this->getClient(),
stable: $this->config->get('use_stable_access_token', false),
);
}
return $this->ticket;
}
public function setTicket(JsApiTicketInterface|RefreshableJsApiTicketInterface $ticket): static
{
$this->ticket = $ticket;
return $this;
}
#[Pure]
public function getUtils(): Utils
{
return new Utils($this);
}
public function createClient(): AccessTokenAwareClient
{
$httpClient = $this->getHttpClient();
if ((bool) $this->config->get('http.retry', false)) {
$httpClient = new RetryableHttpClient(
$httpClient,
$this->getRetryStrategy(),
(int) $this->config->get('http.max_retries', 2) // @phpstan-ignore-line
);
}
return (new AccessTokenAwareClient(
client: $httpClient,
accessToken: $this->getAccessToken(),
failureJudge: fn (Response $response) => (bool) ($response->toArray()['errcode'] ?? 0),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getRetryStrategy(): AccessTokenExpiredRetryStrategy
{
$retryConfig = RequestUtil::mergeDefaultRetryOptions((array) $this->config->get('http.retry', []));
return (new AccessTokenExpiredRetryStrategy($retryConfig))
->decideUsing(function (AsyncContext $context, ?string $responseContent): bool {
return ! empty($responseContent)
&& str_contains($responseContent, '42001')
&& str_contains($responseContent, 'access_token expired');
});
}
/**
* @return array<string,mixed>
*/
protected function getHttpClientDefaultOptions(): array
{
return array_merge(
['base_uri' => 'https://api.weixin.qq.com/'],
(array) $this->config->get('http', [])
);
}
}