微信小程序发送模板消息,php发送模板消息

微信小程序开发交流qq群   173683895

   承接微信小程序开发。扫码加微信。

 

formId 在安卓系统是纯数字,在IOS系统是一串加密字符,如图:

发送模板消息(服务通知)效果图:

前端

wxml


<form bindsubmit="submitForm" report-submit >
  <button form-type="submit">发送</button>
</form>

js

  submitForm(e){
    console.log(e.detail.formId);
    var formId = e.detail.formId == 'the formId is a mock one' ? 1546946903765 : e.detail.formId;
    util.request('http://localhost/sendTemplateMessage.php', 'get', { formId}, '', function (res) {
      console.log('sendTemplateMessage:',res)
    })
  },

后端php

<?php
 	header("Content-Type:text/html;charset=utf8"); 
    header("Access-Control-Allow-Origin: *"); //解决跨域
    header('Access-Control-Allow-Methods:GET');// 响应类型  
    header('Access-Control-Allow-Headers:*'); // 响应头设置 
    $link=mysql_connect("localhost","root","root"); 
    mysql_select_db("6677onechat", $link); //选择数据库
    mysql_query("SET NAMES utf8");//解决中文乱码问题
    
    //$openid = $_GET['openid'];
    $form_id =getFormId();
	getModel($form_id);
	
	/* https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + that.data.access_token; 
     * 微信规定:不能直接在小程序调用,只能在后台发起
     *  -xzz0704 
     */
    function getModel($form_id){
                $access_token = getWxAccessToken();
				$navopenid = $_GET['navopenid'];
				$template_id='dd0ws5CfJdjAyNUNDIf9jRa-xZprclpmiJdeqlWDAOU';
                $value = array(
                    "keyword1"=>array(
                    "value"=>$_GET['name'],
                     //"value"=>'woshihaoren',
                    "color"=>"#4a4a4a"
                    ),
                    "keyword2"=>array(
                        "value"=>$_GET['txt'],
                        "color"=>"#9b9b9b"
                    )
                );
                
                $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
                $dd = array();
                $dd['touser']=$navopenid;
                $dd['template_id']=$template_id;
                $dd['page']='pages/index/index';  //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
                $dd['form_id']=$form_id;
                
                $dd['data']=$value;                        //模板内容,不填则下发空模板
                
                $dd['color']='';                        //模板内容字体的颜色,不填默认黑色
                //$dd['color']='#ccc';
                $dd['emphasis_keyword']='';    //模板需要放大的关键词,不填则默认无放大
                //$dd['emphasis_keyword']='keyword1.DATA';
                
                //$send = json_encode($dd);   //二维数组转换成json对象
                
                /* curl_post()进行POST方式调用api: api.weixin.qq.com*/
                $result = https_curl_json($url,$dd,'json');
                if($result){
                    echo json_encode(array('state'=>5,'msg'=>$result));
                }else{
                    echo json_encode(array('state'=>5,'msg'=>$result));
                }
    }
    
    //获取access_token
	function getWxAccessToken(){
	    $appid='wxd51fee07a27977f2';//填你的appid
	    $appsecret='f9207c1e65ca6c7f0450822bb0a46f19';//填你的appsecret
	        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	        $access_token = makeRequest($url);
	        $access_token = json_decode($access_token['result'],true);
	        return $access_token['access_token'];
	}
    //获取formid
    function getFormId(){
    	$navopenid = $_GET['navopenid'];
		$result = mysql_query("SELECT * FROM chatuser");
		$form_id;
		while($row = mysql_fetch_array($result))
		  {
		  	if($row['openid']== $navopenid){
		  		$form_id =$row['fromId'];
		  	}
		  }
		return $form_id;
		
    }
    
    /* 发送json格式的数据,到api接口 -xzz0704  */
    function https_curl_json($url,$data,$type){
        if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
            $data=json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($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);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;
    }
    
	/**
	 * 发起http请求
	 * @param string $url 访问路径
	 * @param array $params 参数,该数组多于1个,表示为POST
	 * @param int $expire 请求超时时间
	 * @param array $extend 请求伪造包头参数
	 * @param string $hostIp HOST的地址
	 * @return array    返回的为一个请求状态,一个内容
	 */
	function makeRequest($url, $params = array(), $expire = 0, $extend = array(), $hostIp = '')
	{
	    if (empty($url)) {
	        return array('code' => '100');
	    }
	 
	    $_curl = curl_init();
	    $_header = array(
	        'Accept-Language: zh-CN',
	        'Connection: Keep-Alive',
	        'Cache-Control: no-cache'
	    );
	    // 方便直接访问要设置host的地址
	    if (!empty($hostIp)) {
	        $urlInfo = parse_url($url);
	        if (empty($urlInfo['host'])) {
	            $urlInfo['host'] = substr(DOMAIN, 7, -1);
	            $url = "http://{$hostIp}{$url}";
	        } else {
	            $url = str_replace($urlInfo['host'], $hostIp, $url);
	        }
	        $_header[] = "Host: {$urlInfo['host']}";
	    }
	 
	    // 只要第二个参数传了值之后,就是POST的
	    if (!empty($params)) {
	        curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
	        curl_setopt($_curl, CURLOPT_POST, true);
	    }
	 
	    if (substr($url, 0, 8) == 'https://') {
	        curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	        curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	    }
	    curl_setopt($_curl, CURLOPT_URL, $url);
	    curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
	    curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);
	 
	    if ($expire > 0) {
	        curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
	        curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
	    }
	 
	    // 额外的配置
	    if (!empty($extend)) {
	        curl_setopt_array($_curl, $extend);
	    }
	 
	    $result['result'] = curl_exec($_curl);
	    $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
	    $result['info'] = curl_getinfo($_curl);
	    if ($result['result'] === false) {
	        $result['result'] = curl_error($_curl);
	        $result['code'] = -curl_errno($_curl);
	    }
	 
	    curl_close($_curl);
	    return $result;
	}
?>

番外笔记,可以忽略

php,  查找表里面该openid 的formid,前端传发送信息的昵称和信息,然后通过模板消息发送给对方。

<?php
 	header("Content-Type:text/html;charset=utf8"); 
    header("Access-Control-Allow-Origin: *"); //解决跨域
    header('Access-Control-Allow-Methods:GET');// 响应类型  
    header('Access-Control-Allow-Headers:*'); // 响应头设置 
    $link=mysql_connect("localhost","root","root"); 
    mysql_select_db("6677onechat", $link); //选择数据库
    mysql_query("SET NAMES utf8");//解决中文乱码问题
    
    //$openid = $_GET['openid'];
    $form_id =getFormId();
	getModel($form_id);
	
	/* https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + that.data.access_token; 
     * 微信规定:不能直接在小程序调用,只能在后台发起
     *  -xzz0704 
     */
    function getModel($form_id=''){
              
                $access_token = getWxAccessToken();
				$openid = 'oZ5S45bCh2a';
				$template_id='dd0ws5CfJdjAyNUNewetwewer3asd-AOU';
				//$form_id=$_GET['formId'];
                $value = array(
                    "keyword1"=>array(
                    "value"=>$_GET['name'],
                     //"value"=>'woshihaoren',
                    "color"=>"#4a4a4a"
                    ),
                    "keyword2"=>array(
                        "value"=>$_GET['txt'],
                        "color"=>"#9b9b9b"
                    )
                );
                
                $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
                $dd = array();
                $dd['touser']=$openid;
                $dd['template_id']=$template_id;
                //$dd['page']=$page;  //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
                $dd['form_id']=$form_id;
                
                $dd['data']=$value;                        //模板内容,不填则下发空模板
                
                $dd['color']='';                        //模板内容字体的颜色,不填默认黑色
                //$dd['color']='#ccc';
                $dd['emphasis_keyword']='';    //模板需要放大的关键词,不填则默认无放大
                //$dd['emphasis_keyword']='keyword1.DATA';
                
                //$send = json_encode($dd);   //二维数组转换成json对象
                
                /* curl_post()进行POST方式调用api: api.weixin.qq.com*/
                $result = https_curl_json($url,$dd,'json');
                if($result){
                    echo json_encode(array('state'=>5,'msg'=>$result));
                }else{
                    echo json_encode(array('state'=>5,'msg'=>$result));
                }
    }
    
    //获取access_token
	function getWxAccessToken(){
	    $appid='wxd51fee07a27977f2';//填你的appid
	    $appsecret='f9207c1e65ca6c7f0450822bb0a46f19';//填你的appsecret
	        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	        $access_token = makeRequest($url);
	        $access_token = json_decode($access_token['result'],true);
	        return $access_token['access_token'];
	}
    //获取formid
    function getFormId(){
    	$navopenid = $_GET['navopenid'];
		$result = mysql_query("SELECT * FROM chatuser");
		$form_id;
		while($row = mysql_fetch_array($result))
		  {
		  	if($row['openid']== $navopenid){
		  		$form_id =$row['fromId'];
		  	}
		  }
		return $form_id;
		
    }
    
    /* 发送json格式的数据,到api接口 -xzz0704  */
    function https_curl_json($url,$data,$type){
        if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
            $data=json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($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);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;
    }
    
	/**
	 * 发起http请求
	 * @param string $url 访问路径
	 * @param array $params 参数,该数组多于1个,表示为POST
	 * @param int $expire 请求超时时间
	 * @param array $extend 请求伪造包头参数
	 * @param string $hostIp HOST的地址
	 * @return array    返回的为一个请求状态,一个内容
	 */
	function makeRequest($url, $params = array(), $expire = 0, $extend = array(), $hostIp = '')
	{
	    if (empty($url)) {
	        return array('code' => '100');
	    }
	 
	    $_curl = curl_init();
	    $_header = array(
	        'Accept-Language: zh-CN',
	        'Connection: Keep-Alive',
	        'Cache-Control: no-cache'
	    );
	    // 方便直接访问要设置host的地址
	    if (!empty($hostIp)) {
	        $urlInfo = parse_url($url);
	        if (empty($urlInfo['host'])) {
	            $urlInfo['host'] = substr(DOMAIN, 7, -1);
	            $url = "http://{$hostIp}{$url}";
	        } else {
	            $url = str_replace($urlInfo['host'], $hostIp, $url);
	        }
	        $_header[] = "Host: {$urlInfo['host']}";
	    }
	 
	    // 只要第二个参数传了值之后,就是POST的
	    if (!empty($params)) {
	        curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
	        curl_setopt($_curl, CURLOPT_POST, true);
	    }
	 
	    if (substr($url, 0, 8) == 'https://') {
	        curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	        curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	    }
	    curl_setopt($_curl, CURLOPT_URL, $url);
	    curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
	    curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);
	 
	    if ($expire > 0) {
	        curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
	        curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
	    }
	 
	    // 额外的配置
	    if (!empty($extend)) {
	        curl_setopt_array($_curl, $extend);
	    }
	 
	    $result['result'] = curl_exec($_curl);
	    $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
	    $result['info'] = curl_getinfo($_curl);
	    if ($result['result'] === false) {
	        $result['result'] = curl_error($_curl);
	        $result['code'] = -curl_errno($_curl);
	    }
	 
	    curl_close($_curl);
	    return $result;
	}
?>

发送信息时调用发送模板消息

navopenid  对方的openid  

  // 发送模板消息
  sendmsg() {
    var name = wx.getStorageSync('userInfo').nickName;
    var txt = this.data.inputValue ? this.data.inputValue:'你好';
    util.request(app.onechatRul + '/sendTemplateMessage.php', 'GET', {
      navopenid,
      openid: wx.getStorageSync('openid'),
      name,
      txt
    }, '', function(res) {
      console.log('sendTemplateMessage:', res)
    })
  },

 

 

要实现服务号给微信小程序用户发送模板消息需要使用微信公众平台提供的模板消息接口。以下是使用PHP实现的步骤: 1. 获取access_token 首先需要获取access_token,可以通过向以下接口发送GET请求获取: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 其中APPID和APPSECRET分别为服务号的AppID和AppSecret。 2. 获取小程序用户的openid 在向小程序用户发送模板消息之前,需要获取用户的openid。可以通过使用小程序提供的登录接口获取用户的openid,具体方法可以参考小程序开发文档。 3. 发送模板消息 获取用户的openid之后,就可以向用户发送模板消息了。发送模板消息的接口为: https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN 其中ACCESS_TOKEN为第一步获取的access_token。 发送模板消息的数据格式为: { "touser":"OPENID", "template_id":"TEMPLATE_ID", "page":"index", "form_id":"FORMID", "data":{ "keyword1":{ "value":"VALUE1" }, "keyword2":{ "value":"VALUE2" } }, "emphasis_keyword":"keyword1.DATA" } 其中: - touser为接收消息小程序用户的openid; - template_id为模板消息的ID,可以在公众平台后台的模板库中查找; - page为小程序的页面路径,可以不填; - form_id为小程序的form_id,可以在小程序端通过wx.requestPayment等接口获取; - data为模板消息需要替换的变量; - emphasis_keyword为模板消息需要进行高亮的关键字。 具体的数据格式可以参考微信公众平台的文档。 以上是使用PHP实现服务号给微信小程序用户发送模板消息的基本步骤。需要注意的是,为了保证模板消息能够正常发送需要先在公众平台后台的模板库中添加对应的模板,并且设置好模板消息需要替换的变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a_靖

对你有帮助吗?打赏鼓励一下?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值