微信公众号模版消息 uniapp
时间: 2025-02-01 09:17:02 浏览: 83
### 实现 UniApp 中微信公众号模板消息功能
在 UniApp 开发环境中实现微信公众号模板消息功能涉及多个方面,包括前端页面设计、后端服务器配置以及微信公众平台设置。
#### 前端部分:UniApp 页面代码
为了触发模板消息订阅请求,在 UniApp 的页面中可以使用 `wx.requestSubscribeMessage` API 来唤起用户的订阅确认对话框。下面是一个简单的例子:
```javascript
// pages/index/index.vue
<template>
<view class="container">
<button @click="subscribeTemplateMsg">点击订阅</button>
</view>
</template>
<script>
export default {
methods: {
subscribeTemplateMsg() {
wx.requestSubscribeMessage({
tmplIds: ['your_template_id'], // 替换成实际的模板 ID
success(res) {
console.log('用户同意订阅', res);
// 可在此处发起网络请求告知服务器用户已订阅
},
fail(err) {
console.error('用户拒绝订阅或发生错误', err);
}
});
}
}
}
</script>
```
此段代码展示了如何创建一个按钮来让用户主动选择是否要接收来自特定模板的消息[^1]。
#### 后端部分:发送模板消息给用户
当用户完成订阅动作之后,开发者可以通过自己的服务器向微信公众平台上报备并最终把定制化的内容推送给目标受众。以下是 Python Flask 框架下的简单示例用于展示这一过程:
```python
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route('/send-template-message', methods=['POST'])
def send_template_message():
data = request.json
access_token = get_access_token()
url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"
payload = {
"touser": data['openid'],
"template_id": data['templateId'],
"url": "", # 如果不需要跳转则留空
"miniprogram": {}, # 不需要跳小程序也保持为空对象
"data": {
"first": {"value":"您好"},
"keyword1":{"value":"订单号"},
"keyword2":{"value":"状态更新"},
"remark":{"value":"感谢您的支持"}
}
}
response = requests.post(url=url,json=payload).json()
return jsonify(response)
def get_access_token():
appid = 'YOUR_APP_ID'
secret = 'YOUR_APP_SECRET'
token_url = (f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='
f'{appid}&secret={secret}')
resp_json = requests.get(token_url).json()
return resp_json["access_token"]
```
上述脚本定义了一个 POST 接口 `/send-template-message`, 它接受 JSON 形式的输入参数(如 openid 和 templateId),并通过 WeChat API 发送一条结构化的模板消息给指定用户[^4].
阅读全文
相关推荐
















