QQ小程序发送模板消息

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

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

QQ小程序发送模板消息_第1张图片
然后新建一个页面,直接上html代码:

然后写js逻辑:
QQ小程序发送模板消息_第2张图片
然后上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:
QQ小程序发送模板消息_第3张图片
QQ小程序发送模板消息_第4张图片
QQ小程序发送模板消息_第5张图片

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

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在小程序后台弄:
QQ小程序发送模板消息_第6张图片
最后看一下效果吧:
QQ小程序发送模板消息_第7张图片

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

你可能感兴趣的:(小程序)