Django微信公衆號接入

經過苦逼的踩坑,不得不說,開篇不說環境的都是耍xx。。

環境:
python3.7,pycharm,django
微信公衆號測試號申請
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
穿透軟件,ngrok或者釘釘的穿透軟件
https://ding-doc.dingtalk.com/doc#/kn6zg7/hb7000

依賴包
pip install wechatpy
(wechat-sdk 0.6.4 都已經3年沒更新了,我被埋了半天)

代碼:
urls.py 加一行

path('wechat/', views.wechat),

views.py

from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from wechatpy import parse_message, create_reply
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.pay import logger
from wechatpy.replies import TextReply
from wechatpy.utils import check_signature

token = 'weixin'

def wechat(request):
    # GET 方式用於微信公衆平臺綁定驗證
    if request.method == 'GET':
        signature = request.GET.get('signature', '')
        timestamp = request.GET.get('timestamp', '')
        nonce = request.GET.get('nonce', '')
        echo_str = request.GET.get('echostr', '')
        try:
            check_signature(token, signature, timestamp, nonce)
        except InvalidSignatureException:
            echo_str = '錯誤的請求'
        response = HttpResponse(echo_str)
        return response

    elif request.method == 'POST':
        msg = parse_message(request.body)
        if msg.type == 'text':
            reply = create_reply('這是條文字消息', msg)
        elif msg.type == 'image':
            reply = create_reply('這是條圖片消息', msg)
        elif msg.type == 'voice':
            reply = create_reply('這是條語音消息', msg)
        else:
            reply = create_reply('這是條其他類型消息', msg)
        response = HttpResponse(reply.render(), content_type="application/xml")
        return response

啓動項目後,
開啓穿透,
Django微信公衆號接入

微信測試號配置:
url處改爲自己的測試域名
Django微信公衆號接入

能修改成功就ok了,開始更爲漫長的踩坑之旅吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章