微信公众平台实现获取用户OpenID的方法_PHP

WBOY
Release: 2016-06-01 14:35:14
Original
897 people have browsed it

本文实例讲述了微信公众平台实现获取用户OpenID的方法。分享给大家供大家参考。具体分析如下:

用户点击微信自定义菜单view类型按钮后,微信客户端将会打开开发者在按钮中填写的url值 (即网页链接),达到打开网页的目的,但是view不能获取用户的openid,需要使用微信“网页授权获取用户基本信息”高级接口结合使用,获得用户的登入个人信息。

具体方法:

1、配置网页授权回调域名,如 www.bitsCN.com

2、模拟公众号的第三方网页,http://www.bitsCN.com/getcodeurl.php

<&#63;php 
if(isset($_SESSION['user'])){ 
 print_r($_SESSION['user']);
exit;
}
$APPID='公众号在微信的appid';
$REDIRECT_URI='http://www.bitsCN.com/callback.php';
$scope='snsapi_base';
//$scope='snsapi_userinfo';//需要授权
$url='https://open.weixin.qq.com/connect/oauth2/authorize&#63;appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
header("Location:".$url);
&#63;>
Copy after login

3、第三方网页的回跳url中,首先从请求中取得code,然后根据code进一步换取openid和access_token,然后就可以根据openid和access_token调用微信的相关接口查询用户信息了。

<&#63;php
//http://www.bitsCN.com/callback.php
$appid = "公众号在微信的appid"; 
$secret = "公众号在微信的app secret"; 
$code = $_GET["code"]; 
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token&#63;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&#63;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); 
&#63;>
Copy after login

希望本文所述对大家基于php的微信公众平台开发有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template