经过苦逼的踩坑,不得不说,开篇不说环境的都是耍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
能修改成功就ok了,开始更为漫长的踩坑之旅吧