Home Backend Development PHP Tutorial 微信开发之网页授权获取用户信息(二)_PHP

微信开发之网页授权获取用户信息(二)_PHP

May 28, 2016 am 11:49 AM
WeChat webpage

在公众号的配置过程中,许多开发者会在菜单中加入HTML5页面,有时在页面内需要访问页面的用户信息,此时就需要网页授权获取用户基本信息

提醒大家:本文介绍讲述的内容是基于yii2.0框架

1、设置授权回调域名:开发 ---> 接口权限

  找到“网页授权获取用户基本信息”,点击后面对应的“修改”,在弹框响应位置填写授权回调域名即可,此处的域名不需要加http:// (关于网页授权回调域名的说明详情可参考公众平台开发者文档)


2、获取授权

  关于OAuth2.0博主参考的是方倍工作室的博文http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html(PS:方倍是一个微信开发大神,其中的微信开发内容还是比较详细的,推荐参考),其中详细剖析了微信官方文档的相关内容,也提供了获取授权的更详细思路和方案。

  实际上,获取用户信息的关键在于获取用户的openid。博主想要实现用户点击公众号菜单打开页面即可自动授权,从而针对该用户进行数据库操作,于是有下面两种方式: 

  (1)利用自定义菜单请求授权页面

    自定义菜单后面会单独写一篇博文,在这里先简述一下通过自定义菜单进行授权,该方法需要高级接口权限,且局限于关注公众号的用户直接从菜单进入页面。

$menu = '{
"button":[
{
"type": "view",
"name": "商城",
"url": "https://open.weixin.qq.com/connect/oauth/authorize?appid=xxx&redirect_uri=http://tx.heivr.com/index.php&response_type=code&scope=snsapi_base&state=#wechat_redirect"
},
{
"name":"快递服务",
"sub_button":[
{
"type":"click",
"name":"发快递",
"key":"express"
},
{
"type":"click",
"name":"快递查询",
"key":"ww"
}
]
},
]
}'; 
Copy after login

需要授权的view直接在url处填写微信提供的授权请求地址,其中:

•appid:填写微信公众平台基本配置中的AppID;
•redirect_uri:填写授权完成后跳转的页面地址,即自己的html5页面;
•state:跳转至回调页面所带参数;
•response_type:网页授权的两种scope,微信官方文档中说明如下:

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)

2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
按照此方法点击“商城”即可接收到返回的openid,继而进行下一步用户信息的获取。 

(2)利用JS自动请求授权页面

这个方法相对而言比较笨拙,步骤略复杂,但目前能解决需求还没有研究简化方法,且由于页面的跳转多数情况下访问页面的时间会增加,但相比于前一个方法,该方法可以获取到非关注用户的基本信息。有些程序可能涉及到页面分享,程序没有强制关注但其他用户通过分享直接进入页面也需要记录用户信息,此时可以考虑该方法。(微信开发相关的代码博主封装成工具类调用,这里先贴用到的部分,以后整理完成会全部贴出来并附下载链接)

该方法的思路为:js请求链接获取code ---> 利用code换取openid ---> 得到用户基本信息

a. 编辑配置

为了方便把用到的一些微信参数单独写入一个类,方便修改添加及调用

<&#63;php
namespace common\tools\wechat;
/**
* 微信请求相关配置类库
*/
class ConfigTool {
/**
* 微信配置参数
* @return array 配置参数
*/
public function setConfig() {
// 用于验证微信接口配置信息的Token,可以任意填写
$config['token'] = '自己的token';
// appID
$config['appid'] = '自己的appid';
// appSecret
$config['secret'] = '自己的secret';
// 回调链接地址
$config['redirect_uri'] = 'http://tx.heivr.com/index.php&#63;';
// 是否以 HTTPS 安全协议访问接口
$config['https_request'] = false;
// 授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
// snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,
// 即使在未关注的情况下,只要用户授权,也能获取其信息)
$config['scope'] = 'snsapi_userinfo';
// 语言
$config['lang'] = 'zh_CN'; // zh_CN 简体,zh_TW 繁体,en 英语
// 微信公众账户授权地址
$config['mp_authorize_url'] = 'https://api.weixin.qq.com/cgi-bin/token';
// 微信公众账户js临时票据地址
$config['jsapi_ticket_url'] = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
// 授权地址
$config['authorize_url'] = 'https://open.weixin.qq.com/connect/oauth/authorize';
// 获取access token 的地址
$config['access_token_url'] = 'https://api.weixin.qq.com/sns/oauth/access_token';
// 刷新 token 的地址
$config['refresh_token_url'] = 'https://api.weixin.qq.com/sns/oauth/refresh_token';
// 获取用户信息地址
$config['userinfo_url'] = 'https://api.weixin.qq.com/sns/userinfo';
// 验证access token
$config['valid_token_url'] = 'https://api.weixin.qq.com/sns/auth';
// 上传临时素材地址
$config['media_temp_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/media/upload&#63;';
// 上传永久素材地址
$config['media_forever_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/material/add_material&#63;';
return $config;
}
}
Copy after login

b. https请求工具

<&#63;php
namespace common\tools;
/**
* https请求相关类库
*/
class HttpsTool {
const TIMEOUT = ; // 设置超时时间
private $ch; // curl对象
/**
* 发送curl请求,并获取请求结果
* @param string 请求地址
* @param array 如果是post请求则需要传入请求参数
* @param string 请求方法,get 或者 post, 默认为get
* @param bool 是否以https协议请求
*/
public function send_request($requests, $params = null, $method = 'get', $https = true) {
// 以get方式提交
if ($method == 'get') {
if($params){
$request = $requests . $this->create_url($params);
}else{
$request = $requests;
}
}else{
$request = $requests;
}
$this->ch = curl_init($request);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, );// 设置不显示结果,储存入变量
curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 设置超时限制防止死循环
// 判断是否以https方式访问
if ($https) {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, ); // 对认证证书来源的检查
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, ); // 从证书中检查SSL加密算法是否存在
}
if ($method == 'post') { // 以post方式提交
//curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false); //php .文件上传必加内容,.不需要
curl_setopt($this->ch, CURLOPT_POST, ); // 发送一个常规的Post请求
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的数据包
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, );
}
$tmpInfo = curl_exec($this->ch); // 执行操作
if (curl_errno($this->ch)) {
echo 'Errno:'.curl_error($this->ch);//捕抓异常
}
curl_close($this->ch); // 关闭CURL会话
//var_dump($tmpInfo);exit;
return $tmpInfo; // 返回数据
}
/**
* 生成url
*/
public function create_url($data) {
$temp = '&#63;';
foreach ($data as $key => $item) {
$temp = $temp . $key . '=' . $item . '&';
}
return substr($temp, , -);
}
}
Copy after login

关于curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false)会在微信图片资源上传博文中详细讲述它出现的心酸史,这里暂时用不到,不做解释

c. 授权基类

<&#63;php 
namespace common\tools\wechat;
use common\tools\wechat\ConfigTool;
use common\tools\HttpsTool;
/**
* Weixin_oauth 类库
*/
class OauthTool {
public $conf;
public function __construct(){
$re = new ConfigTool; 
$this->conf = $re->setConfig();
} 
/**
* 生成用户授权的地址
* @param string 自定义需要保持的信息
* @param sting 请求的路由
* @param bool 是否是通过公众平台方式认真
*/
public function authorize_addr($route, $state='', $mp=false) {
if ($mp) {
$data = [
'appid' => $this->conf['appid'],
'secret' => $this->conf['token'],
'grant_type' => 'client_credential'
];
$url = $this->conf['mp_authorize_url'];
} else {
$data = [
'appid' => $this->conf['appid'], //公众号唯一标识
'redirect_uri' => urlencode($this->conf['redirect_uri'] . $route), //授权后重定向的回调链接地址
'response_type' => 'code', //返回类型,此处填写code
'scope'=>$this->conf['scope'], //应用授权作用域
'state'=>$state, //重定向后带上state参数,开发者可以填写任意参数
'#wechat_redirect'=>'' //直接在微信打开链接,可不填,做页面重定向时必须带此参数
];
$url = $this->conf['authorize_url'];
}
$send = new HttpsTool;
//var_dump($url . $send->create_url($data));exit;
return $url . $send->create_url($data);
}
/**
* 获取 access token
* @param string 用于换取access token的code,微信提供
*/
public function access_token($code) {
$data = [
'appid' => $this->conf['appid'],
'secret' => $this->conf['secret'],
'code' => $code,
'grant_type' => 'authorization_code'
];
// 生成授权url
$url = $this->conf['access_token_url'];
$send = new HttpsTool;
return $send->send_request($url, $data);
}
/**
* 获取用户信息
* @param string access token
* @param string 用户的open id
*/
public function userinfo($token, $openid) {
$data = [
'access_token' => $token,
'openid' => $openid,
'lang' => $this->conf['lang']
];
// 生成授权url
$url = $this->conf['userinfo_url'];
$send = new HttpsTool;
return $send->send_request($url, $data);
}
}
Copy after login

d. 授权基类调用及用户数据处理(在控制器调用前,先对用户数据存入或更新)

<&#63;php
namespace wechat\controllers\classes;
use common\tools\wechat\OauthTool;
use common\models\User;
use common\tools\EmojiTool;
/**
* 微信用户基本信息获取
*/
class UserinfoClass {
/**
* 用户授权并获取code 
* @return string 用户code
*/
public function getCode($route, $state){
$re = new OauthTool;
$request = $re->authorize_addr($route, $state);
$code = isset($_GET['code']) &#63; $_GET['code'] : '';
return [$request,$code];
}
/**
* 获取用户信息并写入数据库(之后加参数传给code)
*/
public function info($code) {
$re = new OauthTool;
//获取access token
$access = $re->access_token($code);
$token = json_decode($access,true);
//header("Content-type: text/html; charset=gbk"); 
//获取用户信息
if(count($token) != ) {
$response = $re->userinfo($token['access_token'], $token['openid']);
$user = json_decode($response,true);
//用户昵称转换
//$user['nickname'] = EmojiTool::emoji_trans($user['nickname']);
if($model = User::findOne(['openid' => $user['openid'] ])) { //用户已存在更新数据
$model->attributes = $user;
$model->modify_time = time();
$model->save(false);
}else{ //用户不存在写入
$model = new User;
$model->attributes = $user;
$model->create_time = time();
$model->save(false);
}
}
return isset($model->id) &#63; $model->id : '';
}
} 
Copy after login

e. 控制器调用(这里只贴其中一个方法)

/**
* 产品列表
* @return object 所有可用产品信息
*/
public function actionIndex(){
//判断页面是否自动刷新
if(isset($_GET['state'])) {
$refresh = ;
}else{
$refresh = ;
}
//获取用户code
$user = new UserinfoClass;
$request = $user->getCode('r=store/index', );
//该用户userid
$userid = $user->info($request[]);
$model = new Product;
$list = $model->find()->where(['status' => ])->all();
return $this->render('index',['list' => $list, 'refresh' => $refresh, 'userid' => $userid, 'request' => $request]);
}
Copy after login

程序要求用户打开产品列表即获取用户信息并存入数据库,其中设计了几个变量作用如下:

$refresh:判断页面是否刷新,由于首次打开页面未进行oauth验证时才自动请求验证,避免反复刷新,这里用回调的state参数作为判断依据且设state=1(若有特定参数需要可将state赋值为所需值);

$request:即为验证请求地址

f. 视图自动刷新

只需要在视图中添加以下js代码即可

<script type="text/javascript">
//自动请求获取code
$(function(){
var refresh = <&#63;= $refresh; &#63;>;
var request = '<&#63;= $request[]; &#63;>';
if(refresh == ){
console.log();
location = request;
}
});
</script>
Copy after login

以上内容给大家介绍了微信开发之网页授权获取用户信息(二)的全部叙述,希望本文分享能够给大家带来帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles