Message templates
The official document: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/template-message/templateMessage.send.html
template message as shown below
Django acquired access_token
The document describes, obtaining access_token document , must obtain a access_token rear end can send a message template, the document indicates that the token is valid for two hours, it is necessary to acquire the timing of the rear end. Here we use the Django-crontab third-party package to achieve regular tasks.
pip install django-crontab
According to the document description, it is necessary to https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
send the request to get the address and return the results to access_token
I access_token stored in the cache
Python code is as follows:
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'])
In settings.py
the configuration:
CRONJOBS = (
#每隔7200秒都生成一次access——token
('0 */2 * * *', 'django.core.management.call_command', ['runstat', '--token']),
)
This realization every two hours automatically get token
Django template to send a message
We first create a message template in micro-channel public platform
Then copy the template ID into the project, write the view function.
@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'
})
Configurationurls.py
#模板消息通知
path('api/v1/notifications/', notifications),
A user can push the post request to send notifications to the message template interface micro letter! !