Login.class.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. print_r($refer);die;
  25. $this->objMemcached->set($this->refer, $refer);
  26. $host = Config::getInstance ()->get ( 'App_Id' );
  27. $callback = urlencode($host . '?c=Login&a=Callback');
  28. $time = time() . rand(0,100);
  29. $url = 'https://open.weixin.qq.com/connect/qrconnect';
  30. $url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
  31. $url .= '?appid='.$this->appId.'&redirect_uri='.$callback.'&response_type=code&scope=snsapi_userinfo&state='.$time.'#wechat_redirect';
  32. //echo $url;die;
  33. //self::redirect($url);
  34. header ( "Location: " . $url);
  35. }
  36. public function doCallback() {
  37. $refer = $this->objMemcached->get($this->refer);
  38. print_r($refer);die;
  39. $code = Request::g ( 'code' );
  40. $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appId.'&secret='.$this->appSecret.'&code='.$code.'&grant_type=authorization_code';
  41. $data = $this->httpGet($url);
  42. $data = json_decode($data, true);
  43. if (isset($data['access_token']) && $data['access_token']) {
  44. $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'] . '&lang=zh_CN';
  45. $data = $this->httpGet($url);
  46. $data = json_decode($data, true);
  47. if (isset($data['nickname']) && $data['nickname']) {
  48. $refer = $this->objMemcached->get($this->refer);
  49. print_r($refer);die;
  50. $param = $data;
  51. $param['uid'] = $data['openid'];
  52. $refer .= '&' . http_build_url($param);
  53. header ( "Location: " . $refer);
  54. } else {
  55. print_r($data);die;
  56. }
  57. } else {
  58. print_r($data);die;
  59. }
  60. }
  61. private function httpGet($url) {
  62. $curl = curl_init();
  63. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  64. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  65. curl_setopt($curl, CURLOPT_URL, $url);
  66. $res = curl_exec($curl);
  67. curl_close($curl);
  68. return $res;
  69. }
  70. }