Detailed tutorial of sending template messages by wechat applet

Time:2022-2-21

Detailed tutorial of sending template messages by wechat applet

Recently, I have been working on a wechat applet, and one of the difficulties I encountered is the sending of template messages of this wechat applet. For me as a beginner, it costs me a lot of work. Well, don’t talk more nonsense, dry goods!!
Here I attach my relevant learning videos (there are many good things on station B):Add link description
A piece of advice: you can watch the video and modify your code in combination with the article here

Let’s take a look at the actual process of this function first: I don’t want to understand it, just know my general process, which is basically done according to this
Detailed tutorial of sending template messages by wechat applet

First step: obtain openid (wechat user identity certificate)

When logging in, or after logging in, set an option (button or view at will) for the user to trigger the event

JS code

wx.login({
                success: res => {
                  //Send res.code to the background for openid, sessionkey and unionid
                  wx.request({
                    URL: 'URL of your own server related files',
                    method: "POST",
                    data: {
                      code: res.code,
                    },
                    header: {
                      "content-type": "application/x-www-form-urlencoded;charset=utf-8"
                    },
                    success: res1 => {
                      var openid = res1.data.openid;}})}})

Let’s take a look at the relevant code of the background file: the appid and secret can be found on the wechat public platform, and the httpget function can be called directly without moving

<?php
	$code = $_POST["code"];
	
	$appid="。。。。。";
	$secret="。。。。。";	
	$api="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

	function httpGet($url){
		$curl=curl_init();
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($curl,CURLOPT_TIMEOUT,500);
		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;	
	}
	
	$str=httpGet($api);
	echo $str;
?>

In this way, you can get the user’s or your own openid on the front desk. At this time, you can store it in the database or use it directly (this is equivalent to sending yourself a wechat message)

Step 2: select the message template you want

On the wechat public platform, there is a template message board, where you can add the message template you need. Of course, in it, you can also apply for your own fields (but maybe the fields are full and won’t let you apply)
Detailed tutorial of sending template messages by wechat applet

Step 3: that is to officially send wechat template messages

First get the FormID and the information you want to use, then query the database to find the openid of who you want to send wechat messages to, and then request your own server again to transmit the corresponding data (FormID openid and the information you need on the wechat template) and let the server request the wechat server to send this template message

Set buttons to trigger form events. If multi button submission is involved, you can see my article, which may be helpful to youAdd link description

Wxml Code:

<form bindsubmit="clickFormView" report-submit="true" class="form-view">
<view></view>
.....

< button class = "end_submit" form type = "submit" > submit < / button >
</form>

JS code:

var formid = e.detail. formId;// This must be required by WeChat official account.
   var values = e.detail.value;
   var name = values.input.split("+")[0];
   var style = values.input.split("+")[1];
   var kecheng = values. input. split("+")[2];// These are your messages, which you need to obtain by yourself. In the wechat developer tool, you can use console Log to print out all the information. Just choose the information you need most
   var openids = "";
   //Query the database to get the openid you need
   wx.request({
     url: '.....',
     method: "POST",
     Data: {// the database here depends on your background code
       sql: "select openid from wx_openid where tea_id='20190804100' or tea_id='" + app.globalData.userInfo['username'] + "'",
       type: 'select',
       fetch_ Type: 'Assoc' // Assoc field index, Num numeric index
     },
     header: {
       "content-type": "application/x-www-form-urlencoded;charset=utf-8"
     },
     success: res => {
       openids = res.data;
       for (var a in openids) {
         if (openids[a]['openid'] == "") continue;
         wx.request({
           URL: 'background template URL',
           method: "POST",
           data: {
             name: name,
             time: time,
             style: style,
             kecheng: kecheng,
             formid: formid,
             openid: openids[a]['openid'],
           },
           header: {
             "content-type": "application/x-www-form-urlencoded;charset=utf-8"
           },
           success: res1 => {
             console.log("ok");
           } }) }} })

Finally, let’s look at the background code (just one of them): here, give the corresponding template ID of wechat public platform to the variable templateid copied into this code
And remember the end hereENDDon’t add a space in front of it, otherwise it will report an error

<?php

	function httpGet($url){
		$curl=curl_init();
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($curl,CURLOPT_TIMEOUT,500);
		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;	
	}
	function httpPost($data,$url){
		$curl=curl_init();
		curl_setopt($curl,CURLOPT_URL,$url);
		curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
		curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
		curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64)');
		curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($curl,CURLOPT_AUTOREFERER,1);
		curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
		
		$tmpInfo=curl_exec($curl);
		if(curl_errno($curl)){
			return curl_error($curl);
		}
		curl_close($curl);
		return $tmpInfo;	
	}
	
	$openid=$_POST["openid"];
	$formid=$_POST["formid"];
	$name=$_POST["name"];
	$time=$_POST["time"];
	$style=$_POST["style"];
	$kecheng=$_POST["kecheng"];
	$templateid='。。。。。';
	
	$data = <<<END
	{
	  "touser": "{$openid}",
	  "template_id": "{$templateid}",
	  "page": "/pages/login1/login1",
	  "form_id": "{$formid}",
	  "data": {
		  "keyword1": {
			  "value": "{$name}"
		  },
		  "keyword2": {
			  "value": "{$time}"
		  },
		  "keyword3": {
			  "value": "{$style}"
		  } ,
		  "keyword4": {
			  "value": "{$kecheng}"
		  }
	  },
	  "emphasis_keyword": "keyword3.DATA"
	}
END;
	
	$appid="。。。。";
	$secret="。。。。";
	$gettokenapi="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
	$resultstr=httpGet($gettokenapi);
	$arr=json_decode($resultstr,true);
	$token=$arr['access_token'];
	
	//Send template
	$templateapi="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$token}";
	$res=httpPost($data,$templateapi);

?>

Finally, this code will not be completely suitable for you. You need to make some necessary modifications. I wish you success in sending wechat template messages