QqService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Services\Common;
  3. use GuzzleHttp\Client;
  4. /**
  5. * qq第三方登录
  6. * Class QqService
  7. * @package App\Services\Common
  8. */
  9. class QqService
  10. {
  11. protected $auth_url = "https://graph.qq.com/";
  12. protected $appid;
  13. protected $appkey;
  14. protected $httpClient;
  15. /**
  16. * QqService constructor.
  17. */
  18. public function __construct()
  19. {
  20. $this->httpClient=new Client([
  21. 'http_errors' => false
  22. ]);
  23. $this->appid=config('aix.system.oauth.qq.app_id');
  24. $this->appkey=config('aix.system.oauth.qq.app_key');
  25. }
  26. public function getAccessToken($code)
  27. {
  28. $uri=$this->auth_url."oauth2.0/token?grant_type=authorization_code&client_id=$this->appid&client_secret=$this->appkey&code=$code&redirect_uri=".session('qq_redirect_uri');
  29. $resopnse=$this->httpClient->get($uri);
  30. parse_str($resopnse->getBody()->getContents(), $result);
  31. return $result['access_token'];
  32. }
  33. public function getOpenid($access_token)
  34. {
  35. $uri=$this->auth_url."oauth2.0/me?access_token=$access_token";
  36. $resopnse=$this->httpClient->get($uri);
  37. $result=trim(str_replace(['callback(',');'], ["", ""], $resopnse->getBody()->getContents()));
  38. $res_arr=json_decode($result, true);
  39. return $res_arr['openid'];
  40. }
  41. public function getUserInfo($access_token, $openid)
  42. {
  43. $uri=$this->auth_url."user/get_user_info?access_token=$access_token&oauth_consumer_key=$this->appid&openid=$openid";
  44. $resopnse=$this->httpClient->get($uri);
  45. $res_arr=json_decode($resopnse->getBody()->getContents(), true);
  46. return $res_arr;
  47. }
  48. public function getUser($code)
  49. {
  50. $access_token=$this->getAccessToken($code);
  51. $openid=$this->getOpenid($access_token);
  52. $user=$this->getUserInfo($access_token, $openid);
  53. $user['openid']=$openid;
  54. return $user;
  55. }
  56. }