栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

0x00 背景及介绍

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

0x01 语言和框架
  • 语言:Python

  • 框架:Django

  • 开发包:wechat-python-sdk

  • Github源码地址:
    https://github.com/PorridgeEater/WeChat

0x02 参考文档
  • 微信公众平台开发文档:
    http://mp.weixin.qq.com/wiki/home/index.html

  • sdk开发包文档:
    http://wechat-python-sdk.com/

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属性

基本配置

0x05 遇到的坑
  1. runserver后本地能够访问,外网不能访问

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

  1. 输入中文无法响应

  • import os后设置编码为utf8

  1. 端口号被占用

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

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


    实现效果图

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



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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/221685.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号