第一种方法:通过发送信息的形式,获取FromUserName(就是openid);
switch ($MsgType) {
case "text":
$replyMsg = "你的OpenID为:" . $object->FromUserName;
$replyXml = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
break;
}
$resultStr = sprintf($replyXml, $FromUserName, $ToUserName, time(), $replyMsg);
echo $resultStr;
第二种方法:通过OAuth2.0网页授权,自定义菜单中响应
$create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
$redirect_uri = urlencode("http://www.zhosoft.com");
$scope = "snsapi_userinfo"; //snsapi_base 、snsapi_userinfo
$oauth2_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=1#wechat_redirect";
$yishou_url = "http://yishoutest.cailai.com";
echo $oauth2_url;
$post = ' {
"button":[
{
"type":"view",
"name":"官网测试",
"url":"' . $oauth2_url . '"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.zhosoft.com/"
},
{
"type":"view",
"name":"视频",
"url":"http://www.zhosoft.com/"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
}]
}';
获取code ,通过code在获取openid ,然而再获取userinfo;
$appid = "appid";
$secret = "secret";
$code = $_GET["code"];
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $get_token_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res, true);
//根据openid和access_token查询用户信息
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $get_user_info_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
//解析json
$user_obj = json_decode($res, true);
$_SESSION['user'] = $user_obj;
print_r($user_obj);
第二种方法需要注意的是
转载请注明出处:http://blog.csdn.net/churk2012/article/details/50687476