您的位置:首页 > 移动开发 > 微信开发

django wechatpy建立微信简单自动回复

2017-05-23 14:16 926 查看
首先申请下微信公众平台账号,进入公众平台
4000
开发-基础配置界面



在你的项目中编写代码

记得先安装下wechatpy(pip install wechatpy)

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.utils import check_signature

WECHAT_TOKEN = 'your token'
@csrf_exempt
def wechat(request):
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(WECHAT_TOKEN, signature, timestamp, nonce)
except InvalidSignatureException:
echo_str = 'error'
response = HttpResponse(echo_str, content_type="text/plain")
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
else:
logger.info('--------------------------------')

其中url配置如下:

url(r'^wechat', wechat, name='wechat')
说明http://www.zhangpengpeng.cn/wechat指向上述方法

然后提交服务器配置,并启用



进入微信公众号,随意发送一个信息

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: