callback.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: james
  5. * Date: 2017/4/25
  6. * Time: 下午3:43
  7. */
  8. include 'config.php';
  9. //判断state是否正确
  10. if(empty($_GET['state'])) {
  11. exit('参数错误,请重新登录');
  12. }
  13. if($_GET['state'] != $_SESSION['state']) {
  14. exit('<script>alert("参数错误!");
  15. location.href="../login.php";</script>');
  16. }
  17. //检查用户是否同意授权
  18. if(empty($_GET['code'])) {
  19. exit('<script>alert("您没有同意授权!");
  20. location.href="../login.php";</script>');
  21. }
  22. /*
  23. * 通过code换取网页授权access_token
  24. * https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
  25. */
  26. $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.appID.
  27. '&secret='.appsecret.
  28. '&code='.$_GET['code'].
  29. '&grant_type=authorization_code';
  30. //通过curl获取access_token
  31. $res = myCurl($url);
  32. /*
  33. * 正确返回
  34. * { "access_token":"ACCESS_TOKEN","expires_in":7200, "refresh_token":"REFRESH_TOKEN","openid":"OPENID","scope":"SCOPE" }
  35. * 错误返回
  36. * {"errcode":40029,"errmsg":"invalid code"}
  37. */
  38. //将json信息转换为数组
  39. $info = json_decode($res, true);
  40. //判断是否成功
  41. if(empty($info['access_token'])){
  42. exit('参数错误,请重新登录...');
  43. }
  44. /* 获取用户信息
  45. * 请求地址:
  46. * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
  47. * 正确时返回的JSON数据包如下:
  48. * openid 用户的唯一标识
  49. * nickname 用户昵称
  50. * 其他相信查看手册
  51. * 错误时微信会返回JSON数据包如下(示例为openid无效):
  52. * {"errcode":40003,"errmsg":" invalid openid "}
  53. */
  54. $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$info['access_token'].'&openid='.$info['openid'].'&lang=zh_CN';
  55. $res = myCurl($url);
  56. //将json信息转换为数组
  57. $user = json_decode($res, true);
  58. if(!empty($user['errcode'])) {
  59. exit('参数错误,请重新登录...');
  60. }
  61. //注册session 并返回登录页面
  62. $_SESSION['wxopenid'] = $user['openid'];
  63. $_SESSION['uface'] = $user['headimgurl'];
  64. $_SESSION['uname'] = $user['nickname'];
  65. header('location:');
  66. function myCurl($url, $type = 'GET', $data = null){
  67. $curl = curl_init();
  68. curl_setopt($curl, CURLOPT_URL , $url);
  69. curl_setopt($curl, CURLOPT_RETURNTRANSFER , true);
  70. if($type != 'GET'){
  71. curl_setopt($curl, CURLOPT_POST, 1);
  72. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  73. }
  74. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
  75. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST , false);
  76. curl_setopt($curl, CURLOPT_ENCODING , 'gzip,deflate');
  77. $res = curl_exec($curl);
  78. curl_close($curl);
  79. return $res;
  80. }