Django后端發(fā)送小程序微信模板消息示例(服務(wù)通知)
模板消息
模板消息如下圖所示
Django中獲取access_token
根據(jù)文檔描述,獲取access_token文檔,后端必須獲取一個access_token才能夠發(fā)送模板消息,文檔中說明該token有效期為兩小時,需要后端定時去獲取。我們這里使用Django-crontab第三方包來實(shí)現(xiàn)定時任務(wù)。
pip install django-crontab
根據(jù)文檔描述,需要向https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET這個地址發(fā)送get請求,返回結(jié)果為access_token
我把a(bǔ)ccess_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']), )
這樣就實(shí)現(xiàn)了每隔兩小時自動獲取token
Django發(fā)送模板消息
我們首先在微信公眾平臺中創(chuàng)建模板消息
然后把模板ID復(fù)制到項(xiàng)目中,編寫視圖函數(shù)。
@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 #模板填充的數(shù)據(jù) } response = requests.post(f'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}', json=payload) #直接返回res結(jié)果 return JsonResponse(response.json()) else: return JsonResponse({ 'err': 'access_token missing' })
配置urls.py
#模板消息通知 path('api/v1/notifications/', notifications),
用戶向notifications這個接口發(fā)送post請求后即可推送模板消息到微信中?。?/p>
以上這篇Django后端發(fā)送小程序微信模板消息示例(服務(wù)通知)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中執(zhí)行調(diào)用JS的多種實(shí)現(xiàn)方法總結(jié)
這篇文章主要給大家介紹了關(guān)于Python中執(zhí)行調(diào)用JS的多種實(shí)現(xiàn)方法,在一些特殊的python應(yīng)用場景下需要逆向執(zhí)行javascript代碼塊或者.js文件,需要的朋友可以參考下2023-08-08pycharm2023.1配置python解釋器時找不到conda環(huán)境解決辦法
如果你已經(jīng)安裝了Anaconda或Miniconda,但是在PyCharm中找不到conda解釋器,可以試試本文介紹的方法,這篇文章主要給大家介紹了關(guān)于pycharm2023.1配置python解釋器時找不到conda環(huán)境的解決辦法,需要的朋友可以參考下2023-12-12python3.6+opencv3.4實(shí)現(xiàn)鼠標(biāo)交互查看圖片像素
這篇文章主要為大家詳細(xì)介紹了python3.6+opencv3.4實(shí)現(xiàn)鼠標(biāo)交互查看圖片像素,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02python (logging) 日志按日期、大小回滾的操作
這篇文章主要介紹了python (logging) 日志按日期、大小回滾的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python pip install如何修改默認(rèn)下載路徑
這篇文章主要介紹了Python pip install如何修改默認(rèn)下載路徑,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04