OpenPlatform.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace app\common\Service\Third\Wechat;
  3. use fast\Http;
  4. use app\common\facade\Wechat;
  5. use app\common\exception\BusinessException;
  6. class OpenPlatform
  7. {
  8. public $wechat;
  9. protected $request;
  10. protected $payload;
  11. public function __construct($payload)
  12. {
  13. $this->payload = $payload;
  14. $this->request = request();
  15. $this->wechat = Wechat::openPlatform();
  16. }
  17. public function login()
  18. {
  19. $payload = $this->payload;
  20. if (empty($payload['code'])) {
  21. ('登陆失败');
  22. }
  23. $config = shop_config('shop.platform.App');
  24. // 获取accessToken & openid
  25. $res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
  26. 'appid' => $config['app_id'],
  27. 'secret' => $config['secret'],
  28. 'code' => $payload['code'],
  29. 'grant_type' => 'authorization_code'
  30. ]);
  31. $decryptedData = json_decode($res, true);
  32. if (isset($decryptedData['errmsg'])) {
  33. throw new BusinessException($decryptedData['errmsg']);
  34. }
  35. // 获取userInfo
  36. $res = Http::get('https://api.weixin.qq.com/sns/userinfo', ['access_token' => $decryptedData['access_token'], 'openid' => $decryptedData['openid']]);
  37. $userInfo = is_string($res) ? json_decode($res, true) : $res;
  38. if (isset($userInfo['errmsg'])) {
  39. throw new BusinessException($userInfo['errmsg']);
  40. }
  41. $wechatUser = [
  42. 'openid' => $userInfo['openid'],
  43. 'unionid' => $userInfo['unionid'] ?? '',
  44. 'avatar' => $userInfo['headimgurl'],
  45. 'nickname' => $userInfo['nickname'],
  46. ];
  47. return $wechatUser;
  48. }
  49. public function bind()
  50. {
  51. return $this->login();
  52. }
  53. }