1 min read

django 接入微信公众平台

  1. 利用 python django 介入微信公众平台
  2. 首先,需要成为 微信的开发者。
  3. 然后,搭建 django 环境 (可以参考官方文档)
    使用 Django 建立一个 微信公众平台的 项目
django-admin.py startproject wechat

最后, 在views 下加入一下代码

    from django.http import HttpResponse
    from django.core.exceptions import PermissionDenied
    from django.shortcuts import render_to_response
    from django.views.generic import View
    from django.utils.encoding import smart_str, smart_unicode
    from django.conf import settings
    import xml.etree.ElementTree as ET
    import hashlib
    import time
    TOKEN = getattr(settings, 'WechatToken', 'mywebtoken')  #定义 token
    class Weixin(View):
        token = TOKEN
        def validate(self, request):
            signature = request.REQUEST.get('signature', None)
            timestamp = request.REQUEST.get('timestamp', None)
            nonce = request.REQUEST.get('nonce', None)
            list = [self.token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            if signature == hashcode:
                return True
            else:
                return False
        def paraseMsgXml(self, rootElem):
            # logger.info(rootElem)
            msg = {}
            if rootElem.tag == 'xml':
                for child in rootElem:
                    msg[child.tag] = smart_str(child.text)
            return msg
        def get(self, request):
            if self.validate(request):
                echostr = request.GET.get('echostr', None)
                return HttpResponse(echostr)
            return PermissionDenied
        def post(self, request):
            rawStr = request.raw_post_data
            if self.validate(request):
                msg = self.paraseMsgXml(ET.fromstring(rawStr))
                return render_to_response('reply.xml',
                    {
                        'msg': msg,
                        'timestamp': str(int(time.time())),
                        'msgText': 'text',
                        'replyContent': 'welcome to my weichat',
                    },
                    mimetype="application/xml")
            else:
                return PermissionDenied