OfficialAccount.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace app\common\Service\Third\Wechat;
  3. use app\common\facade\Wechat;
  4. use app\common\exception\BusinessException;
  5. class OfficialAccount
  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::officialAccount();
  15. }
  16. public function login()
  17. {
  18. $code = $this->request->get('code');
  19. if (empty($code)) {
  20. throw new BusinessException('缺少code参数');
  21. }
  22. $decryptData = $this->wechat->oauth->user()->getOriginal();
  23. $wechatUser = [
  24. 'openid' => $decryptData['openid'],
  25. 'unionid' => $decryptData['unionid'] ?? '',
  26. 'avatar' => $decryptData['headimgurl'],
  27. 'nickname' => $decryptData['nickname'],
  28. ];
  29. return $wechatUser;
  30. }
  31. public function bind()
  32. {
  33. return $this->login();
  34. }
  35. /**
  36. * 获取网页登录地址redirect+返回code
  37. *
  38. * @return string
  39. */
  40. public function oauthLogin()
  41. {
  42. // 返回前端
  43. if (!empty($this->request->param('code'))) {
  44. if($this->payload['event'] === 'bind') {
  45. $query['bind_code'] = $this->request->param('code');
  46. }else {
  47. $query['login_code'] = $this->request->param('code');
  48. }
  49. return [
  50. 'redirect_url' => $this->payload['page'] . '?' . http_build_query($query)
  51. ];
  52. } else {
  53. $query = [
  54. 'platform' => 'officialAccount',
  55. 'payload' => urlencode(json_encode($this->payload))
  56. ];
  57. $loginUrl = $this->request->domain() . '/api/shop/third.wechat/oauthLogin?' . http_build_query($query);
  58. return [
  59. 'login_url' => $this->wechat->oauth->scopes(['snsapi_userinfo'])->redirect($loginUrl)->getTargetUrl()
  60. ];
  61. }
  62. }
  63. public function jssdk($APIs)
  64. {
  65. $this->wechat->jssdk->setUrl($this->payload['url']);
  66. return $this->wechat->jssdk->buildConfig($APIs, false, false, false);
  67. }
  68. }