Django后端发送小程序微信模板消息示例(服务通知)

yipeiwu_com5年前Python基础

模板消息

官方文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/template-message/templateMessage.send.html

模板消息如下图所示

Django中获取access_token

根据文档描述,获取access_token文档,后端必须获取一个access_token才能够发送模板消息,文档中说明该token有效期为两小时,需要后端定时去获取。我们这里使用Django-crontab第三方包来实现定时任务。

pip install django-crontab

根据文档描述,需要向https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET这个地址发送get请求,返回结果为access_token

我把access_token存入到缓存中

Python代码如下:

response = requests.get(f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={settings.APPID}&secret={settings.APPSECRET}')
response = response.json()
if response.get('access_token', ''):
 cache.set('access_token', response['access_token'])
 cache.expire('access_token', response['expires_in'])

在settings.py中配置:

CRONJOBS = (
 #每隔7200秒都生成一次access——token
 ('0 */2 * * *', 'django.core.management.call_command', ['runstat', '--token']),
)

这样就实现了每隔两小时自动获取token

Django发送模板消息

我们首先在微信公众平台中创建模板消息

然后把模板ID复制到项目中,编写视图函数。

@require_http_methods(["POST"])
@csrf_exempt
def notifications(request):
 if request.method == 'POST':
  access_token = cache.get('access_token')

  template_id = '你的模板id'
  push_data = {
   "keyword1": {
    "value": obj.order_sn
   },
   "keyword2": {
    "value": obj.time
   },
   "keyword3": {
    "value": "{:.2f}".format(float(obj.total_price))
   },
  }

  if access_token:
   # 如果存在accesstoken
   payload = {
    'touser': req_data.get('openid', ''), #这里为用户的openid
    'template_id': template_id, #模板id
    'form_id': req_data.get('form_id', ''), #表单id或者prepay_id
    'data': push_data #模板填充的数据
   }

   response = requests.post(f'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}',
       json=payload)

   #直接返回res结果
   return JsonResponse(response.json())
  else:
   return JsonResponse({
    'err': 'access_token missing'
   })

配置urls.py

#模板消息通知
path('api/v1/notifications/', notifications),

用户向notifications这个接口发送post请求后即可推送模板消息到微信中!!

以上这篇Django后端发送小程序微信模板消息示例(服务通知)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python建立Map写Excel表实例解析

Python建立Map写Excel表实例解析

本文主要研究的是用Python语言建立Map写Excel表的相关代码,具体如下。 前言:我们已经能够很熟练的写Excel表相关的脚本了。大致的操作就是,从数据库中取数据,建立Excel模...

Python 用matplotlib画以时间日期为x轴的图像

Python 用matplotlib画以时间日期为x轴的图像

1.效果展示 主要效果就是,x轴 显示时间单位。 下图展示的就是想要到达的效果。 其实主要是运用了datetime.date这个类型的变量作为x轴坐标的数据输入。 2. 源码...

python中enumerate的用法实例解析

在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法。具体如下: enumerate参数为可遍历的变量,...

Python批量查询关键词微信指数实例方法

Python批量查询关键词微信指数实例方法

教你用Python批量查询关键词微信指数。 前期准备安装好Python开发环境及Fiddler抓包工具。前期准备安装好Python开发环境及Fiddler抓包工具。 首先打开Fiddle...

python求最大连续子数组的和

抛出问题: 求一数组如 l = [0, 1, 2, 3, -4, 5, -6],求该数组的最大连续子数组的和 如结果为[0,1,2,3,-4,5] 的和为7 问题分析: 这个问题很...