php微信公众平台开发之获取用户基本信息_php实例
本文的方法将囊括订阅号和服务号以及自定义菜单各种场景,无论是否有高级接口权限,都有办法来获得用户基本信息,而无需模拟登录。
把微信和第三方网站结合起来运行,是许多客户经常要的方案。这里简要介绍一下获取微信用户的基本信息,并在第三方网站直接登录。
当微信公户关注一个公众号时,会产生一个独一无二的OpenID,此时我们就需要用到它去请求微信服务器获取用户的基本信息,包括头像,昵称等。
更加详细的说明请参考 微信开发文档 。
获取的步骤如下:
1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
5 附:检验授权凭证(access_token)是否有效
一、在微信公众平台 —— 开发者中心 : 网页授权获取用户基本信息 :点击 “修改”,配置网页回调域名
二、用户授权获取code
必备资源:
$appid = ‘*****************';
$appsecret = ‘*************************';
注:redirect_url是授权后重定向的回调链接地址,请使用urlencode对链接进行处理。
在网站入口处加上配置的 $url = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=http%3A%2F%2Fjixian.c.zmit.cn%2F&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect';
并请求访问上诉 url 。
当用户授权后,回调设置的域名,并会在url参数中拼接我们所需要的code,我们直接用 $_GET[‘code'] 获取即可!
三、通过code获取网页授权access_token和openid
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
$opendid= $token->openid;
$access_token = $token->access_token;
四、获取用户信息
$info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$opendid.'⟨=zh_CN';
$info = json_decode(file_get_contents($info_url));
$data['name'] = $info->nickname;
$data['image'] = $info->headimgurl;
print_r($info);
五、当获取到用户的openid等信息后,我们就可以将其存入数据库,只要有openid了,就相当于微信用户已经登录该网站!
使用AppID和AppSecret获取的access_token,通过全局Access Token获取用户基本信息
1. 用户关注以及回复消息的时候,均可以获得用户的OpenID
<xml> <ToUserName><![CDATA[gh_b629c48b653e]]></ToUserName> <FromUserName><![CDATA[ollB4jv7LA3tydjviJp5V9qTU_kA]]></FromUserName> <CreateTime>1372307736</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[subscribe]]></Event> <EventKey><![CDATA[]]></EventKey> </xml>
其中的FromUserName就是OpenID
2. 然后使用access_token接口,请求获得全局Access Token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
返回结果:
{ "access_token": "NU7Kr6v9L9TQaqm5NE3OTPctTZx797Wxw4Snd2WL2HHBqLCiXlDVOw2l-Se0I-WmOLLniAYLAwzhbYhXNjbLc_KAA092cxkmpj5FpuqNO0IL7bB0Exz5s5qC9Umypy-rz2y441W9qgfnmNtIZWSjSQ", "expires_in": 7200 }
3. 再使用全局ACCESS_TOKEN获取OpenID的详细信息
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID
返回如下:
{
"subscribe": 1,
"openid": "oLVPpjqs2BhvzwPj5A-vTYAX4GLc",
"nickname": "刺猬宝宝",
"sex": 1,
"language": "zh_CN",
"city": "深圳",
"province": "广东",
"country": "中国",
"headimgurl": "http://wx.qlogo.cn/mmopen/JcDicrZBlREhnNXZRudod9PmibRkIs5K2f1tUQ7lFjC63pYHaXGxNDgMzjGDEuvzYZbFOqtUXaxSdoZG6iane5ko9H30krIbzGv/0",
"subscribe_time": 1386160805
}
至此,获得用户的基本信息。
这种方式最适合用户在关注的时候,回复一条欢迎关注+用户昵称的信息,如关注下面公众账号时的回复所示。扫描二维码可体验。
以上就是本文针对php微信公众平台开发之获取用户基本信息的全部内容,希望大家喜欢。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
