OpenPlatformService.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace services\extend;
  3. use Yii;
  4. use AppleSignIn\ASDecoder;
  5. use linslin\yii2\curl\Curl;
  6. use yii\helpers\Json;
  7. use yii\web\UnprocessableEntityHttpException;
  8. /**
  9. * Class OpenPlatformService
  10. * @package services\extend
  11. */
  12. class OpenPlatformService
  13. {
  14. /**
  15. * 微信开放平台
  16. *
  17. * @param string $code
  18. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  19. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  20. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  21. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  22. * @throws \Psr\SimpleCache\InvalidArgumentException
  23. * @throws \yii\web\UnprocessableEntityHttpException
  24. *
  25. * Array
  26. * (
  27. * [openid] => ''
  28. * [nickname] => ''
  29. * [sex] => 1
  30. * [language] => zh_CN
  31. * [city] => 杭州
  32. * [province] => 浙江
  33. * [country] => 中国
  34. * [headimgurl] => ''
  35. * [privilege] => Array
  36. * (
  37. * )
  38. * [unionid] => ''
  39. * )
  40. */
  41. public function wechat(string $code)
  42. {
  43. $appId = Yii::$app->services->config->backendConfig('wechat_app_id'); //开发平台申请
  44. $appSecret = Yii::$app->services->config->backendConfig('wechat_app_secret'); //开发平台申请
  45. // 认证
  46. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appId . "&secret=" . $appSecret . "&code=" . $code . "&grant_type=authorization_code";
  47. // 调用微信api
  48. $http = new Curl();
  49. $result = Json::decode($http->get($url));
  50. Yii::$app->services->base->getWechatError($result);
  51. // 拉取用户信息
  52. $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $result['access_token'] . "&openid=" . $result['openid'] . "&lang=zh_CN";
  53. return Json::decode($http->get($url));
  54. }
  55. /**
  56. * apple 登录
  57. *
  58. * @param string $clientUser openid
  59. * @param string $identityToken jwt
  60. * @return array
  61. * @throws UnprocessableEntityHttpException
  62. */
  63. public function apple(string $clientUser, string $identityToken)
  64. {
  65. $appleSignInPayload = ASDecoder::getAppleSignInPayload($identityToken);
  66. /**
  67. * Obtain the Sign In with Apple email and user creds.
  68. */
  69. $email = $appleSignInPayload->getEmail();
  70. $user = $appleSignInPayload->getUser();
  71. /**
  72. * Determine whether the client-provided user is valid.
  73. */
  74. $isValid = $appleSignInPayload->verifyUser($clientUser);
  75. if ($isValid == false) {
  76. throw new UnprocessableEntityHttpException('验证失败');
  77. }
  78. return [$email, $user];
  79. }
  80. }
粤ICP备19079148号