OpenPlatform.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. use app\common\Enum\ChannelEnum;
  7. class OpenPlatform
  8. {
  9. public $wechat;
  10. protected $request;
  11. protected $payload;
  12. protected $platform;
  13. public function __construct($platform,$payload)
  14. {
  15. $this->payload = $payload;
  16. $this->request = request();
  17. if($platform == ChannelEnum::CHANNEL_IOS_APP){
  18. $this->wechat = Wechat::openIosAppPlatform();
  19. }else{
  20. $this->wechat = Wechat::openAndroidAppPlatform();
  21. }
  22. $this->platform = $platform;
  23. }
  24. /**
  25. * 转换平台名称格式
  26. * 将前端驼峰命名转换为后端下划线格式
  27. *
  28. * @param string $platform
  29. * @return string
  30. */
  31. protected function convertPlatformName($platform)
  32. {
  33. // 将驼峰命名转换为下划线格式
  34. return strtolower(preg_replace('/([A-Z])/', '_$1', lcfirst($platform)));
  35. }
  36. public function login()
  37. {
  38. $payload = $this->payload;
  39. if (empty($payload['code'])) {
  40. throw new BusinessException('登陆失败');
  41. }
  42. // 需要转换 前段穿 DouyinMiniProgram 后端配置是 douyin_mini_program
  43. $platformKey = $this->convertPlatformName($this->platform);
  44. $config = shop_config('shop.platform.' . $platformKey);
  45. // 获取accessToken & openid
  46. $res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
  47. 'appid' => $config['app_id'],
  48. 'secret' => $config['secret'],
  49. 'code' => $payload['code'],
  50. 'grant_type' => 'authorization_code'
  51. ]);
  52. $decryptedData = json_decode($res, true);
  53. if (isset($decryptedData['errmsg'])) {
  54. throw new BusinessException($decryptedData['errmsg']);
  55. }
  56. // 获取userInfo
  57. $res = Http::get('https://api.weixin.qq.com/sns/userinfo', ['access_token' => $decryptedData['access_token'], 'openid' => $decryptedData['openid']]);
  58. $userInfo = is_string($res) ? json_decode($res, true) : $res;
  59. if (isset($userInfo['errmsg'])) {
  60. throw new BusinessException($userInfo['errmsg']);
  61. }
  62. $wechatUser = [
  63. 'openid' => $userInfo['openid'],
  64. 'unionid' => $userInfo['unionid'] ?? '',
  65. 'avatar' => $userInfo['headimgurl'],
  66. 'nickname' => $userInfo['nickname'],
  67. ];
  68. return $wechatUser;
  69. }
  70. public function bind()
  71. {
  72. return $this->login();
  73. }
  74. }