当前位置:网站首页>Wechat official account release reminder (wechat official account template message interface)
Wechat official account release reminder (wechat official account template message interface)
2022-07-26 10:19:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
Main contents of this paper : - 1. Project brief introduction
- Function description :
- Characteristics contrast
- Function description :
- Characteristics contrast
- 2. Project screenshots
- 3. The development of preparation
- 3.1 development tool
- 3.2 Environmental support
- 1、 Access to official account development information :
- 2、 Set up IP White list
- 3、 Configure the domain name
- 4、 Add developers
- 4. Interpretation of official reference documents
- 5. Web authorization login implementation (PHP For example )
- 5.1 Tool class GetWX
- 5.2 obtain code
- 5.3 Exchange for access_token
- 5.4 Get user information
- 5.5 Another complete example
- 6. Template message push implementation (PHP For example )
- 6.1 official JSSDK file (PHP)
- 6.2 Template message JSON turn
- 6.3 Send template message
- 7. Postscript and source code
1. Project brief introduction
Inspiration comes from the school Daily health daily
, It is required to use wechat applet to punch in daily health . So the function of this project is similar to QQ Group robots
, Or is it Daily alarm clock
.
Function description :
Users visit a given page , Conduct Authorized login
, Then confirm your identity ( Undergraduate or graduate ), and Turn on notification
, You can receive the message reminder of wechat service number at the appointed time every day . Of course , Users can customize the time of daily notification , Daily notifications can also be turned on or off at any time .
Characteristics contrast
- and QQ Group robots 、 Compared with the alarm clock , The realization of this function , It is convenient for users to directly access the applet with one click .
- But this method Pay attention to the service number , At the same time, the development threshold is high .
2. Project screenshots
On the left : Pages subscribed by users , Chinese : The page on which the user modifies the notification time , Right picture : The user receives a message reminder
3. The development of preparation
3.1 development tool
1、 Coding tools : For project development . If you use Java
Realization , You can use IntelliJ IDEA
, If you use PHP
Development , You can use JetBrains PhpStorm
;
2、 Run the tool : For local testing . If it is PHP
Development , Can choose phpstudy_pro
As PHP The running and deployment environment of the project ;
3、 Testing tools : Only use WeChat developer tools
, Development mode selection official account
Web debugging
.
Wechat developer tool download address :https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
Because it involves wechat authorized login function , So the test tool must use WeChat developer tools
, But ordinary browsers cannot realize this function .
How to use and debug wechat developer tools , Consistent with ordinary browsers .
3.2 Environmental support
1、 Any domain name , Need to open SSL( namely https visit );
2、 A wechat service number , Must be certified ;
3、 With external network IP One server .
If it's just learning technology , Meet the first two items . If the project needs to go online , The above three are indispensable . For the first 2 strip , No service number , It can also be in
Wechat open platform
Create a website application . However, wechat open platform also needs enterprise certification .
When the above environment is satisfied , Next, you need to configure the wechat service number . There are mainly :
1、 Access to official account development information :
The development information of official account is mainly developer ID(AppID)
and Developer password (AppSecret)
.
Some interfaces must use developers ID And the developer password can make the call request .
The access path is : WeChat official account background → Development → Basic configuration
.
2、 Set up IP White list
Only IP White list
Medium IP Address can be called obtain access_token Interface
, among access_token Is to carry out other operations , Necessary parameters such as sending message template .
3、 Configure the domain name
The page access path of the configuration domain name is : Official account background → Set up → Setting of public number → Feature set
.
There are three main domain names that need to be configured :
① Business domain name
After setting the business domain name , When visiting the page under the domain name in wechat , Will not be rearranged . When the user enters the domain name , No safety tips . For example, open a web page in wechat , When entering a form , There will be no “ Please do not enter QQ password ” Wait for safety tips .
② JS Interface security domain name
Set up JS After interface security domain name , Developers of official account can be downloaded with WeChat. JS Interface . For example, in the previous article access_token Acquisition , You need to use this domain name .
③ Authorized domain name of web page
After the user agrees to authorize to the official account on the web page authorization page , Wechat will send the authorization data to a callback page , The callback page needs to be under this domain name , To ensure safety and reliability .
4、 Add developers
Only added developers , Can be used web Developer tools
Develop and debug the corresponding official account .
The access path of the add developer page is : WeChat official account background → Development → Developer tools → web Developer tools
.
5、 Add the template
stay Add function plug-in
Module , add to Template message
function
Then in the template library , Search for the right template , Add :
Template ID It is the parameter used in development .
4. Interpretation of official reference documents
About the development technology of wechat official account , And its implementation route , It is introduced on the official website .
Official documents :https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
Open the official development document , The title of the first unit is required reading before development , It is still necessary to read the developer specification and global return code description chapters .
When developing , Do not violate the relevant specifications of wechat , Otherwise, it is easy to be sealed , Then the global return code can help quickly locate the problem .
4.1 Web authorization login interpretation
Open the official development document , The first 5 Chapter WeChat web development
in , The first 2 Section is Web page authorization
Reference documents for .
Direct link :https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
Before the table of contents of this chapter , There is a paragraph about web authorization .
The first point Explanation on the domain name of webpage authorization callback , That is, the configuration of the domain name in the previous article . Second point Two kinds of web page authorization scope Description of the differences , It mainly describes two authorization modes , One is silent login authorization , This form can only get users OpenID, The other is to obtain the basic information of users , This form will pop up , Users need to manually click login . Two ways of implementation , Mainly to modify the login link scope The value of the parameter . Detailed description later . The third point About web licensing access_token And the general access_token The difference between , Refer to the documentation . In fact, the main description is web authorization access_token It's more secure , Must pass code To get access_token, And it's different code Acquired access_token Different , every last access_token The period of validity 2 Hours (7200 second ), Every access_token Here 2 Within hours , Only valid for the same user . And ordinary access_token( That is, in basic support “ obtain access_token” Interface ) You can get it directly , Different scenes can be reused , Also valid for 2 Hours , Obsolete needs to be refreshed .
To be specific , The web authorization process is divided into four steps :
1、 Guide the user to enter the authorization page to approve the authorization , obtain code
2、 adopt code Website authorization access_token( And basic support access_token Different )
3、 if necessary , Developers can refresh web page authorization access_token, Avoid expiration
4、 Authorization via web page access_token and openid Get basic user information ( Support UnionID Mechanism )
1. obtain code
First, you need to enable users to access the following links , To log in :
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
In this link , Fields identified by uppercase letters , Need to be replaced ( The same below ).
The parameters in the above links are described in detail below :
Parameters | Whether must | explain |
---|---|---|
appid | yes | The only sign of official account number |
redirect_uri | yes | Callback link address redirected after authorization , Please use urlEncode Handling links |
response_type | yes | Return type , Only fill in code |
scope | yes | Application authorization scope , Only for snsapi_base ( Do not pop up the authorization page , Direct jump , Only users can be obtained openid) or snsapi_userinfo( Authorization page pops up , It can be done by openid Get a nickname 、 Gender 、 home . also , Even if you don't pay attention , As long as the user is authorized , Information can also be obtained ) |
state | no | Reset to bring back state Parameters , Developers can fill in a-zA-Z0-9 Parameter values for , most 128 byte |
#wechat_redirect | yes | Whether you open it directly or make a page 302 When redirecting , This parameter is required |
After the user confirms to log in , You can get it from the callback link address redirected after authorization code, The format is as follows :
redirect_uri/?code=CODE&state=STATE
there CODE Is the next exchange access_token Parameters must be , and STATE Other information customized by developers .
2. Exchange for access_token
It's got code, Next you need to use this code In exchange for access_token.
The request link is as follows (GET The way ):
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
The parameters in the above links are described in detail below :
Parameters | Whether must | explain |
---|---|---|
appid | yes | The only sign of official account number 、 developer ID |
secret | yes | Members of the public, appsecret、 Developer password |
code | yes | Fill in the first step code Parameters |
grant_type | yes | Only for :authorization_code |
After the request is successful , Back to JSON The packet format is as follows :
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
About that JSON The fields of the data package are described as follows :
Parameters | explain |
---|---|
access_token | Web page authorization interface call certificate , Be careful : this access_token With basic support access_token Different |
expires_in | access_token Interface call credential timeout , Company ( second ) |
refresh_token | User refresh access_token, The period of validity 30 God . When access_token After a timeout , have access to refresh_token refresh . |
openid | User unique identification , Please note that , When we are not concerned about the official account number , User access to official account page , It will also produce a unique user and official account. OpenID |
scope | Scope of user authorization , Use a comma (,) Separate |
Here are the optional actions , Not usually used :
Use refresh_token
obtain access_token A link to the (GET The way ):
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
The parameters in the above links are described in detail below :
Parameters | Whether must | explain |
---|---|---|
appid | yes | The only sign of official account number |
grant_type | yes | Fill in for refresh_token |
refresh_token | yes | Pass through access_token Acquired refresh_token Parameters |
Correctly returned JSON The format is consistent with the above .
Some instructions : So let's go over here , We have got the user's OpenID. If you only do user uniqueness verification , This is the end . Again , For sending template messages , Only the user's OpenID.
3. Get user information
If the page authorization scope is snsapi_userinfo
, At this time, the developer can use the access_token
and openid
Pull user information .
The request link is as follows (GET The way 、 Need to use https agreement ):
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
The parameters of the above link are described as follows :
Parameters | describe |
---|---|
access_token | Web page authorization interface call certificate , That is, obtained in the previous steps access_token. |
openid | The unique identification of the user |
lang | Return to country language version ,zh_CN Simplified Chinese character ,zh_TW traditional Chinese character ,en English |
Returned after successful request JSON The packet format is as follows :
{
"openid":" OPENID",
"nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
Above JSON The parameters of the data package are described in detail as follows :
Parameters | describe |
---|---|
openid | The unique identification of the user |
nickname | The user nickname |
sex | Gender of user , The value is 1 It's male , The value is 2 It was a woman , The value is 0 Time is unknown |
province | Province filled in user profile |
city | City filled in by personal data of ordinary users |
country | Country , If China is CN |
headimgurl | The avatars , The last value represents the size of the square head ( Yes 0、46、64、96、132 Value optional ,0 representative 640*640 Square head ), This item is empty when the user does not have a picture . If the user changes the Avatar , Original head URL Will fail . |
privilege | User privilege information ,json Array , For example, wechat Waka users are (chinaunicom) |
unionid | Only when users bind the official account to WeChat open platform account. , This field will appear . |
attach : Inspection authorization certificate (access_token) Whether it works
Request link (GET Method 、 Need to use https agreement ):
https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
The parameters of the above link are described as follows :
Parameters | describe |
---|---|
access_token | Web page authorization interface call certificate , Be careful : this access_token With basic support access_token Different |
openid | The unique identification of the user |
Correct JSON The returned result of the packet is as follows :
{
"errcode":0,"errmsg":"ok"}
On error JSON Return to example :
{
"errcode":40003,"errmsg":"invalid openid"}
This method can detect access_token Is it overdue , To ensure the high availability of the project .
4.2 Template message push interpretation
Open the official development document , The first 4 Chapter Message management
in , The first 7 Section is Template message interface
Reference documents for .
Direct link :https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html
In the official documentation , The content described in this module at a large length , It is aimed at the third-party wechat service providers , So there are some that individual developers can't use .
Summarize the actual process of template message push , The main process is as follows :
1. Acquisition basis access_token
The request link is as follows (GET The way ):
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
The parameters in this link are described in detail below :
Parameters | Whether must | explain |
---|---|---|
grant_type | yes | obtain access_token Fill in client_credential |
appid | yes | Third party user unique credentials |
secret | yes | Third party user unique credential key , namely appsecret |
The request returned successfully JSON The packet format is as follows :
{
"access_token":"ACCESS_TOKEN","expires_in":7200}
JSON Packet parameter description :
Parameters | explain |
---|---|
access_token | Acquired credentials |
expires_in | Voucher effective time , Company : second |
2. Send message template
The request link is as follows (POST The way ):
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
In this link, you only need access_token
One parameter , That is, obtained in the first step access_token
.
POST The packet format is JSON Format , Examples are as follows :
{
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"miniprogram":{
"appid":"xiaochengxuappid12345",
"pagepath":"pages/index?foo=bar"
},
"data":{
"first": {
"value":" Congratulations on your successful purchase !",
"color":"#173177"
},
"keyword1":{
"value":" chocolate ",
"color":"#173177"
},
"keyword2": {
"value":"39.8 element ",
"color":"#173177"
},
"keyword3": {
"value":"2014 year 9 month 22 Japan ",
"color":"#173177"
},
"remark":{
"value":" Welcome to buy again !",
"color":"#173177"
}
}
}
The JSON The parameters in the data package are described in detail as follows :
Parameters | If required | explain |
---|---|---|
touser | yes | The receiver openid |
template_id | yes | Templates ID, A string of characters obtained after adding the template message in the previous configuration |
url | no | Template jump link ( Overseas account no jump ability ) |
miniprogram | no | Data required for skipping applets , No need to skip the applet to transfer the data . When both links and applets exist , Jump applet first . |
appid | yes | Applet to jump to appid( This applet appid It must be bound to the official account of the template message. , Small games are not supported temporarily ) |
pagepath | no | The specific page path to jump to the applet , Support with parameters ,( Example pages/index?foo=bar), Require the applet to be published , Small games are not supported temporarily |
data | yes | Template data . The number of data here , It needs to correspond to the parameters in the message template , As shown in the figure below . |
color | no | Template content font color , Default to black if not filled |
After the request is successful , Back to JSON The packet format is as follows :
{
"errcode":0,
"errmsg":"ok",
"msgid":200228332
}
At this time , Users will receive corresponding reminders through wechat on their mobile phones .
Writing at this point , It mainly describes the general implementation process of authorized login and sending template messages .
Below , It will be combined with the actual project , The implementation process of the above functions , In the form of project source code , For a more detailed demonstration .
5. Web authorization login implementation (PHP For example )
5.1 Tool class GetWX
The main function of this tool class is based on the implementation process of wechat authorized login , Make link request and data acquisition .
<?php
/** * Get wechat user information */
class GetWX
{
// Development information of official account
private $appid = 'APPID';
private $appsecret = 'APPSECERT';
/** * function : User authorization and access code * * @param $callback */
public function get_code($callback)
{
$appid = $this->appid;
$scope = 'snsapi_userinfo';
$state = md5(uniqid(rand(), TRUE));// only ID Identifiers are never repeated
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
header("Location:$url");
}
/** * function : adopt code obtain access_token * * @param $code * @return mixed */
public function get_access_token($code)
{
$appid = $this->appid;
$appsecret = $this->appsecret;
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
$data = json_decode(file_get_contents($url));// Back to json Array to array Array
return $data;
}
/** * function : Use access_token Get user information * * @param $access_token * @param $openid * @return mixed */
public function get_user_info($access_token, $openid)
{
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
$data = json_decode(file_get_contents($url));// Back to json Array to array Array
return $data;
}
}
?>
The specific implementation method of this tool class is not unique . There is a second complete example in the following article .
5.2 obtain code
Login callback page (login.php) The source code is as follows :
<?php
include 'getWX.php';
$getWX = new GetWX();
// without GET To code, Then execute the login operation
if (!isset($_GET['code'])) {
// Wechat server callback url, Here is this page url
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$callback = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// obtain code
$getWX->get_code($callback);
} //GET here we are code, You can do the following
else {
}
As shown in the above source code , Now visit https://XXXX.cn/test/login.php, Execute to if Statement place , Judge whether there is code This parameter , So I got the current link URL Address (callback Parameters ), And give it to get_code Method , This method will construct the login link , And go to this page , Then the login authorization page pops up , As shown below :
The user clicks agree!
after , Back to $callback link . At this time , Carry in the link code Parameters , And developer defined state Parameters . As shown in the figure below :
What we use for the time being is code Parameters .
5.3 Exchange for access_token
Next , Use this code Exchange for access_token
, We will continue to improve login.php Code , As follows :
<?php
include 'getWX.php';
$getWX = new GetWX();
// without GET To code, Then execute the login operation
if (!isset($_GET['code'])) {
// Wechat server callback url, Here is this page url
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$callback = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// obtain code
$getWX->get_code($callback);
} //GET here we are code, You can do the following
else {
// Take it from the link code
$code = $_GET['code'];
// Get web page authorization access_token And the user openid
$data = $getWX->get_access_token($code);
// Test output
echo 'access_token:' . $data->access_token . '<br>';
echo 'expires_in:' . $data->expires_in . '<br>';
echo 'refresh_token:' . $data->refresh_token . '<br>';
echo 'openid:' . $data->openid . '<br>';
echo 'scope:' . $data->scope . '<br>';
}
The output information is as follows :
5.4 Get user information
I got it from above access_token
and OpenID
, Next, you can use these two parameters to obtain the basic information of the user .
We will continue to improve login.php, as follows :
<?php
include 'getWX.php';
$getWX = new GetWX();
// without GET To code, Then execute the login operation
if (!isset($_GET['code'])) {
// Wechat server callback url, Here is this page url
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$callback = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// obtain code
$getWX->get_code($callback);
} //GET here we are code, You can do the following
else {
// Take it from the link code
$code = $_GET['code'];
// Get web page authorization access_token And the user openid
$data = $getWX->get_access_token($code);
// Get wechat user information
$userInfo = $getWX->get_user_info($data->access_token, $data->openid);
// Test output :
echo 'openid:' . $userInfo->openid . '<br>';
echo 'nickname:' . $userInfo->nickname . '<br>';
echo 'sex:' . $userInfo->sex . '<br>';
echo 'province:' . $userInfo->province . '<br>';
echo 'city:' . $userInfo->city . '<br>';
echo 'country:' . $userInfo->country . '<br>';
echo 'headimgurl:' . $userInfo->headimgurl . '<br>';
}
The execution result is shown in the figure below :
At this time , We get the basic information of users , Then you can save these basic information to the database , user ID Etc. can be saved to session perhaps cookie in , wait , Perform various other operations .
5.5 Another complete example
Tool class :
<?php
/** * Get wechat user information * This source code comes from the Internet */
class GetWxUser
{
private $appid = '';
private $appsecret = '';
/** * 1、 Get wechat user information , Judge whether there is code, Have use code Exchange for access_token, Not to get code. * @return array Wechat user information array */
public function get_user_all()
{
if (!isset($_GET['code'])) {
// No, code, Go to wechat interface to get code code
// Wechat server callback url, Here is this page url
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$callback = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// obtain code
$this->get_code($callback);
} else {
// obtain code After jumping back here
$code = $_GET['code'];
$data = $this->get_access_token($code);// Get web page authorization access_token And the user openid
$userInfo = $this->get_user_info($data['access_token'], $data['openid']);// Get wechat user information
return $userInfo;
}
}
/** * 2、 User authorization and access code * @param string $callback Wechat server callback link url */
public function get_code($callback)
{
$appid = $this->appid;
$scope = 'snsapi_userinfo';
$state = md5(uniqid(rand(), TRUE));// only ID Identifiers are never repeated
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) . '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
header("Location:$url");
}
/** * 3、 Use code Exchange for access_token * @param string In exchange for access_token Of code, Wechat provides * @return array access_token And the user openid Array */
public function get_access_token($code)
{
$appid = $this->appid;
$appsecret = $this->appsecret;
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
$user = json_decode(file_get_contents($url));
if (isset($user->errcode)) {
echo 'error:' . $user->errcode . '<hr>msg :' . $user->errmsg;
exit;
}
$data = json_decode(json_encode($user), true);// Back to json Array to array Array
return $data;
}
/** * 4、 Use access_token Get user information * @param string access_token * @param string User openid * @return array User information array */
public function get_user_info($access_token, $openid)
{
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
$user = json_decode(file_get_contents($url));
if (isset($user->errcode)) {
echo 'error:' . $user->errcode . '<hr>msg :' . $user->errmsg;
exit;
}
$data = json_decode(json_encode($user), true);// Back to json Array to array Array
return $data;
}
}
?>
The login page login.php:
<?php
header("Content-Type: text/html;charset=utf-8");
// Set time zone
date_default_timezone_set('Asia/Chongqing');
include 'getWXUser.php';
$getWxUser = new GetWxUser();
// The home page URL
$homeUrl = 'https://mzxy.cxhit.cn';
// No, code, Go to wechat interface to get code code
if (!isset($_GET['code'])) {
// Wechat server callback url, Here is this page url
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$callback = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$getWxUser->get_code($callback);
} // obtain code After jumping back here
else {
$code = $_GET['code'];
// Get web page authorization access_token And the user openid
$data = $getWxUser->get_access_token($code);
// Get wechat user information ( Array )
$userInfo = $getWxUser->get_user_info($data['access_token'], $data['openid']);
// Save to database
if ($userInfo['openid'] != '') {
saveUserInfo($userInfo['openid'], $userInfo['nickname'], $userInfo['sex'], $userInfo['province'], $userInfo['city'], $userInfo['country'], $userInfo['headimgurl']);
}
// Save to cookie in
setcookie('openid', $userInfo['openid'], time() + 3600 * 24 * 30, "/");
// Back to home
header("Location:" . $homeUrl);
}
?>
6. Template message push implementation (PHP For example )
6.1 official JSSDK file (PHP)
The SDK It realizes the acquisition of various parameters , Source code is as follows :
<?php
class JSSDK
{
private $appId;
private $appSecret;
public function __construct($appId, $appSecret)
{
$this->appId = $appId;
$this->appSecret = $appSecret;
}
public function getSignPackage()
{
$jsapiTicket = $this->getJsApiTicket();
// Be careful URL Be sure to get it dynamically , You can't hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr();
// Here, the order of the parameters should be in the following order key value ASCII Code ascending sort
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => $this->appId,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
}
private function createNonceStr($length = 16)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
private function getJsApiTicket()
{
// jsapi_ticket It should be stored and updated globally , The following code is written to a file as an example
$data = json_decode($this->get_php_file("jsapi_ticket.php"));
if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
// If it is an enterprise number, use the following URL obtain ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$this->set_php_file("jsapi_ticket.php", json_encode($data));
}
} else {
$ticket = $data->jsapi_ticket;
}
return $ticket;
}
public function getAccessToken()
{
// access_token It should be stored and updated globally , The following code is written to a file as an example
$data = json_decode($this->get_php_file("access_token.php"));
if ($data->expire_time < time()) {
// If it is an enterprise number, use the following URL obtain access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$this->set_php_file("access_token.php", json_encode($data));
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
private function httpGet($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// To ensure the security of data transmission between the third-party server and wechat server , All wechat interfaces adopt https Way to call , You have to use the following 2 Line code open ssl Security check .
// If code validation fails here during deployment , succeed in inviting sb. http://curl.haxx.se/ca/cacert.pem Download the new certificate file .
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
private function get_php_file($filename)
{
return trim(substr(file_get_contents($filename), 15));
}
private function set_php_file($filename, $content)
{
$fp = fopen($filename, "w");
fwrite($fp, "<?php exit();?>" . $content);
fclose($fp);
}
}
6.2 Template message JSON turn
Take the following template message as an example , demonstrate . Templates The detailed content
The contents of this section need to be kept in mind , Because it's constructing JSON when , Use this information .
Then define a function , The main function is to send data JSON format
Function source code :
// Template message JSON format
function json_tempalte($openid, $appid, $nickname, $time)
{
// Template message
$template = array(
'touser' => $openid, // user openid
'template_id' => 'XXXX', // The template configured under the official account id
'url' => 'https://XXXX.cn', // Click the link that will jump to the template message
'miniprogram' => array(
'appid' => $appid,
'pagepath' => 'pages/main/login/login?foo=bar'
),
'data' => array(
'first' => array('value' => ' Have you finished today's health daily ? Hang in the air , Please hurry up ~', 'color' => "#FF0000"),
'keyword1' => array('value' => $nickname, 'color' => '#173177'), //keyword It needs to correspond to the configured template message
'keyword2' => array('value' => $time, 'color' => '#173177'),
'remark' => array('value' => ' Click here to fill in . This notice is generated by your subscription , Switch identities 、 Change the notification time and unsubscribe management , Please visit the menu bar 『 Learning Assistant 』 modular .', 'color' => '#FF0000'),
)
);
$json_template = json_encode($template);
return $json_template;
}
The result of this function is JSON Data packets .
6.3 Send template message
The key source code is as follows :
include("jssdk.php");
$jssdk = new JSSDK("APPID", "APPSECRET");
// Define message templates JSON
$json_template = json_tempalte('APPID', 'wxa0738e54aae84423', ' Ten year old Lu ' . '( Undergraduate )', date("Y-m-d"));
// obtain AccessToken
$accessToken = $jssdk->getAccessToken();
//POST Link to
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken;
// Submit
list($returnCode, $returnContent) = http_post_json($url, $json_template);
// Print log (JSON Format )
echo ' The sending result is as follows :' . $returnContent . '\n';
among , In the above code http_post_json
Function as follows :
// send out POST request
function http_post_json($url, $jsonStr)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($jsonStr)
)
);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array($httpCode, $response);
}
This function is encapsulated by itself POST request . Of course
After execution , The user can receive the message template .
7. Postscript and source code
Writing at this point , The main use methods of wechat authorized login and wechat template message push are explained .
Although the template message push function of daily reminder has been mentioned in the previous article , But it will not be discussed here .
Source download :https://mianbaoduo.com/o/bread/YZuVk5dp
above .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/128618.html Link to the original text :https://javaforall.cn
边栏推荐
- 【Halcon视觉】形态学膨胀
- Force deduction DFS
- The CLOB field cannot be converted when querying Damon database
- Cause: couldn‘t make a guess for 解决方法
- 新建福厦铁路全线贯通 这将给福建沿海带来什么?
- Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component
- 详细解析js中的混合方式构造对象(构造加属性,原型加方法)
- Transform between tree and array in JS (hide the children field if the child node of the tree is empty)
- 点赞,《新程序员》电子书限时免费领啦!
- Installation and use of cocoapods
猜你喜欢
随机推荐
Redis realizes distributed lock and gets a watchdog
Netease cloud UI imitation -- & gt; sidebar
Use of Android grendao database
点赞,《新程序员》电子书限时免费领啦!
汉诺塔II|汉诺塔4柱
Vs2019 configuring opencv
Study on the basis of opencv
时间序列异常检测
Cause: couldn‘t make a guess for 解决方法
SQL Server 2008 server engine failed to start?
Tower of Hanoi II | tower of Hanoi 4 columns
Use of tabbarcontroller
详细解析js中的混合方式构造对象(构造加属性,原型加方法)
AirTest
【socket】三次握手是在listen中完成,accept只从完成连接的队列中拿出一个连接
Wechat applet learning notes 1
Deduct daily question 838 of a certain day
How to write a million reading article
【C#语言】LINQ概述
Getting started with SQL - combined tables