flask開發微信公眾號


 

1.進入微信公眾號首頁,進行注冊登錄 https://mp.weixin.qq.com/

2.進入個人首頁,進行公眾號設置

可參照 公眾號文檔 進行開發

開發前 先閱讀 接口權限列表

3.配置服務器 服務器地址(URL) 令牌(Token)
 開發者基本配置

import hashlib
@app.route('/wx',methods=['GET','POST'])
def wx():
    if request.method == 'GET':
        signature = request.args.get('signature')
        timestamp = request.args.get('timestamp')
        echostr = request.args.get('echostr')
        nonce = request.args.get('nonce')
        token = 'mytoken1'
        if len(request.args)==0:
            return "hello, this is handle view"
        list = [token, timestamp, nonce]
        list.sort()
        s = list[0]+list[1]+list[2]
        hashcode = hashlib.sha1(s.encode('utf-8')).hexdigest()
        if hashcode == signature:
            return echostr
        else:
            print('驗證失敗')
            return ""

重新啟動成功后(python main.py 80),點擊提交按鈕。若提示”token驗證失敗”, 請認真檢查代碼或網絡鏈接等。若token驗證成功,會自動返回基本配置的主頁面,點擊啟動按鈕

4.接收用戶發送的消息 (即粉絲給公眾號發送的文本消息)
公眾平台發送的xml至開發者服務器。
形式:

發送xml

# 接收
        import xml.etree.cElementTree as ET
        
        xml = ET.fromstring(request.data)
        toUser = xml.find('ToUserName').text
        fromUser = xml.find('FromUserName').text
        msgType = xml.find("MsgType").text

5.自動回復 文本消息

     if msgType == 'text':
		......
        reply = '''<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[text]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>'''
        response = make_response(reply % (fromUser, toUser, str(int(time.time())), end))
        response.headers['content-type'] = 'application/xml'
        return response

6. 實現“圖”尚往來

        elif msgType == 'image':
            img = xml.find('MediaId').text
            reply = '''<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[image]]></MsgType>
                                 <Image>
                                 <MediaId><![CDATA[%s]]></MediaId>
                                 </Image>
                                </xml>'''
            response = make_response(reply % (fromUser, toUser, str(int(time.time())), img))
            response.headers['content-type'] = 'application/xml'
            return response

7.臨時素材

class Basic(object):
    def __init__(self):
        self.accessToken = ''
        self.leftTime = ''

    def real_get_access_token(self):
        AppID = '....'
        AppSecret = '...'
        postUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (AppID, AppSecret)
        resp = requests.get(url=postUrl)
        urlResp = json.loads(resp.text)
        access_token = urlResp['access_token']
        print('access_token是',access_token)
        return access_token
class Media(object):
    def __init__(self):
        self.access_token = Basic().real_get_access_token()

    def upload(self,type='image',path=None):
        files = {'apk': open(path, 'rb')}
        data = {'enctype': 'multipart/form-data'}
        post_url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s'%(self.access_token,type)
        resp = requests.post(url=post_url,data=data,files=files)
        urlResp = json.loads(resp.text)
        print(urlResp)

media = Media()
media.upload(path='123.png')

8.關注和取消事件

用戶在關注與取消關注公眾號時,微信會把這個事件推送到開發者填寫的URL。方便開發者給用戶下發歡迎消息或者做帳號的解綁。為保護用戶數據隱私,開發者收到用戶取消關注事件時需要刪除該用戶的所有信息。

微信服務器在五秒內收不到響應會斷掉連接,並且重新發起請求,總共重試三次。
形式:
視圖處理:

        elif msgType == 'event':
            event = xml.find('Event').text
            if event == 'subscribe':   #關注
                msg = '輸入想要視頻資源關鍵字試試~'  
            else:  #取消關注
                msg = '期待你的下次關注~'
            reply = '''<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[text]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                </xml>'''
            response = make_response(reply % (fromUser, toUser, str(int(time.time())), msg))
            response.headers['content-type'] = 'application/xml'
            return response

9.回復圖文消息
在這里插入圖片描述

            reply = '''<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[news]]></MsgType>
                                <ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[%s]]></Title>
                                <Description><![CDATA[%s]]></Description>
                                <PicUrl><![CDATA[%s]]></PicUrl><Url>
                                <![CDATA[%s]]></Url></item></Articles>
                                </xml>'''
            response = make_response(reply % (fromUser, toUser, int(time.time()), 'voice','voice Description','http://mmbiz.qpic.cn/mmbiz_jpg/jeXD1dScd9sHxTr4WGwywQiabrcrErmR9p86ZUDthLWcImgLepRMxYrhrVMemibp4nCHpyHFPn7yvYv5A49miarKQ/0?wx_fmt=jpeg','https://www.baidu.com'))
            response.headers['content-type'] = 'application/xml'
            return response

截圖:在這里插入圖片描述
10.js接口安全域名

設置JS接口安全域名后,公眾號開發者可在該域名下調用微信開放的JS接口。

注意事項:

1、可填寫三個域名或路徑(例:wx.qq.com或wx.qq.com/mp),需使用字母、數字及“-”的組合,不支持IP地址、端口號及短鏈域名。

2、填寫的域名須通過ICP備案的驗證。

3、 將文件MP_verify_hS2bkgbglKjk0udm.txt(點擊下載)上傳至填寫域名或路徑指向的web服務器(或虛擬主機)的目錄(若填寫域名,將文件放置在域名根目錄下,例如wx.qq.com/MP_verify_hS2bkgbglKjk0udm.txt;若填寫路徑,將文件放置在路徑目錄下,例如wx.qq.com/mp/MP_verify_hS2bkgbglKjk0udm.txt),並確保可以訪問

步驟1.,將文件引入到 項目同一級目錄

步驟2.更改flask查找文件路徑

因為查找路徑為:wx.qq.com/MP_verify_hS2bkgbglKjk0udm.txt

app = Flask(name,static_url_path=’’)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM