Heim  >  Artikel  >  php教程  >  微信公众平台实现获取用户OpenID的方法,公众openid

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

WBOY
WBOYOriginal
2016-06-13 09:06:57969Durchsuche

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

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

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

具体方法:

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

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

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

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

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn