Login.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Cas\Controller;
  3. use KIF\Core\Config;
  4. /**
  5. *
  6. * Login
  7. * @author rabin
  8. *
  9. */
  10. class Login extends Controller{
  11. private $appId;
  12. private $appSecret;
  13. public function __construct() {
  14. $wechat_cfg = Config::getInstance()->get('wechat_cfg');
  15. $this->appSecret = $wechat_cfg['appSecret'];
  16. $this->appId = $wechat_cfg['appId'];
  17. $this->objMemcached = new Memcached();
  18. $this->refer = 'accessTokenRefer';
  19. }
  20. public function doGet() {
  21. $refer = Request::g ( 'referer' );
  22. $this->objMemcached->set($this->refer, $refer);
  23. $host = Config::getInstance ()->get ( 'App_Id' );
  24. $callback = urlencode($host . '?c=Login&a=Callback');
  25. $time = time() . rand(0,100);
  26. $url = 'https://open.weixin.qq.com/connect/qrconnect';
  27. $url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
  28. $url .= '?appid='.$this->appId.'&redirect_uri='.$callback.'&response_type=code&scope=snsapi_login&state='.$time.'#wechat_redirect';
  29. //echo $url;die;
  30. //self::redirect($url);
  31. header ( "Location: " . $url);
  32. }
  33. public function doCallback() {
  34. $code = Request::g ( 'code' );
  35. $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appId.'&secret='.$this->appSecret.'&code='.$code.'&grant_type=authorization_code';
  36. $data = $this->httpGet($url);
  37. $data = json_decode($data, true);
  38. if (isset($data['access_token']) && $data['access_token']) {
  39. $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'] . '&lang=zh_CN';
  40. $data = $this->httpGet($url);
  41. $data = json_decode($data, true);
  42. $refer = $this->objMemcached->get($this->refer);
  43. $param = $data;
  44. $param['uid'] = $data['openid'];
  45. $refer .= '&' . http_build_url($param);
  46. header ( "Location: " . $refer);
  47. }
  48. }
  49. private function httpGet($url) {
  50. $curl = curl_init();
  51. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  52. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  53. curl_setopt($curl, CURLOPT_URL, $url);
  54. $res = curl_exec($curl);
  55. curl_close($curl);
  56. return $res;
  57. }
  58. }