You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
3.2 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. <?php
  2. namespace App\Common;
  3. /**
  4. * OAuth2.0微信授权登录实现/微信PC扫码授权登录
  5. * 微信/PC扫码登录,两种的方式是一样的,先跳转到微信网页获取code,通过code获取token,通过token获取用户信息
  6. */
  7. class WechatAuth
  8. {
  9. //高级功能->开发者模式->获取
  10. private $app_id;
  11. private $app_secret;
  12. public function __construct($app_id, $app_secret)
  13. {
  14. $this->app_id = $app_id;
  15. $this->app_secret = $app_secret;
  16. }
  17. /**
  18. * 获取微信授权链接
  19. *
  20. * @param string $redirect_uri 回调地址,授权后重定向的回调链接地址,请使用urlEncode对链接进行处理
  21. * @param mixed $state 可以为空,重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
  22. */
  23. public function get_authorize_url($redirect_uri = '', $state = '')
  24. {
  25. return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->app_id."&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";
  26. }
  27. /**
  28. * 微信PC扫码授权登录链接
  29. *
  30. * @param string $redirect_uri 回调地址,授权后重定向的回调链接地址,请使用urlEncode对链接进行处理
  31. * @param mixed $state 可以为空,重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
  32. */
  33. public function get_qrconnect_url($redirect_uri = '', $state = '')
  34. {
  35. return "https://open.weixin.qq.com/connect/qrconnect?appid".$this->app_id."&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=snsapi_login&state=".$state."#wechat_redirect";
  36. }
  37. /**
  38. * 获取授权token
  39. *
  40. * @param string $code 通过get_authorize_url获取到的code
  41. */
  42. public function get_access_token($code = '')
  43. {
  44. $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
  45. $token_data = $this->http($token_url);
  46. return json_decode($token_data, true);
  47. }
  48. /**
  49. * 获取授权后的微信用户信息
  50. *
  51. * @param string $access_token
  52. * @param string $open_id
  53. */
  54. public function get_user_info($access_token = '', $open_id = '')
  55. {
  56. $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
  57. $info_data = $this->http($info_url);
  58. return json_decode($info_data, true);
  59. }
  60. // cURL函数简单封装
  61. function http($url, $data = null)
  62. {
  63. $curl = curl_init();
  64. curl_setopt($curl, CURLOPT_URL, $url);
  65. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  66. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  67. if (!empty($data))
  68. {
  69. curl_setopt($curl, CURLOPT_POST, 1);
  70. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  71. }
  72. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  73. $output = curl_exec($curl);
  74. curl_close($curl);
  75. return $output;
  76. }
  77. }