1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- namespace app\common\Service\Third\Wechat;
- use fast\Http;
- use app\common\facade\Wechat;
- use app\common\exception\BusinessException;
- use app\common\Enum\ChannelEnum;
- class OpenPlatform
- {
- public $wechat;
- protected $request;
- protected $payload;
- protected $platform;
- public function __construct($platform,$payload)
- {
- $this->payload = $payload;
- $this->request = request();
- if($platform == ChannelEnum::CHANNEL_IOS_APP){
- $this->wechat = Wechat::openIosAppPlatform();
- }else{
- $this->wechat = Wechat::openAndroidAppPlatform();
- }
- $this->platform = $platform;
- }
- /**
- * 转换平台名称格式
- * 将前端驼峰命名转换为后端下划线格式
- *
- * @param string $platform
- * @return string
- */
- protected function convertPlatformName($platform)
- {
- // 将驼峰命名转换为下划线格式
- return strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst($platform)));
- }
- public function login()
- {
- $payload = $this->payload;
- if (empty($payload['code'])) {
- throw new BusinessException('登陆失败');
- }
- // 需要转换 前段穿 DouyinMiniProgram 后端配置是 douyin_mini_program
- $platformKey = $this->convertPlatformName($this->platform);
- $config = shop_config('shop.platform.' . $platformKey);
- // 获取accessToken & openid
- $res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
- 'appid' => $config['app_id'],
- 'secret' => $config['secret'],
- 'code' => $payload['code'],
- 'grant_type' => 'authorization_code'
- ]);
- $decryptedData = json_decode($res, true);
- if (isset($decryptedData['errmsg'])) {
- throw new BusinessException($decryptedData['errmsg']);
- }
- // 获取userInfo
- $res = Http::get('https://api.weixin.qq.com/sns/userinfo', ['access_token' => $decryptedData['access_token'], 'openid' => $decryptedData['openid']]);
- $userInfo = is_string($res) ? json_decode($res, true) : $res;
- if (isset($userInfo['errmsg'])) {
- throw new BusinessException($userInfo['errmsg']);
- }
- $wechatUser = [
- 'openid' => $userInfo['openid'],
- 'unionid' => $userInfo['unionid'] ?? '',
- 'avatar' => $userInfo['headimgurl'],
- 'nickname' => $userInfo['nickname'],
- ];
- return $wechatUser;
- }
- public function bind()
- {
- return $this->login();
- }
- }
|