Python微信订餐小程序课程视频


Python实战量化交易理财系统


flask wechatpy网页授权

先写个调用微信接口例子的例子

网上全是 Django的例子,完全没有个flask的例子,我来写些简单的例子。希望帮到和我一样的业余选手。wechatpy是微信各种接口的封装,所以用这个模块我们个人也可以快速做出比较复杂的各种微信程序。不用管各种请求,恶心的签名什么的。感觉就是一键通过,感谢大牛们的wechatpy让我们能专注在程序功能逻辑上。

下面写一些简单的例子,自己开发过这些的应该一看就懂。

业余的多久没接触了,多少东西忘了,说个大概意思吧,可能多少东西有些用词不准,见谅。

主动接口调用

#主动接口调用例子
from wechatpy import WeChatClient
CORP_ID = 'wx---------------'
SECRET = 'cdc*****************'
client = WeChatClient(CORP_ID, SECRET)
#短短4行,你可以调用各种主动接口,获取token什么的
#格式为:client+接口函数 大家可以在wechatpy上慢慢试,一键通过
#不用自己post /get什么,真好。生活这美好
print(client.customservice.get_accounts())
print(client.fetch_access_token())

消息回复

#消息回复
#flask不做解释,只介绍wechatpy
from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')#这里是接受所有请求,你们自己可以改下
def get_dir(path):
msg = parse_message(request.get_data())
#解析 XML 消息
print(msg)
reply = create_reply('这里是要回复的内容', message=msg)
#构建 Reply 传入一个合法的 Message 对象来自动生成 source 和 target:
print(reply)
return reply.render()#回复完成,我去,除去服务架构,又是三行完成。
#想着原来自己慢慢写每个步骤想哭。

if __name__ == '__main__':
app.run(
host='0.0.0.0',port=443,debug = True,
ssl_context=(
'./SSL/1_jinxinhp.cn_bundle.crt',
'./SSL/2_jinxinhp.cn.key'
)
)#4个0表示监听所有ip。默认只监听本地

flask wechatpy网页授权

#本着绝不手动处理接口的心态,必须自己不做任何拼接,请求
#就两个字,爽爽。本例以获取到openid为结束
from flask import Flask, request, redirect, jsonify, session, abort
import functools
from wechatpy.oauth import WeChatOAuth
from wechatpy.enterprise import WeChatClient
app = Flask(__name__)

CORP_ID = 'wx7*******************'
SECRET = 'cdc***********************'
app.secret_key = 'key'

client = WeChatClient(
CORP_ID,
SECRET)
#微信客户端对象,获取openid只有获取用户信息,关注了公众号才行
#所以我们只是用来取授权跳转地址和code,把地址和code再填入用公众号对象
#就可以得到openid了。openid信息=众号对象.fetch_access_token(code)
#整个步骤就完成了

url=''#授权跳转地址缓存
@app.route('/wx/')#这里注意回调地址和授权地址我的都一样
#如果不一样注意调节一下网络结构
#如果第一次开发要注意,这些敏感操作,都需要在公众号上授权地址的,老玩家也别忘了
def index():
global url
code = request.args.get('code', None)#获取转跳后的code
if code:#获取到code,说明是授权转跳后请求
#创建公众号 OAuth对象,才能获取openid
oauthClient = WeChatOAuth(app_id=CORP_ID ,
secret=SECRET,
redirect_uri=url)
try:
user_openid = oauthClient.fetch_access_token(code)
#用公众号OAuth对象以code获取openid的json信息
except Exception as e:
print ('发生错误')

return user_openid#获取openid的json信息返回到网页上
else:#code为空,说明是第一次请求,就是请求授权的页面
state = request.args.get('state', None)#stat自定义内容
url=client.oauth.authorize_url(request.url,state=state)
#获取coed和redirect_uri,code不用处理,在地址参数里取就行了
#redirect_uri地址就需要自己用变量存一下了。
return redirect(url )


if __name__ == '__main__':
app.run(
host='0.0.0.0',port=443,debug = True,
ssl_context=(
'./SSL/1_jinxinhp.cn_bundle.crt',
'./SSL/2_jinxinhp.cn.key'
)
)#4个0表示监听所有ip。默认只监听本地

自己也刚写到这里,因为真的太方便了,网上又没有例子,所以在网上印个模子,方便后来人。

flask wechatpy jssdk验证

server.py要几个文件了,所以标下

#今天不行了,要自己动手了
#不能享受一步到位了
#只是个测试程序,后面把token和ticket取出来单独储存
from flask import Flask, request, redirect, jsonify, session, render_template
import functools
from wechatpy.oauth import WeChatOAuth
from wechatpy.enterprise import WeChatClient
import wechatpy
import time
import random

app = Flask(__name__)

CORP_ID = 'wx*****************'
SECRET = 'cdc**********************'

client2 = wechatpy.WeChatClient(
CORP_ID,
SECRET
)
app.secret_key = 'key'

client = WeChatClient(
CORP_ID,
SECRET
)
url=''
@app.route('/wx/')

def index():
global url
print('')
#print()
code = request.args.get('code', None)

if code:
oauthClient = WeChatOAuth(app_id=CORP_ID ,
secret=SECRET,
redirect_uri=url)
try:
user_info = oauthClient.fetch_access_token(code)
except Exception as e:
print ('发生错误')

return render_template("html/网页应用.html")
else:
state = request.args.get('state', None)#stat自定义内容
url=client.oauth.authorize_url(request.url,state=state)
return redirect(url )
#因为百度搜不到,我也就不想怎注释了
#此处为微信jssdk的ajax请求
#需要在公众上设置该网址jssdk权限,别忘了
@app.route('/wx/jssdk',methods = ['POST'])
def wxjssdk():
print('………………………………………',request.form)
#print('-----------------',client2.jsapi.get_jsapi_card_params)
url=request.form.get('url')
ticket=client2.jsapi.get_jsapi_ticket()
print(ticket)
noncestr=''.join(random.sample(string.ascii_letters + string.digits, 8))
timestamp=str(int(time.time()))
signature=client2.jsapi.get_jsapi_signature(noncestr, ticket, timestamp, url)
print(signature)
return jsonify({'timestamp':timestamp,'nonceStr':noncestr,'signature':signature})

if __name__ == '__main__':
app.run(
host='0.0.0.0',port=443,debug = True,
ssl_context=(
'./SSL/1_jinxinhp.cn_bundle.crt',
'./SSL/2_jinxinhp.cn.key'
)
)#4个0表示监听所有ip。默认只监听本地

前端文件 html文件路径为 \templates\html\网页应用.html 网页应用.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回调页面</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

<script>


// 请求签名
$.ajax({
url: "jssdk",
type: 'post',
data: { url: location.href.split('#')[0]},
success:function(res){
//alert('res: '+res.signature);
wx.config({
debug: false,
appId: 'wx-------------------',
timestamp: res.timestamp,
nonceStr: res.nonceStr,
signature: res.signature,
jsApiList: [
'onMenuShareTimeline',
'closeWindow',
'hideAllNonBaseMenuItem',
'showMenuItems',
'onMenuShareTimeline',

'getLocation','openLocation'
]
});
wx.ready(function () {//jssdk 初始化完成
alert('成功');

});

//wx.closeWindow();//关闭窗口"menuItem:exposeArticle"
wx.error(function (res) {
alert('错误:'+res.errMsg); // 正式环境记得关闭啊!!!!
});

}
});

///返回关闭窗口
$(function(){
pushHistory();//加入空的页面记录
window.addEventListener("popstate", function(e) {
wx.closeWindow();//关闭窗口
}, false);
function pushHistory() { //加入空的页面记录
var state = {
title: "title",
url: "#"
};
window.history.pushState(state, "title", "#");
}
}) ///返回关闭窗口

</script>

</body>
</html>

好了,网页应用到处结束了。你可以任意构建自己的程序了。 看看我过几天写不写支付,支付也一样。 下次写了支付再传一次