Home  >  Article  >  Backend Development  >  微信公众平台实现获取用户OpenID的方法_php实例

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

WBOY
WBOYOriginal
2016-06-07 17:13:22963browse

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

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

具体方法:

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

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

<&#63;php 
if(isset($_SESSION['user'])){ 
 print_r($_SESSION['user']);
exit;
}
$APPID='公众号在微信的appid';
$REDIRECT_URI='http://www.php.net/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;>

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

<&#63;php
//http://www.php.net/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;>

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

Statement:
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