1. 程式人生 > >python微信公眾賬號二次開發

python微信公眾賬號二次開發

微信公眾號開發網址:https://mp.weixin.qq.com/

注意:申請公眾賬號後,系統需要一天的稽核時間後,才能進行二次開發;

建立步驟:

1.申請免費且支援python的伺服器,新浪雲sae,新建SAE應用之後,有兩種程式碼提交方式,建議使用SVN(因為git支援程式碼提交,但不支援環境配置);

2.將對應版本的資訊複製到微信開發-基本配置-URL,提交顯示錯誤,因為還沒有寫程式碼,可以先用web框webpy架寫個網頁;

檢視webpy使用說明:http://www.webpy.org/install.zh-cn

檢視ase進行python開發入門說明:http://www.sinacloud.com/doc/sae/python/index.html

3.配置資訊,告訴新浪雲需要什麼執行環境。點選程式碼管理-編輯程式碼,將用到的第三方庫資訊寫入config.yaml,注意破折號,冒號後面空格!!

libraries:
- name: webpy
  version: "0.36"

- name: lxml
  version: "2.3.4"
在index.wsgi檔案中寫入python啟動程式
新建檔案,寫入接受微信get請求驗證的Python檔案

4.在index.wgsi中寫入以下資訊:

#coding=utf-8

import os
import sae
import web

from weixinInterface import WeixinInterface

#配置web的路由
urls = (
    '/weixin','WeixinInterface'
)
#拼接路徑
app_root=os.path.dirname(__file__)
templates_root = os.path.join(app_root,'templates')
#渲染模版
render = web.template.render(templates_root)

#啟動app
app = web.application(urls,globals()).wsgifunc()
application = sae.create_wsgi_app(app)
5.在自己編寫的Python檔案中寫入微信驗證和接受資訊的程式
#coding=utf-8

import hashlib
import web
import time
import os
from lxml import etree

#hashlib用於加密,md5,hash等
#lxml用來解析xml檔案

class WeixinInterface(object):
    #初始化
    def __init__(self):
        #拼接路徑
        self.app_root = os.path.dirname(__file__)
        self.templates_root = os.path.join(self.app_root,'templates')
        #渲染模版
        self.render = web.template.render(self.templates_root)

    #使用get方法,接收微信的get請求,看開發者文件的說明
    #http://mp.weixin.qq.com/wiki/8/f9a0b8382e0b77d87b3bcc1ce6fbc104.html
    def GET(self):
        data = web.input()
        signature = data.signature#微信加密簽名
        timestamp = data.timestamp#時間戳
        nonce = data.nonce#隨機數
        echostr = data.echostr#隨即字串
        token = 'zq90857'#自己設定的token

        #將token、timestamp、nonce三個引數進行字典序排序
        list = [token,timestamp,nonce]
        list.sort()
        #將三個引數字串拼接成一個字串進行sha1加密
        sha1=hashlib.sha1()
        map(sha1.update,list)
        temStr = sha1.hexdigest()#加密
        #判斷
        if temStr == signature:
            return echostr

7.假設接收文字資訊,按照開發者文件的要求,配置template資料夾下reply_text.xml檔案
$def with(toUser,fromUser,createtime,content)
<xml>
 <ToUserName><![CDATA[$toUser]]></ToUserName>
 <FromUserName><![CDATA[$fromUser]]></FromUserName> 
 <CreateTime>$createtime</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[$content]]></Content>
 </xml>
下圖1是新浪雲的介面,圖片2新浪雲環境配置和線上程式設計頁面,圖3是是微信公眾號開發後臺頁面,圖4是公眾號與粉絲通話結果