Table of Contents
WeChat development webpage authorization to obtain user information (2), user information
您可能感兴趣的文章:
Home Backend Development PHP Tutorial WeChat development webpage authorization to obtain user information (2), user information_PHP tutorial

WeChat development webpage authorization to obtain user information (2), user information_PHP tutorial

Jul 12, 2016 am 09:01 AM
Scope Authorize User Info Web page Obtain

WeChat development webpage authorization to obtain user information (2), user information

During the configuration process of the public account, many developers will add HTML5 pages to the menu, sometimes in The page needs to access the user information of the page. At this time, the web page authorization is required to obtain the user’s basic information

Bangkejia reminds everyone: the content introduced in this article is based on the yii2.0 framework

1. Set authorization callback domain name: Development ---> Interface permissions

Find "Web page authorization to obtain basic user information", click the corresponding "Modify" at the end, and fill in the authorization callback domain name in the response position of the pop-up box. The domain name here does not need to add http:// (about the web page authorization callback domain name) For detailed instructions, please refer to the public platform developer documentation)


2. Obtain authorization

About OAuth2.0 bloggers refer to the blog post of Fangbei Studio http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html (PS: Fangbei is a WeChat development master, among whom The content of WeChat development is relatively detailed, and it is recommended to refer to it), which analyzes the relevant content of WeChat official documents in detail, and also provides more detailed ideas and solutions for obtaining authorization.

In fact, the key to obtaining user information is to obtain the user's openid. The blogger wants to realize that users can automatically authorize themselves by clicking on the official account menu to open the page, so as to perform database operations on the user, so there are two ways:

(1) Use the custom menu to request authorization page

I will write a separate blog post after the custom menu. Here I will briefly describe authorization through the custom menu. This method requires advanced interface permissions and is limited to users who follow the official account and enter the page directly from the menu.

$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

For views that require authorization, directly fill in the authorization request address provided by WeChat at the url, where:

•appid: Fill in the AppID in the basic configuration of WeChat public platform;
•redirect_uri: Fill in the address of the page that will jump after authorization is completed, that is, your own html5 page;
•state: parameters for jumping to the callback page;
•response_type: Two scopes for web page authorization. The official WeChat documentation explains as follows:

1. Web page authorization initiated with snsapi_base as the scope is used to obtain the openid of the user who enters the page, and is authorized silently and automatically jumps to the callback page. What users perceive is that they directly enter the callback page (often a business page)

2. Web page authorization initiated with snsapi_userinfo as the scope is used to obtain the user's basic information. However, this kind of authorization requires the user to manually agree, and since the user has agreed, there is no need to pay attention, and the user's basic information can be obtained after authorization.
According to this method, click "Mall" to receive the returned openid, and then proceed to the next step of obtaining user information.

(2) Use JS to automatically request the authorization page

This method is relatively clumsy and the steps are slightly complicated. However, there is currently no simplified method that can solve the needs. In addition, due to page jumps, the time to access the page will increase in most cases, but compared to the previous method, This method can obtain basic information about non-following users. Some programs may involve page sharing. The program does not force following, but other users who enter the page directly through sharing also need to record user information. In this case, you can consider this method. (The code bloggers related to WeChat development are encapsulated into tool calls. The used parts are posted here first. After the arrangement is completed, they will all be posted with download links)

The idea of ​​this method is: js request link to get code ---> Use code in exchange for openid ---> Get basic user information

a. Edit configuration

In order to facilitate the writing of some WeChat parameters used in a separate class, it is convenient to modify, add and call

<&#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 request tool

<&#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

Regarding curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false), the sad history of its appearance will be described in detail in the WeChat image resource upload blog post. It will not be used here for the time being and will not be explained

c. Authorization base class

<&#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. Authorization base class call and user data processing (user data is stored or updated before controller call)

<&#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. Controller call (only one of the methods is posted here)

/**
* 产品列表
* @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

The program requires the user to open the product list to obtain user information and store it in the database. Several variables are designed with the following functions:

$refresh: Determine whether the page is refreshed. Since the page is opened for the first time without oauth verification, verification is automatically requested to avoid repeated refreshes. Here, the state parameter of the callback is used as the basis for judgment and state=1 (if there are specific parameters required, you can Assign state to the required value);

$request: is the verification request address

f. View automatic refresh

Just add the following js code to the view

<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

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

您可能感兴趣的文章:

  • PowerShell获取Windows用户列表、用户信息的方法
  • php curl登陆qq后获取用户信息时证书错误

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1089942.htmlTechArticle微信开发之网页授权获取用户信息(二),用户信息 在公众号的配置过程中,许多开发者会在菜单中加入HTML5页面,有时在页面内需要访问页...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

There are several situations where this in js points to There are several situations where this in js points to May 06, 2024 pm 02:03 PM

In JavaScript, the pointing types of this include: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

How are closures implemented in Java? How are closures implemented in Java? May 03, 2024 pm 12:48 PM

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

See all articles