index.php

<?php
$appid='wx9e';
$redirect_uri='http://z.weipenglai.com/7/wx/openId/redirect.php';
$scope='snsapi_base';
$state='state';
$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
header("Location:".$url);

通过点击index.php页面来跳转到redirect.php来显示访问者的openId。

redirect.php

<?php
$appid = "wx"; 
$secret = ""; 
$code = isset($_GET['code'])?$_GET['code']:'';//获取code
$get_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";//通过code换取网页授权access_token
$ch = curl_init();  
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);curl_close($ch); 
$json_obj =json_decode($res,true);
$openid=$json_obj["openid"];
print_r($res);