| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <?php
- declare(strict_types=1);
- namespace app\miniapi\auth;
- use app\miniapi\exception\ApiException;
- final class WechatIdentityProvider implements IdentityProvider
- {
- public function exchange(string $code): array
- {
- $appid = (string) config('mini_api.wechat_appid', '');
- $secret = (string) config('mini_api.wechat_secret', '');
- if ($appid === '' || $secret === '') {
- throw new ApiException(50301, '微信登录尚未配置', 503);
- }
- $url = 'https://api.weixin.qq.com/sns/jscode2session?' . http_build_query([
- 'appid' => $appid,
- 'secret' => $secret,
- 'js_code' => $code,
- 'grant_type' => 'authorization_code',
- ]);
- $ch = curl_init($url);
- curl_setopt_array($ch, [
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_CONNECTTIMEOUT => 5,
- CURLOPT_TIMEOUT => 10,
- CURLOPT_SSL_VERIFYPEER => true,
- CURLOPT_SSL_VERIFYHOST => 2,
- CURLOPT_FOLLOWLOCATION => false,
- ]);
- $raw = curl_exec($ch);
- $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- if ($raw === false || $status !== 200) {
- throw new ApiException(50302, '微信登录服务暂时不可用', 503);
- }
- $data = json_decode($raw, true);
- if (!is_array($data) || empty($data['openid']) || !is_string($data['openid']) || strlen($data['openid']) > 128) {
- throw new ApiException(40102, '微信登录凭据无效,请重新登录', 401);
- }
- // session_key and unionid are deliberately neither returned nor logged.
- return [
- 'appid' => $appid,
- 'openid' => $data['openid'],
- ];
- }
- }
|