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

今天先用php简单写一下,有空了再写java的。

首先创建一个空项目:

因为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:




然后是后台程序php:

tokentest.php

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);
   }
  })
 },

appid和appsercet在小程序后台弄:



最后看一下效果吧:


总结

以上所述是小编给大家介绍的php实现QQ小程序发送模板消息功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对悠悠之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

点赞(148)

评论列表共有 0 条评论

立即
投稿
返回
顶部