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.

77 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. */
  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. * 获取授权token
  29. *
  30. * @param string $code 通过get_authorize_url获取到的code
  31. */
  32. public function get_access_token($code = '')
  33. {
  34. $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";
  35. $token_data = $this->http($token_url);
  36. return json_decode($token_data, true);
  37. }
  38. /**
  39. * 获取授权后的微信用户信息
  40. *
  41. * @param string $access_token
  42. * @param string $open_id
  43. */
  44. public function get_user_info($access_token = '', $open_id = '')
  45. {
  46. $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
  47. $info_data = $this->http($info_url);
  48. return json_decode($info_data, true);
  49. }
  50. // cURL函数简单封装
  51. function http($url, $data = null)
  52. {
  53. $curl = curl_init();
  54. curl_setopt($curl, CURLOPT_URL, $url);
  55. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  56. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  57. if (!empty($data))
  58. {
  59. curl_setopt($curl, CURLOPT_POST, 1);
  60. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  61. }
  62. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  63. $output = curl_exec($curl);
  64. curl_close($curl);
  65. return $output;
  66. }
  67. }