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.

76 lines
2.4 KiB

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