服務器搭建公衆號簡單回覆(新手教程)

官網:https://mp.weixin.qq.com/wiki?action=doc&id=mp1472017492_58YV5&t=0.6407812687055042#0

## 申請服務器,公衆號
博主申請了騰訊雲的服務器,還有一篇[騰訊雲簡單網站設置教程](https://blog.csdn.net/LuckyMon/article/details/89024375),這裏先關掉http服務器 service httpd stop,省得後面佔用80端口。公衆號能夠去微信公衆平臺申請,這裏博主申請了訂閱號。
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/2019051716285788.png)

## 搭建服務
這裏博主安裝了python2.7和 [web.py](http://webpy.org/),使用了pip進行安裝[Python pip 安裝與使用](https://www.runoob.com/w3cnote/python-pip-install-usage.html)

第一步肯定可否在服務器運行python,網頁端訪問,官網提供代碼以下:

```
# -*- coding: utf-8 -*-
# filename: main.py
import web

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

class Handle(object):
    def GET(self):
        return "hello, this is handle view"

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()
```
在服務器進入放 main.py 的文件夾,命令行輸入python main.py 80 ,此步易發生端口被佔用狀況,需多多注意。命令行顯示0.0.0.0 是正常狀況,可正常訪問  http://服務器IP/wx 。443端口一樣能夠使用,命令行輸入python main.py 443 ,可正常訪問  https://服務器IP/wx 。可依照實際狀況選擇。下圖是官網給的訪問狀況。
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20190517162620438.png)
## 開發者基本配置(token)
下圖是博主配置成功了的,沒有打碼,固然如今沒法訪問,博主把80端口改回了http服務。token令博主頭疼了很長時間。
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/2019051716311770.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0x1Y2t5TW9u,size_16,color_FFFFFF,t_70)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

class Handle(object):
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "hello, this is handle view"
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "hello" #我設置的token

            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print "handle/GET func: hashcode, signature: ", hashcode, signature
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception, Argument:
            return Argument
```
從新啓動 python main.py 80 ,成功的話,點擊啓動按鈕

## 簡單回覆
須要四個python
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 reply
import receive
import web

class Handle(object):
    def GET(self):
        try:
            data = web.input()
            if len(data) == 0:
                return "hello, this is handle view"
            signature = data.signature
            timestamp = data.timestamp
            nonce = data.nonce
            echostr = data.echostr
            token = "hello" #請按照公衆平臺官網\基本配置中信息填寫

            list = [token, timestamp, nonce]
            list.sort()
            sha1 = hashlib.sha1()
            map(sha1.update, list)
            hashcode = sha1.hexdigest()
            print "handle/GET func: hashcode, signature: ", hashcode, signature
            if hashcode == signature:
                return echostr
            else:
                return ""
        except Exception, Argument:
            return Argument

    def POST(self):
        try:
            webData = web.data()
            print "Handle Post webdata is ", webData#後臺打日誌
            recMsg = receive.parse_xml(webData)
            if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                content = "test"
                replyMsg = reply.TextMsg(toUser, fromUser, content)
                return replyMsg.send()
            else:
                print "暫且不處理"
                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
    if msg_type == 'text':
        return TextMsg(xmlData)

    elif msg_type == 'image':
        return ImageMsg(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")
class ImageMsg(Msg):
    def __init__(self, xmlData):
        Msg.__init__(self, xmlData)
        self.PicUrl = xmlData.find('PicUrl').text
        self.MediaId = xmlData.find('MediaId').text
```
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)
class ImageMsg(Msg):
    def __init__(self, toUserName, fromUserName, mediaId):
        self.__dict = dict()
        self.__dict['ToUserName'] = toUserName
        self.__dict['FromUserName'] = fromUserName
        self.__dict['CreateTime'] = int(time.time())
        self.__dict['MediaId'] = mediaId
    def send(self):
        XmlForm = """
            <xml>
            <ToUserName><![CDATA[{ToUserName}]]></ToUserName>
            <FromUserName><![CDATA[{FromUserName}]]></FromUserName>
            <CreateTime>{CreateTime}</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            <Image>
            <MediaId><![CDATA[{MediaId}]]></MediaId>
            </Image>
            </xml>
            """
        return XmlForm.format(**self.__dict)
```

所有添加後,從新啓動 python main.py 80 。成功向微信公衆號發送數據會返回test

html

相關文章
相關標籤/搜索