Login.class.php 2.5 KB

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