Skip to content

Commit 2ec6472

Browse files
Copilotovertrue
andauthored
Add error checking in WeChat::getUserByToken() (#302)
* Initial plan * Add error checking in WeChat::getUserByToken() for API error responses Co-authored-by: overtrue <1472352+overtrue@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: overtrue <1472352+overtrue@users.noreply.github.com>
1 parent 5540077 commit 2ec6472

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/Providers/WeChat.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,13 @@ protected function getUserByToken(string $token): array
166166
]),
167167
]);
168168

169-
return $this->fromJsonBody($response);
169+
$response = $this->fromJsonBody($response);
170+
171+
if (! empty($response['errcode'])) {
172+
throw new Exceptions\AuthorizeFailedException((string) ($response['errmsg'] ?? ''), $response);
173+
}
174+
175+
return $response;
170176
}
171177

172178
#[Pure]

tests/Providers/WechatTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,34 @@ public function test_throws_exception_when_access_token_missing()
186186

187187
$getSnsapiBaseUserFromCode->invoke($mockProvider, 'test_code');
188188
}
189+
190+
public function test_throws_exception_when_get_user_by_token_fails()
191+
{
192+
$mockProvider = $this->getMockBuilder(WeChat::class)
193+
->setConstructorArgs([[
194+
'client_id' => 'client_id',
195+
'client_secret' => 'client_secret',
196+
'redirect_url' => 'http://localhost/socialite/callback.php',
197+
]])
198+
->onlyMethods(['getHttpClient', 'fromJsonBody'])
199+
->getMock();
200+
201+
$mockResponse = $this->createMock(\Psr\Http\Message\ResponseInterface::class);
202+
$mockHttpClient = $this->createMock(\GuzzleHttp\Client::class);
203+
$mockHttpClient->method('get')->willReturn($mockResponse);
204+
205+
$mockProvider->method('getHttpClient')->willReturn($mockHttpClient);
206+
$mockProvider->method('fromJsonBody')->willReturn([
207+
'errcode' => 40003,
208+
'errmsg' => 'invalid openid',
209+
]);
210+
211+
$getUserByToken = new ReflectionMethod(WeChat::class, 'getUserByToken');
212+
$getUserByToken->setAccessible(true);
213+
214+
$this->expectException(AuthorizeFailedException::class);
215+
$this->expectExceptionMessage('invalid openid');
216+
217+
$getUserByToken->invoke($mockProvider, 'test_token');
218+
}
189219
}

0 commit comments

Comments
 (0)