微信python开发笔记1
入门
-
进入微信公众平台 微信公众平台如何成为开发者
-
安装wechat-python-sdk wechat-python-sdk 开发包
pip install wechat-sdk
-
进入微信公众平台 微信公众平台
-
然后进入公众平台测试帐号,获取测试账号
-
接口配置信息
第五步接口配置信息说明
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
由此可见是返回传入进拉echostr则可以通过验证
最终例子
修改 wechat-python-sdk/examples/tutorial_official_1.py 使用bottle.py得
# -*- coding: utf-8 -*-
import requests
from wechat_sdk import (
WechatBasic,
WechatConf
)
from bottle import (
get,
post,
route,
run,
request
)
appid='wx8030b1cfdb5abe0b'
token = '123456'
appsecret='fb0b00d1c6221156661b33e32dee4264',
conf = WechatConf(
appid=appid,
appsecret=appsecret,
)
wechat = WechatBasic(token=token, conf=conf)
ment_data = {
'button':[
{
'type': 'click',
'name': '今日歌曲',
'key': 'V1001_TODAY_MUSIC'
},
{
'type': 'click',
'name': '歌手简介',
'key': 'V1001_TODAY_SINGER'
},
{
'name': '菜单',
'sub_button': [
{
'type': 'view',
'name': '搜索',
'url': 'http://www.soso.com/'
},
{
'type': 'view',
'name': '视频',
'url': 'http://v.qq.com/'
},
{
'type': 'click',
'name': '赞一下我们',
'key': 'V1001_GOOD'
} ] } ] }
wechat.create_menu(ment_data)
@get('/')
def sig():
# 下面这些变量均假设已由 Request 中提取完毕
signature = request.GET['signature']
timestamp = request.GET['timestamp']
nonce = request.GET['nonce']
# 实例化 wechat
# 对签名进行校验
if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):
return request.GET['echostr']
@post('/')
def handle():
# 下面这些变量均假设已由 Request 中提取完毕
body_text = request.body.read()
token = '123456'
signature = request.GET['signature']
timestamp = request.GET['timestamp']
nonce = request.GET['nonce']
wechat = WechatBasic(token=token)
# 对签名进行校验
if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):
# 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作)
wechat.parse_data(body_text)
# 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义)
message = wechat.get_message()
response = None
if message.type == 'text':
if message.content == 'wechat':
response = wechat.response_text(u'^_^')
else:
response = wechat.response_text(u'文字')
elif message.type == 'image':
response = wechat.response_text(u'图片')
else:
response = wechat.response_text(u'未知')
# 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出
return response
run(host='123.56.92.104', port=8888, debug=True)