OpenPlatform.php 1.7 KB

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