Djangoのバックエンドは、アプレットマイクロレターテンプレートメッセージ(サービス通知)を送信します

メッセージテンプレート

公式文書:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/template-message/templateMessage.send.html
テンプレートメッセージ下図のように

Djangoはaccess_tokenは取得しました

文書は、説明文書をaccess_tokenは取得メッセージテンプレートを送信することができるaccess_tokenは後端を取得する必要があり、文書はトークンは2時間有効であることを示し、後端のタイミングを取得する必要があります。ここでは、定期的なタスクを達成するためのジャンゴ- crontabのサードパーティ製のパッケージを使用しています。
pip install django-crontab
文書の記載によれば、する必要があるhttps://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRETアドレスを取得し、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']),
)

二時間おきに自動的にこの実現には、トークンを取得します

メッセージを送信するための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),

ユーザーは、メッセージテンプレートインターフェイスマイクロ手紙に通知を送信するためにPOSTリクエストをプッシュすることができます!

おすすめ

転載: www.cnblogs.com/PyKK2019/p/11610482.html