为了账号安全,请及时绑定邮箱和手机立即绑定

Python微信后台开发--环境搭建与接入指南

标签:
Python

0x00 背景及介绍


申请一个微信公众平台订阅号,将后台接入到服务器上,验证服务器地址的有效性,实现简单的业务逻辑,根据用户发送不同类型的消息做出不同的反应。

0x01 语言和框架


0x02 参考文档


0x03 服务器配置


  • 系统:CentOS

  • 配置过程:

  1. 更新系统

yum update
  1. 安装python依赖包

yum groupinstall "Development tools"yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
  1. 安装python和pip及更新

yum install python
yum install python-pip
(sudo) pip install --upgrade pip
  1. 安装Django框架

pip install Django
  1. 安装wechat-python-sdk开发包

pip install wechat-sdk
  1. 新建一个Django实例

django-admin.py startproject PROJECT_NAMEcd PROJECT_NAME
python manage.py startapp APP_NAME
python manage.py makemigrations
python manage.py migrate
  1. 添加url规则(urls.py)

urlpatterns = [
        url(r'^wechat/', views.wechat_home),
]
  1. 编写views逻辑(views.py)

#-*- coding:utf-8 -*-import sys
reload(sys)
sys.setdefaultencoding('utf8')from django.http.response import HttpResponse, HttpResponseBadRequestfrom django.views.decorators.csrf import csrf_exemptfrom wechat_sdk import WechatConffrom wechat_sdk import WechatBasicfrom wechat_sdk.exceptions import ParseErrorfrom wechat_sdk.messages import (TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage, ShortVideoMessage)
conf = WechatConf(
        token='YOUR_TOKEN_HERE',
        appid='YOUR_APPID',
        appsecret='YOUR_APPSECRET',
        encrypt_mode='YOUR_MODE',
        encoding_aes_key='YOUR_AES_KEY')@csrf_exemptdef wechat_home(request):
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        wechat_instance = WechatBasic(conf=conf)        if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):            return HttpResponseBadRequest('Verify Failed')        else:            if request.method == 'GET':
                response = request.GET.get('echostr', 'error')            else:                try:
                    wechat_instance.parse_data(request.body)    
                    message = wechat_instance.get_message()         
                    if isinstance(message, TextMessage):            
                        reply_text = 'text'
                    elif isinstance(message, VoiceMessage):         
                        reply_text = 'voice'
                    elif isinstance(message, ImageMessage):         
                        reply_text = 'image'
                    elif isinstance(message, LinkMessage):          
                        reply_text = 'link'
                    elif isinstance(message, LocationMessage):      
                        reply_text = 'location'
                    elif isinstance(message, VideoMessage):         
                        reply_text = 'video'
                    elif isinstance(message, ShortVideoMessage):    
                        reply_text = 'shortvideo'
                    else:
                        reply_text = 'other'
                    response = wechat_instance.response_text(content=reply_text)                except ParseError:  
                    return HttpResponseBadRequest('Invalid XML Data')            return HttpResponse(response, content_type="application/xml")
  1. 开启django app,后台挂载在80端口

sudo python manage.py runserver 0.0.0.0:80 &

0x04 微信后台配置


  • 记录APPID和APPSecret填入views.py的conf属性

  • 填写服务器配置

    • 注意URL最后带上/,否则django会报POST URL error

    • 自定义token,填入views.py的conf属性

    • 自定义EncodingAESKey,填入views.py的conf属性

https://img1.sycdn.imooc.com//5d58b1bf000135a408590491.png

基本配置

0x05 遇到的坑


  1. runserver后本地能够访问,外网不能访问

  • 绑定ip到0.0.0.0,设置为对公监听即可

  1. 输入中文无法响应

  • import os后设置编码为utf8

  1. 端口号被占用

  • ps aux | grep manage后然后kill -9 相应进程号

0x06 后记


  • 能够识别不同的消息类型并进行相应回复


    https://img1.sycdn.imooc.com//5d58b1bc000158f504660837.png

    实现效果图

  • 代码的功能还有待完善,结构和逻辑也可以再设计得更清晰一些



作者:PorridgeEater
链接:https://www.jianshu.com/p/e6eb2dbef4c4


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消