OpenPlatform.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. throw new BusinessException('登陆失败');
  22. }
  23. $config = shop_config('shop.platform.App');
  24. echo "<pre>";
  25. print_r($this->wechat);
  26. echo "</pre>";
  27. exit;
  28. // 获取accessToken & openid
  29. $res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
  30. 'appid' => $config['app_id'],
  31. 'secret' => $config['secret'],
  32. 'code' => $payload['code'],
  33. 'grant_type' => 'authorization_code'
  34. ]);
  35. $decryptedData = json_decode($res, true);
  36. if (isset($decryptedData['errmsg'])) {
  37. throw new BusinessException($decryptedData['errmsg']);
  38. }
  39. // 获取userInfo
  40. $res = Http::get('https://api.weixin.qq.com/sns/userinfo', ['access_token' => $decryptedData['access_token'], 'openid' => $decryptedData['openid']]);
  41. $userInfo = is_string($res) ? json_decode($res, true) : $res;
  42. if (isset($userInfo['errmsg'])) {
  43. throw new BusinessException($userInfo['errmsg']);
  44. }
  45. $wechatUser = [
  46. 'openid' => $userInfo['openid'],
  47. 'unionid' => $userInfo['unionid'] ?? '',
  48. 'avatar' => $userInfo['headimgurl'],
  49. 'nickname' => $userInfo['nickname'],
  50. ];
  51. return $wechatUser;
  52. }
  53. public function bind()
  54. {
  55. return $this->login();
  56. }
  57. }