1 <?php 2 //启用session 3 session_start(); 4 //编码 5 header("Content-type: text/html; charset=utf-8"); 6 //保存微信openid 7 $weixin_openid = ""; 8 //保存从微信得到的code 9 $code = ""; 10 //获得菜单中设置的state值 11 $state = ""; 12 13 //修改为注册的测试号信息 14 $appid = "wx834404c1d1dbb5ec"; 15 $secret = "bf03cfa823d80dd537bd18e83ce9a4e4"; 16 17 if (isset($_GET[‘code‘]) && isset($_GET[‘state‘]) ){ 18 $weixin_openid = GetOpenid($_GET[‘code‘]); 19 $code = $_GET[‘code‘]; 20 $state = $_GET[‘state‘]; 21 //echo $resultStr; 22 }else{ 23 echo "NO CODE"; 24 return ; 25 } 26 27 // store session data 28 $_SESSION[‘weixin_openid‘]=$weixin_openid; 29 30 if($state == "s1"){ 31 //我的课堂 32 header(‘Location: courseCenter.php‘); 33 }else if($state == "s2"){ 34 //订单记录 35 header(‘Location: orderList.php‘); 36 }else{ 37 $textTpl="由认证接口进入我的课堂,<br/>您的 wx_openid: %s <br/> code: %s <br/> state: %s <br/> 38 <a href=‘orderList.php‘>订单记录</a>"; 39 $resultStr = sprintf($textTpl, $weixin_openid, $code, $state); 40 41 echo $resultStr ; 42 } 43 44 45 46 //获取微信的openid 47 function GetOpenid($c_code) 48 { 49 $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $c_code . "&grant_type=authorization_code"; 50 //$url = "http://www.baidu.com"; 51 $result = getData($url); 52 53 $jsondecode = json_decode($result); 54 if($jsondecode != null){ 55 if(property_exists ( $jsondecode, "openid" ) ) 56 { 57 return $jsondecode->{"openid"}; 58 }else{ 59 return "code is invalid."; 60 } 61 } 62 63 return null; 64 } 65 //获取https的get请求结果 66 function getData($c_url) 67 { 68 $curl = curl_init(); // 启动一个CURL会话 69 curl_setopt($curl, CURLOPT_URL, $c_url); // 要访问的地址 70 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 71 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在 72 curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER[‘HTTP_USER_AGENT‘]); // 模拟用户使用的浏览器 73 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 74 curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer 75 // curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 76 // curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 77 curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环 78 curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 79 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 80 $tmpInfo = curl_exec($curl); // 执行操作 81 if (curl_errno($curl)) { 82 echo ‘Errno‘.curl_error($curl);//捕抓异常 83 } 84 curl_close($curl); // 关闭CURL会话 85 return $tmpInfo; // 返回数据 86 } 87 88 ?>