QQ小程序发送模板消息

QQ小程序群里有伙伴要发送模板消息的代码,所以今天给大家分享QQ小程序模板消息发布,绝对一步一步带着大家走,每个细节都讲到。
今天先用php简单写一下,有空了再写java的。

首先创建一个空项目:
因为QQ小程序没有编译器,先用微信小程序创建。

新建一个项目,其实微信小程序和QQ小程序本质上没有区别
然后新建一个页面,直接上html代码:

<form bindsubmit="form_submit" report-submit="true">
<button  formType="submit">这是模板发送按钮</button>
</form>

然后写js逻辑:
记着勾选不校验合法域名
然后上js代码

form_submit(e) {
    console.log(e.detail.formId)
    var that = this
    wx.showToast({
      title: '正在发送模板消息请求',
      duration: 5000,
      icon: 'loading',
      mask: true
    })
    //推送消息
    wx.login({
      success: function (res) {
        console.log("获得的code");
        console.log(res)
        var code = res.code;//发送给服务器的code
        console.log("获得用户信息成功");
            if (code) {
              wx.request({
                url: 'https://xxxx/tokentest.php',//服务器的地址,现在微信小程序只支持https请求,所以调试的时候请勾选不校监安全域名
                data: {
                  code: code,
                  formID: e.detail.formId,
                },
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                  console.log(res.data);
                  wx.setStorageSync('useropenid', res.data)
                  wx.showToast({
                    title: '发送模板消息成功!',
                  })
                }
              })
            }
            else {
              console.log("获取用户登录态失败!");
            }
      },
      fail: function (error) {
        console.log('login failed ' + error);
      }
    })
  },

这里简单说一下原理:
微信小程序、QQ小程序想要发送模板消息给用户,必须要用户在小程序前端有提交表单的动作出现,所以我们在html中写了个form标签来完成这一要求,然后在js端接受该表单返回的formid,这个表单id是有七天时效的,也就是说在7天之内可以向用户发送模板消息。综上,发送模板消息需要两个东西:一是用户的openid(发给谁),二是用户的formid(有表单提交动作)。
我们在js中拿到了用户的formid但是没有拿到openid,所以需要请求后台去拿用户的openid。
拿openid需要用用户提交上去的code,和小程序的appid及appsercet三把钥匙去请求微信服务器,返回用户的openid.

申请一个模板templateid:
这里我们随便选一个
我这里选了三个关键词
然后拿到templaid

然后是后台程序php:
tokentest.php

<?php
//require_once('getAccessToken.php');
$appid="166666666";//你的小程序id
$appsecret="xxxxxxx";//你的小程序密钥
function curl_get_https($url)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
		$tmpInfo = curl_exec($curl); 
		curl_close($curl);
		return $tmpInfo;   //返回json对象
	}
function getAccessToken ($appid, $appsecret) {                  
  $url='https://api.q.qq.com/api/getToken?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
  //$url='https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code';
  /*
  $arrContextOptions=array(
      "ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        ),
    );  
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
*/
    $info = curl_get_https($url);
    $json = json_decode($info);//对json数据解码
    $arr = get_object_vars($json);
  $access_token = $arr['access_token'];
  return $access_token;
}



  //获得openid
  $code = $_GET['code'];//小程序传来的code值
    //$nick = $_GET['nick'];//小程序传来的用户昵称
    //$imgUrl = $_GET['avaurl'];//小程序传来的用户头像地址
    //$sex = $_GET['sex'];//小程序传来的用户性别
   // $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code=' . $code . '&grant_type=authorization_code';
   $url='https://api.q.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code=' . $code . '&grant_type=authorization_code';
    //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取;
    //$info = file_get_contents($url);//发送HTTPs请求并获取返回的数据,推荐使用curl
	$info = curl_get_https($url);
    $json = json_decode($info);//对json数据解码
    $arr = get_object_vars($json);
    $openid = $arr['openid'];
	echo "openid:";
	echo $openid;
    $session_key = $arr['session_key'];
	$formid = $_GET['formID'];//小程序传来的用户
echo "formid:";
echo $formid;
// 根据你的模板对应的关键字建立数组
// color 属性是可选项目,用来改变对应字段的颜色
date_default_timezone_set("Asia/Shanghai");
$nowtime=date("Y.m.d");
$color="black";

$data_arr = array(
  'keyword1' => array( "value" => "哈哈哈", "color" => $color ) ,
  'keyword2' => array( "value" => $nowtime, "color" => $color ) ,
  'keyword3' => array( "value" => "这是测试", "color" => $color ) ,
);
$templateid="xxxx";//这里填自己的模板id

$post_data = array (
  // 用户的 openID,可用过 wx.getUserInfo 获取
  "touser"           => $openid,
  // 小程序后台申请到的模板编号
  "template_id"      => $templateid,
  // 点击模板消息后跳转到的页面,可以传递参数
  "page"             => "/pages/person/person",
  // 第一步里获取到的 formID
  "form_id"          => $formid,
  // 数据
  "data"             => $data_arr,
  // 需要强调的关键字,会加大居中显示
 // "emphasis_keyword" => "keyword2.DATA"

);
        
// 发送 POST 请求的函数
// 你也可以用 cUrl 或者其他网络库,简单的请求这个函数就够用了         
function send_post( $url, $post_data ) {
  $options = array(
    'http' => array(
      'method'  => 'POST',
      // header 需要设置为 JSON
      'header'  => 'Content-type:application/json',
      'content' => $post_data,
      // 超时时间
      'timeout' => 60
    ),
	"ssl"=>array(
            "verify_peer"=>false,
            "verify_peer_name"=>false,
        )
  );

  $context = stream_context_create( $options );
  $result = file_get_contents( $url, false, $context );

  return $result;
}

// 这里替换为你的 appID 和 appSecret
$url = "https://api.q.qq.com/api/json/template/send?access_token=".getAccessToken ($appid, $appsecret);  
// 将数组编码为 JSON
$data = json_encode($post_data, true);   

// 这里的返回值是一个 JSON,可通过 json_decode() 解码成数组
$return = send_post( $url, $data);
var_dump($return);

?>


appid和appsercet在小程序后台弄:
这里是小程序ID和秘钥
最后看一下效果吧:
就完成了

有任何报错或者问题请留言,原创不易,谢谢大家

### 微信小程序调用API发送服务号模板消息 为了实现从小程序向用户的服务号发送模板消息的功能,需遵循特定的开发流程。此功能依赖于微信公众平台所提供的接口支持。 #### 准备工作 确保已拥有经过认证的服务号,并获取到相应的`AppID` 和 `AppSecret` 。这些信息用于后续请求访问令牌所需的身份验证[^1]。 #### 获取access_token 每次发送模板消息前都需要先取得有效的`access_token` ,这是调用微信开放平台上各类接口的基础凭证之一。可以通过HTTP GET方式请求如下URL来获得: ```http https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET ``` 其中`APPID`和`APPSECRET`应替换为实际应用对应的值。成功响应会返回JSON格式的数据包,内含所需的`access_token`字段。 #### 构建并发送模板消息 构建要发送消息体结构,具体参数说明可参见官方文档。下面给出Python语言下的简单示例代码片段展示如何构造POST请求以触发消息推送行为: ```python import requests import json url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=TOKEN" data = { "touser": "OPENID", "template_id": "TEMPLATE_ID", "page": "index", "form_id": "FORMID", "data": { "keyword1": {"value": "商品名称"}, "keyword2": {"value": "订单金额"} } } response = requests.post(url, data=json.dumps(data)) print(response.json()) ``` 注意以上代码中的变量均需替换成真实环境里的对应值,比如用户的OpenID、表单id以及具体的关键词内容等。此外,在正式环境中建议加入错误处理逻辑以便更好地应对异常情况。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

爱学习的森

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值