oauth.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. class oauth_c extends Control
  3. {
  4. function __construct()
  5. {
  6. parent::Control();
  7. }
  8. function oauth_c()
  9. {
  10. $this->__construct();
  11. }
  12. function index_f()
  13. {
  14. $_SESSION["oauthuser_info"]=false;
  15. $code = $_GET['code'];
  16. $state = $_GET['state'];
  17. //换成自己的接口信息
  18. $appid = '';
  19. $appsecret = '';
  20. if($this->sys_config[Appid]&&strlen($this->sys_config[Appid])>1){
  21. $appid=$this->sys_config[Appid];
  22. $appsecret=$this->sys_config[Appsecret];
  23. }else if($this->STCModel->Appid)
  24. {
  25. $appid=$this->STCModel->Appid;
  26. $appsecret=$this->STCModel->Appsecret;
  27. }
  28. if (empty($code)) $this->error('授权失败');
  29. $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
  30. $token = json_decode(file_get_contents($token_url));
  31. if (isset($token->errcode)) {
  32. echo '<h1>错误:</h1>'.$token->errcode;
  33. echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
  34. exit;
  35. }
  36. $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
  37. //转成对象
  38. $access_token = json_decode(file_get_contents($access_token_url));
  39. if (isset($access_token->errcode)) {
  40. echo '<h1>错误:</h1>'.$access_token->errcode;
  41. echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
  42. exit;
  43. }
  44. $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
  45. //转成对象
  46. $user_info = json_decode(file_get_contents($user_info_url));
  47. if (isset($user_info->errcode)) {
  48. echo '<h1>错误:</h1>'.$user_info->errcode;
  49. echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
  50. exit;
  51. }
  52. $_SESSION["oauthuser_info"]=$user_info;
  53. header('location:'.$this->url('login'));
  54. //echo "<script> alert('sucess');parent.location.href='".$this->url('login')."'; </script>";
  55. //error('',$this->url('login'));
  56. //打印用户信息
  57. //echo '<pre>';
  58. //print_r($user_info);
  59. //echo '</pre>';
  60. }
  61. }
  62. ?>