Home  >  Article  >  WeChat Applet  >  How to implement a mini program to send service notifications

How to implement a mini program to send service notifications

WJ
WJOriginal
2020-06-10 11:27:546437browse

How to implement a mini program to send service notifications

How to implement the mini program to send service notifications?

Sending messages to users through small programs requires a lot of verification. If you just encounter this requirement, you may spend a long time researching and testing it, so I have compiled a complete set of logic for sending messages from the basics for future development. The message notification function provides ideas and reduces learning time

Sending a template message mainly has the following parts

1. Obtain access_token

2. Create a message template

3. Get form_id

4. Send message notification

5. Set scheduled tasks

1. Get access_token

When requesting to send a message to WeChat, you will need access_token, which is equivalent to the ID card of the mini program. Although there are two certificates, appid and appsecret, in order to ensure security, WeChat uses access_token, a time-limited identity certificate, for verification. , an access_token is only valid for 2 hours, and a single applet can only request access_token 1000 times a day, so we need a set of logic to ensure the availability of access_token

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

You only need to request the above address to return the corresponding access_token

According to this interface, write the following method

public function test(){
$appId = '';
$appSecret = '';
$token = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret);
$token = json_decode($token);
$token = $token->access_token;
db('token')->where('id',1)->update(['access_token'=>$token]);//覆盖上一条access_token
}

Then set a timer to trigger the interface every hour, and then you can take out the token that is sure to be used at will

$token = db('token')->find();
$token = $token['access_token'];

2. Create a message template

There is a template message tab in the left column of the mini program WeChat public platform. You only need to add a template message according to the document to get the corresponding Corresponding template ID, this step is basically operated by the web page without further display

3. Obtain form_id

In order to prevent the mini program from doing too much to the user, WeChat Message notifications have a restriction on message notifications. Every time a message notification is sent, a form_id or prepay_id is required

prepay_id is the ID returned by the user after using WeChat payment, and will not be explained in detail in this article

form_id is the Id bound to the button. Whenever the user clicks the bound button, a form_id will be returned. The validity period of a form_id is 7 days, and each user's form_id can only be used for that user, so we need A special logic to save and use form_id

①设计form_id表结构
form_id有2个条件,第一个是仅7天内有效,第二个是仅对创建form_id的用户有效,针对这2个要求建立如下表
创建时间用户id
idcreateTimeopenIdform_id
id作为主键自增不用解释
createTime作为找到过期form_id的标志,设置定时任务,删除过期form_id
openId用来找到用户自己的form_id来使用
②取到form_id
<!--pages/index/index.wxml-->
<form  report-submit=&#39;ture&#39; bindsubmit=&#39;form_id&#39;>
    <button form-type="submit">确定</button>
</form>
// pages/index/index.js
form_id: function(e) {
    wx.request({
        url: &#39;test.com/index/index/form_id&#39;,//自行替换接口
        method: "POST",
        data: {
            form_id: e.detail.formId,
            openId: openId//自行获取当前用户openId
        },
        header: {
            &#39;content-type&#39;: &#39;application/x-www-form-urlencoded&#39;
        }
    })
},
//test.com/index/index/form_id
public function form_id(){
    if (empty($_POST)) {die;}
    $form_id = $_POST[&#39;form_id&#39;];
    if ($form_id == &#39;the formId is a mock one&#39;){die;}//过滤开发工具生成的form_id
    $openId = $_POST[&#39;openId&#39;];
    if (!$openId) {die;}
    $data = compact(&#39;form_id&#39;,&#39;openId&#39;);
    db(&#39;form_id&#39;)->insert($data);
}
③使用form_id
public function test(){
    $openId = &#39;&#39;;
    $form_id = db(&#39;form_id&#39;)->where(&#39;openId&#39;,$openId)->order(&#39;id&#39;)->field(&#39;form_id&#39;)->find();
    $form_id = $form_id[&#39;form_id&#39;];
}
④定时删除过期form_id
public function test(){
    $time = time()-518400;//保证form_id可用性删除6天前的form_id
    db(&#39;form_id&#39;)->where(&#39;createTime&#39;,&#39;<&#39;,$time)->delete();
    //将该方法每天执行一次
}

4. Send message notification

When access_token and form_id are guaranteed to be available, you can send message notification to the user

public function message($data){
    //获取form_id
    $form_id = db(&#39;form_id&#39;)->where(&#39;openId&#39;,$openId)->order(&#39;id&#39;)->find();
    if (!$form_id) {die;}
    $form_id = $form_id[&#39;form_id&#39;];
    db(&#39;form_id&#39;)->where(&#39;form_id&#39;,$form_id)->delete();
    //获取access_token
    $access_token = db(&#39;token&#39;)->where(&#39;id&#39;,1)->find();
    $access_token = $access_token[&#39;access_token&#39;];
    //获取消息内容
    $openId = $data[&#39;openId&#39;];
    $title = $data[&#39;title&#39;];
    $data1 = $data[&#39;data1&#39;];
    $data2 = $data[&#39;data2&#39;];
    $request_url=&#39;https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=&#39;.$access_token;
    $request_data=[
        &#39;touser&#39; => $openId,
        &#39;template_id&#39; => &#39;&#39;,//表id
        &#39;page&#39;  =>  &#39;pages/test/test?data1=&#39;.$data1.&#39;&data2=&#39;.$data2,//本消息点击后跳转到的页面
        "form_id"   =>  $form_id,
        &#39;data&#39;  =>  [
            &#39;keyword1&#39;  =>  [
                &#39;value&#39; =>  $title
            ],
            &#39;keyword2&#39;  =>  [
                &#39;value&#39; =>  $data1
            ],
            &#39;keyword3&#39;  =>  [
                &#39;value&#39; =>  $data2
            ]
        ],
        &#39;emphasis_keyword&#39;  =>  "keyword1.DATA"//消息中要放大的内容
    ];
    $return=json_decode($this->request($request_url,$request_data),true);//发送消息,并读取返回值
    return $return;
}
//上面的$this->request方法
public function request($url, $data=null)
{
    $headers=array(&#39;Content-type:application/json;charset=UTF-8&#39;,&#39;Accept:application/json&#39;,&#39;Cache-Control:no-cache&#39;,&#39;Pragma:no-cache&#39;);
    $curl=curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        $data=json_encode($data);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $output=curl_exec($curl);
    curl_close($curl);
    return $output;
}

5. Set up scheduled tasks

In order to ensure that the above operations can proceed smoothly, we need to set up several scheduled tasks to help send messages. Let’s first assume that there are several methods

getToken //Update token every hour

delForm_id //Delete form_id 6 days ago once a day

message //Send message once every minute

First Connect to the server and open the scheduled task settings

crontab -e

Each line in the settings is a scheduled task, divided into 3 parts

1.* * * * *
这5个参数分别表示定时任务的执行时间,每个参数与上个参数隔一个空格,分别为(分)(时)(天)(月)(星期),下面举例子
* * * * *//每分钟执行一次
0 * * * *//每小时的第0分钟执行一次
*/5 * * * *//每5分钟执行一次
* 23 * * *//每天的23点执行一次
* * 1 * *//每月1号执行一次
* * * */2 *//每2个月执行一次
0 0 * * 6//每周6的0点0分执行一次

2./usr/bin/php

This is the path to the php executable file. If you cd to this path and give the path to the php executable file, the php file will be executed. It can be used to test whether the php file can set up scheduled tasks.

Note, This path is just a shortcut, the real php execution file is in /usr/local/php/bin/php or /usr/local/php(version number)/ bin/php, if there is no shortcut created under bin, please create it yourself

3./Project path/execution file

This is the path to the php file that needs to be executed, if written It is native PHP, just point to the file directly. If it is written using the thinkphp framework, you need to point to index.php in the root directory or public directory, followed by /module/controller/method

Knowing these three points, we can write the above three scheduled tasks

* */1 * * */usr/bin/php /项目路径/index.php /index/index/getToken
* 4 * * */usr/bin/php /项目路径/index.php /index/index/delForm_id
* * * * */usr/bin/php /项目路径/index.php /index/index/message

Finally, restart the scheduled task

//CentOS5/CentOS6
/sbin/service crond restart
//CentOS7
/bin/systemctl restart crond.service

Related recommendations:小program tutorial

The above is the detailed content of How to implement a mini program to send service notifications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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