个人公众号服务端开发Demo

Posted hughzm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了个人公众号服务端开发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)

效果图

【客户端--公众号】

 技术分享图片

【服务端日志】

技术分享图片

 


以上是关于个人公众号服务端开发Demo的主要内容,如果未能解决你的问题,请参考以下文章

微信公众平台开发教程 订阅号与服务号的区别

一分钟开始持续集成之旅系列之:微信公众号服务器端应用(以 Java 后端为基础)

个人微信公众号搭建Python实现 -开发配置和微信服务器转入-认识微信公众号(14.1.1)

微信公众号开发,微信手机端一直提示该公众号暂时无法提供服务,请稍候再试

Java后端开发工程师简历加分项:公众号个人简历搭建

微信公众号开发-遇到的坑