个人公众号服务端开发Demo

公众号出来很久了,也可以个人申请。知道公众号的服务端开发其实很简单,接口调用封装,数据存取,不外如是。

人一旦懒了,真的是 “无可救药” 了。。。现简单描述晚到的公众号HelloWorld

  • 思路

  公众号里面简单的文章展示,静态博客展示这种好像没啥特别的,就跳过了。

  在聊天框输入参数, 传到云服务器处理,然后请求个三方API获取信息,封装返回。嗯,这就算个基本的Demo了

  •  准备

  1, 得申请个公众号,个人的,免费

  2, 最好买一台云服务器,双十一的阿里云最低100¥/Year,heihei

  •   Let's go 

  按照 微信的公众号对接的文档来就可以了,直接贴代码

  main.py

# -*- coding: utf-8 -*-
# filename: main.py
import web
from handle import Handle

urls = (
    '/wx', 'Handle',
)

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()

 handle.py

# -*- coding: utf-8 -*-
# filename: handle.py

import hashlib
import web
import reply
import receive
import requests
import re
import logging

MY_TOKEN = "XXXXX" # 按照在公众号上的设置对应
URL_PHONENUM_INFO = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='root.log', level=logging.INFO, format=LOG_FORMAT)

# 调用查询号码省份运营商的API,简单暴力正则匹配结果返回
def getCurrentPhoneNumInfo(num):
    logging.info("getCurrentPhoneNumInfo[%s]", num)
    try:
        if re.match("^1[3|5|7|8]\d{9}$", num) == None:
            return "Error phone number format."
        else:
            r = requests.get(URL_PHONENUM_INFO + num)
            m = re.search("carrier\:\'(.*)\'.*", r.text, re.M)
            result = m.group(1)
            logging.info("result=%s" , result) 
            return result.encode("UTF-8") # python2的转码问题总是会坑到一批新人
    except Exception as e:
        logging.error(e)
        return "API error"

class Handle(object):
   
     # 文档中的Get不是为了对话框交互准备的,此处删除   

    def POST(self):
        try:
            webData = web.data()
            logging.warn("Handle Post webdata is %s", webData)
            #后台打日志
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                receiveContent = recMsg.Content
                logging.warn("receive content:" + receiveContent) 
                content = getCurrentPhoneNumInfo(receiveContent)
                replyMsg = reply.TextMsg(toUser, fromUser, content)
                return replyMsg.send()
            else:
                logging.error("格式不支持,暂且不处理") 
                return "success"
        except Exception, Argment:
            return Argment

receive.py

# -*- coding: utf-8 -*-
# filename: receive.py
import xml.etree.ElementTree as ET
def parse_xml(web_data):
    if len(web_data) == 0:
        return None
    xmlData = ET.fromstring(web_data)
    msg_type = xmlData.find('MsgType').text
  # 暂只处理text格式的消息,demo嘛
if msg_type == 'text': return TextMsg(xmlData) class Msg(object): def __init__(self, xmlData): self.ToUserName = xmlData.find('ToUserName').text self.FromUserName = xmlData.find('FromUserName').text self.CreateTime = xmlData.find('CreateTime').text self.MsgType = xmlData.find('MsgType').text self.MsgId = xmlData.find('MsgId').text class TextMsg(Msg): def __init__(self, xmlData): Msg.__init__(self, xmlData) self.Content = xmlData.find('Content').text.encode("utf-8")

reply.py

# -*- coding: utf-8 -*-
# filename: reply.py
import time
class Msg(object):
    def __init__(self):
        pass
    def send(self):
        return "success"
    
class TextMsg(Msg):

    def __init__(self, toUserName, fromUserName, content):
        self.__dict = dict()
        self.__dict['ToUserName'] = toUserName
        self.__dict['FromUserName'] = fromUserName
        self.__dict['CreateTime'] = int(time.time())
        self.__dict['Content'] = content
        
    def send(self):
        XmlForm = """
        <xml>
        <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
        <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
        <CreateTime>{CreateTime}</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[{Content}]]></Content>
        </xml>
        """
        return XmlForm.format(**self.__dict)

在加一个restat.sh 会用起来更舒服

ps -ef | grep "main.py" | grep -v grep  | awk '{print $2}' |xargs kill -9
python main.py 80 & 

效果图

【客户端--公众号】

 

【服务端日志】

 

posted @ 2018-11-15 21:28  hugh.zm  阅读(1061)  评论(2编辑  收藏  举报