
python可以开发微信。下面我们来看一下使用python开发微信的方法:
1、申请免费且支持python的服务器,新浪云sae,新建SAE应用之后,有两种代码提交方式,建议使用SVN(因为git支持代码提交,但不支持环境配置);
2、将对应版本的信息复制到微信开发-基本配置-URL,提交显示错误,因为还没有写代码,可以先用web框webpy架写个网页;
3、配置信息,告诉新浪云需要什么运行环境。点击代码管理-编辑代码,将用到的第三方库信息写入config.yaml,注意破折号,冒号后面空格!!
1 2 3 4 5 6 | libraries:
- name: webpy
version: "0.36"
- name: lxml
version: "2.3.4"
|
在index.wsgi文件中写入python启动程序新建文件,写入接受微信get请求验证的Python文件
4、在index.wgsi中写入以下信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #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文件中写入微信验证和接受信息的程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #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:
def GET(self):
data = web.input()
signature = data.signature#微信加密签名
timestamp = data.timestamp#时间戳
nonce = data.nonce#随机数7a686964616fe4b893e5b19e31333363393735
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
|
6、假设接收文字信息,按照开发者文档的要求,配置template文件夹下reply_text.xml文件
1 2 3 4 5 6 7 8 | $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>
|
更多Python知识请关注Python视频教程栏目。