怎么用python 导出微信 python收藏

首先,我们要先看看微信远程控制电脑的原理是什么呢?
我们可以利用Python的标准库控制本机电脑,然后要实现远程的话,我们可以把电子邮件作为远程控制的渠道,我们用Python自动登录邮箱检测邮件,当我们发送关机指令给这个邮箱的时候,若Python检测到相关的指令,那么Python直接发送本机的相关命令。
下面来分析一下该项目:
1.需求分析
1.范围:用Python开发一个远程操控电脑的项目。
2.总体要求:
总体功能要求:能够通过该软件远程控制该软件所在的电脑的重启或关机操作。
系统要求:开发语言使用Python,并且开发出来的程序能在Windows运行。
首先,我们可以利用Python的标准库控制本机电脑,然后要实现远程的话,我们可以把电子邮件作为远程控制的渠道,我们用Python自动登录邮箱检测邮件,当我们发送关机指令给这个邮箱的时候,若Python检测到关机的指令,那么Python直接发送本机的关闭。
本项目的流程图如下
第一步,需要注册一个新浪邮箱。然后点击新浪邮箱点击右上角设置如图
选择“客户端pop/imap/smtp”
打开新浪邮箱的SMTP与POP3功能
具体实现代码:
配置文件config.ini
smtphost =
username =
password = XXX
timelimit = 2
shutdown=shutdown -f -s -t 100 -c closing...
music = F:Masetti - Our Own Heaven.mp3
video = F:Jai Waetford - Shy.mp4
notepad = notepad
excutor.py
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import win32api
from mccLog import mccLog
class executor(object):
def __init__(self,commandDict,openDict):
:param commandDict:
:param openDict:
self.mccLog = mccLog()
mandDict = commandDict
self.openDict = openDict
def execute(self,exe,mailHelper):
self.mailHelper = mailHelper
subject = exe['subject']
print u'start to process'
if subject !='pass':
self.mailHelper.sendMail('pass','Slave')
if subject in mandDict:
print u'start command'
command = mandDict[subject]
os.system(command)
self.mailHelper.sendMail('Success','Boss')
print u'command success'
except Exception,e:
print 'command error'
self.mailHelper.sendMail('error','boss',e)
elif subject in self.openDict:
print u'open the file now'
openFile = self.openDict[subject]
win32api.ShellExecute(0,'open',openFile,'','',1)
self.mailHelper.sendMail('Success','Boss')
print u'open file success'
except Exception,e:
print u'open file error'
self.mailHelper.sendMail('error','Boss',e)
elif subject[:7].lower() =='sandbox':
self.sandBox(subject[8:])
self.mailHelper.sendMail('error','Boss','no such command!')
def sandBox(self,code):
name = code.split('$n$')[0]
code = code.split('$n$')[1]
codestr = '\n'.join(code.split('$c$'))
codestr = codestr.replace('$',' ')
with open(name,'a') as f:
f.write(codestr)
os.system('python' + name)
configReader.py
import ConfigParser
import os,sys
class configReader(object):
def __init__(self,configPath):
configFile = os.path.join(sys.path[0],configPath)
self.cReader = ConfigParser.ConfigParser()
self.cReader.read(configFile)
def readConfig(self,section,item):
return self.cReader.get(section,item)
def getDict(self,section):
commandDict = {}
items = self.cReader.items(section)
for key,value in items:
commandDict[key] = value
return commandDict
日志文件mccLog.py
import logging
from datetime import datetime
class mccLog(object):
def __init__(self):
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=datetime. now().strftime('%Y%m%d%H%M%S') + '.log',
filemode='a'
def mccWriteLog(self,logContent):
(logContent)
def mccError(self,errorContent):
logging.error(errorContent)
mailHelper.py
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from email.mime.text import MIMEText
from configReader import configReader
from mccLog import mccLog
import poplib
import smtplib
class mailHelper(object):
CONFIGPATH = 'config.ini'
def __init__(self):
初始化邮件
self.mccLog = mccLog()
cfReader = configReader(self.CONFIGPATH)
self.pophost = cfReader.readConfig('Slave','pophost')
self.smtphost = cfReader.readConfig('Slave','smtphost')
self.port = cfReader.readConfig('Slave','port')
self.username = cfReader.readConfig('Slave','username')
self.password = cfReader.readConfig('Slave','password')
self.bossMail = cfReader.readConfig('Boss','mail')
self.loginMail()
self.configSlaveMail()
def loginMail(self):
self.mccLog.mccWriteLog('start to login the E-mail')
print 'start to login e-mail'
self.pp = poplib.POP3_SSL(self.pophost)
self.pp.set_debuglevel(0)
self.pp.user(self.username)
self.pp.pass_(self.password)
self.pp.list()
print 'login successful!'
self.mccLog.mccWriteLog('login the email successful!')
print 'login the email successful!'
except Exception,e:
print 'Login failed!'
self.mccLog.mccWriteLog('Login the email failed!')
def acceptMail(self):
self.mccLog.mccWriteLog('Start crawling mail!')
print 'Start crawling mail'
ret = self.pp.list()
mailBody = self.pp.retr(len(ret[1]))
self.mccLog.mccWriteLog('Catch the message successfully')
print 'Catch the message successfully'
return mailBody
except Exception,e:
self.mccLog.mccError('Catch the message failed' + e)
print 'Catch the message failed'
return None
def analysisMail(self,mailBody):
正则分析邮件
:param mailBody:
self.mccLog.mccWriteLog('Start crawling subject and sender')
print 'Start crawling subject and sender'
subject = re.search("Subject: (.*?)',",str(mailBody[1]).decode('utf-8'),re.S).group(1)
print subject
sender = re.search("'X-Sender: (.*?)',",str(mailBody[1]).decode('utf-8'),re.S).group(1)
command = {'subject':subject,'sender':sender}
self.mccLog.mccWriteLog("crawling subject and sender successful!")
print 'crawling subject and sender successful'
return command
except Exception,e:
self.mccLog.mccError("crawling subject and sender failed!" + e)
print 'crawling subject and sender failed!'
return None
def sendMail(self,subject,receiver,body='Success'):
:param subject:
:param receiver:
:param body:
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = subject
msg['from'] = self.username
self.mccLog.mccWriteLog('Start sending mail' + 'to' +receiver)
print 'Start sending mail'
if receiver == 'Slave':
self.handle.sendmail(self.username,self.username,msg.as_string())
self.mccLog.mccWriteLog('Send the message successfully')
print 'Send the message successfully'
except Exception,e:
self.mccLog.mccError('Send the message failed' + e)
print 'Send the message failed'
return False
elif receiver == 'Boss':
self.handle.sendmail(self.username,self.bossMail,msg.as_string())
self.mccLog.mccWriteLog('Send the message successfully')
print 'Send the message successfully'
except Exception,e:
self.mccLog.mccError('Send the message failed!' + e)
print 'Send the message failed!'
return False
def configSlaveMail(self):
self.mccLog.mccWriteLog('Start configuring the mailbox')
print 'Start configuring the mailbox'
self.handle = smtplib.SMTP(self.smtphost, self.port)
self.handle.login(self.username, self.password)
self.mccLog.mccWriteLog('The mailbox configuration is successful')
print 'The mailbox configuration is successful'
except Exception, e:
self.mccLog.mccError('The mailbox configuration is failed' + e)
print 'The mailbox configuration is failed'
weiChatControlComputer.py
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import time
import sys
from mailHelper import mailHelper
from excutor import executor
from configReader import configReader
__Author__ = 'william'
__Verson__ = 0.5
reload(sys)
sys.setdefaultencoding('utf-8')
class MCC(object):
CONFIGPATH = 'config.ini'
KEY_COMMAND = 'Command'
KEY_OPEN = 'Open'
KEY_BOSS = 'Boss'
KEY_TIMELIMIT = 'timelimit'
def __init__(self):
self.mailHelper = mailHelper()
self.configReader = configReader(self.CONFIGPATH)
commandDict = self.configReader.getDict(self.KEY_COMMAND)
openDict = self.configReader.getDict(self.KEY_OPEN)
self.timeLimit = int(self.configReader.readConfig(self.KEY_BOSS,self.KEY_TIMELIMIT))
self.excutor = executor(commandDict,openDict)
self.toRun()
def toRun(self):
实现轮训操作
while True:
self.mailHelper = mailHelper()
self.run()
time.sleep(self.timeLimit)
def run(self):
mailBody = self.mailHelper.acceptMail()
if mailBody:
exe = self.mailHelper.analysisMail(mailBody)
self.excutor.execute(exe,self.mailHelper)
if __name__ == '__main__':
mcc = MCC()
运行截图:
在这个小项目的编写过程中,知道了项目开发的基本流程并且走了一遍,通过项目管理的方式去开发项目,并且在这个小项目开发的过程中,复习了Python一些初级阶段的基础知识,并且更深刻体会到从项目的设计到项目的实施,以及项目的测试运维等步骤需要程序员深刻的理解,这样才能在项目中逐渐完善自我。
待续。。。
本文已收录于以下专栏:
相关文章推荐
Python实现网页版微信登陆
#!/usr/bin/python
#coding=UTF-8
import requests, json
import itchat
import os,time,datetime
from PIL...
最近上网换了个运营商,只能插有线。于是手机自然就只能接受笔记本的热点了。但是晚上上床玩手机时电脑不关,玩到3、4点再下去关未免太麻烦了。
为了解决这个问题,我想到了两个办法:
1.不玩手机了
itchatmp是一个开源的微信公众号、企业号接口,使用python调用微信公众号从未如此简单。
基于Itchat,微信远程访问电脑文件设计思路
用户输入用户名和密码后遍历当前硬盘分区
为每一个路径和文件建立索引
区分路径和文件,以便于查看
每次显示内容包括当前路径下所有文件和文件夹,以及前一...
介绍通过邮件在世界任何地方控制电脑的方法。
1.准备材料
首先电脑上需要安装了python,安装了opencv更好(非必需)
如果安装了opencv的话,在opencv的python目录下找到cv2.pyd,将该文件放到python的库搜索路...
我主要参考这篇文章进行实践:点击打开链接
python版本:3.5
首先整体步骤分为两步:第一步,抓取好友个性签名,这一步主要依靠itchat实现;第二步,分词并形成词云,主要依靠jieba和wo...
今天来分享一个“高大上”的技术——使用python编写一个可以用微信远程控制电脑的程序!
先来分析一下控制的具体流程:
我们使用微信给特定的邮箱发送一封邮件,其中包含了我们想要电脑执行的命令,...
他的最新文章
讲师:刘文志
讲师:陈伟
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)(python学习)
(python学习)
第三方登录:欢迎大家访问我的个人网站:
主要分享Python 及Django教程以及相关的博客
交流QQ群:
欢迎大家访问我的主页:
Python 及Django兴趣交流QQ群:
今天偶然看见/jiaoyu121/p/6944398.html#top博客,用Python玩转微信,写得非常好。
然而,貌似用的Python2版本,并且每次执行都要重复扫码登录,这对于我这种Python3的用户是不行的。
动起手来,自己干!
1. 安装相应的库
pip install itchat
pip install echarts-python
2. 实现登陆状态保存:
import itchat
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
这样你就可以保持一段时间登录状态,而不用每次运行代码都要扫码登录了!
首次登录,程序会弹出一个二维码图片窗口,用微信手机客户端扫码就可以登录了!
3. 使用饼图展示个人好友性别分布
有一个echarts-python库可以帮助你方便的使用python代码在浏览器中展示百度Echart图。但是,但是,这个库是Python2的,
Python3用起来水土不服,没办法只好根据错误修改库的源码!下图显示了应该改的两个地方(其实还有很多地方)。
改完库的源码,就可以执行代码了。借用前人的代码,修改了一下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import itchat
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
friends = itchat.get_friends(update=True)[:]
total = len(friends) - 1
male = female = other = 0
for friend in friends[1:]:
sex = friend[&Sex&]
if sex == 1:
elif sex == 2:
female += 1
other += 1
# print(&男性好友:%.2f%%& % (float(male) / total * 100))
# print(&女性好友:%.2f%%& % (float(female) / total * 100))
# print(&其他:%.2f%%& % (float(other) / total * 100))
from echarts import Echart, Legend, Pie
chart = Echart('%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
[{'value': male, 'name': '男性 %.2f%%' % (float(male) / total * 100)},
{'value': female, 'name': '女性 %.2f%%' % (float(female) / total * 100)},
{'value': other, 'name': '其他 %.2f%%' % (float(other) / total * 100)}],
radius=[&50%&, &70%&]))
chart.use(Legend([&male&, &female&, &other&]))
del chart.json[&xAxis&]
del chart.json[&yAxis&]
chart.plot()
运行代码,测试一下,成功在浏览器展示出来了:
我好想暴露了什么....
4. 好友个性签名词云
分析好友信息,能发现个性签名,可以用它做词云。
for friend in friends:
signature = friend[&Signature&].strip()
signature = re.sub(&&span.*&&, &&, signature)
signature_list.append(signature)
raw_signature_string = ''.join(signature_list)
上面利用正则,去掉一些类似&span class=....&以及空格之类的无用字符。然后把他们连成一个大的长的字符串
pip install jieba
这个库是用来将字符串拆分成不重复的一个一个的词的,貌似都是2字词。
pip install wordcloud
安装词云库,会弹出错误如下图
怎么办?去http://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud 页面下载所需的wordcloud模块的whl文件
下载后进执行“pip install wordcloud-1.3.1-cp36-cp36m-win_amd64.whl”,就可以了。意文件路径。
利用jieba的cut方法将字符串裁成一个一个的词,然后用空格,将它们又连起来。注意是用空格哦!千万别看错了!
text = jieba.cut(raw_signature_string, cut_all=True)
target_signatur_string = ' '.join(text)
再导入一些辅助的库
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import PIL.Image as Image
import numpy as np
这些库,有的会自动安装,有的可能要你自己装,比如pip install numpy
然后提供一张图片。
wordcloud会根据这张图片在x和y轴上的颜色以及范围等等,布置词云。这个过程是通过numpy的矩阵和matplot的画图能力实现的。
下面的源码是根据原文的代码略微修改后的。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import itchat
import jieba
def echart_pie(friends):
total = len(friends) - 1
male = female = other = 0
for friend in friends[1:]:
sex = friend[&Sex&]
if sex == 1:
elif sex == 2:
female += 1
other += 1
from echarts import Echart, Legend, Pie
chart = Echart('%s的微信好友性别比例' % (friends[0]['Name']), 'from WeChat')
chart.use(Pie('WeChat',
[{'value': male, 'name': '男性 %.2f%%' % (float(male) / total * 100)},
{'value': female, 'name': '女性 %.2f%%' % (float(female) / total * 100)},
{'value': other, 'name': '其他 %.2f%%' % (float(other) / total * 100)}],
radius=[&50%&, &70%&]))
chart.use(Legend([&male&, &female&, &other&]))
del chart.json[&xAxis&]
del chart.json[&yAxis&]
chart.plot()
def word_cloud(friends):
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import PIL.Image as Image
import numpy as np
d = os.path.dirname(__file__)
my_coloring = np.array(Image.open(os.path.join(d, &2.png&)))
signature_list = []
for friend in friends:
signature = friend[&Signature&].strip()
signature = re.sub(&&span.*&&, &&, signature)
signature_list.append(signature)
raw_signature_string = ''.join(signature_list)
text = jieba.cut(raw_signature_string, cut_all=True)
target_signatur_string = ' '.join(text)
my_wordcloud = WordCloud(background_color=&white&, max_words=2000, mask=my_coloring,
max_font_size=40, random_state=42,
font_path=r&C:\Windows\Fonts\simhei.ttf&).generate(target_signatur_string)
image_colors = ImageColorGenerator(my_coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis(&off&)
plt.show()
# 保存图片 并发送到手机
my_wordcloud.to_file(os.path.join(d, &wechat_cloud.png&))
itchat.send_image(&wechat_cloud.png&, 'filehelper')
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
friends = itchat.get_friends(update=True)[:]
# echart_pie(friends)
word_cloud(friends)
运行后的效果是这样的:
windows下的显示效果真不怎么样!
阅读(...) 评论()
作者:刘江
版权所有,出自/feixuelove1009在 SegmentFault,解决技术问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
一线的工程师、著名开源项目的作者们,都在这里:
获取验证码
已有账号?
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
这是我随便拿到的一个微信二维码的图片
http://mp./rr?timestamp=&src=3&ver=1&signature=q6PJ4iwz2XQTjlRFChULUeyL9foFWJYob94G2OuP-Px7I1Ed0FexIhHA9eEQGjmvgcZtl-CGI1jhJeeJp45sHoiIqaEMG6UZ2wMSrn*bCuE=
但是链接格式里面包含时间轴,也就是这个连接会过期....那么目前只有唯一的方法就是把这个图片保存下来了.
现在问题是,类似这样的图片要如何下载呢?好像一般的下载方式不太好下载
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
我抓包看了一下这个 URL 的响应,就是一个普通的响应,实现起来其实很简单的,随手给你写了一个简单的例子,这是你想要的吗?
# -*- coding: UTF-8 -*-
import urllib2
url = 'http://mp./rr?timestamp=&src=3&ver=1&signature=q6PJ4iwz2XQTjlRFChULUeyL9foFWJYob94G2OuP-Px7I1Ed0FexIhHA9eEQGjmvgcZtl-CGI1jhJeeJp45sHoiIqaEMG6UZ2wMSrn*bCuE='
request = urllib2.Request(url)
response = urllib2.urlopen(request)
f = open('test.png', 'wb')
f.write(response.read())
其他的你应该自己会了吧!
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
直接获取内容,然后将其保存到文件。然后你尝试打开这个文件,看看是否正常就好了。
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
正好之前写了一个从微信那边下载图片的一段程序
$url = "http://file.api./....?access_token={$access_token}&media_id={$media_id}";//图片路径
$file_path = ROOT_PATH.'runtime/';//保存路径
$file_name = $file_path.$media_id.'.jpg';//文件名
$hander = curl_init();
$fp = fopen($file_name,'wb');
curl_setopt($hander,CURLOPT_URL,$url);
curl_setopt($hander,CURLOPT_FILE,$fp);
curl_setopt($hander,CURLOPT_HEADER,0);
curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
//curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
curl_setopt($hander,CURLOPT_TIMEOUT,60);
curl_exec($hander);
curl_close($hander);
fclose($fp);
同步到新浪微博
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:python开发微信支付学习记录(转)
时间: 12:49:46
&&&& 阅读:136
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&前言
微信支付是由微信及财付通联合推出的移动支付创新产品。如今,随着微信支付的全面开放,相关需求也越来越多,很多开发人员进行微信支付开发及商家申请微信支付时,面临着诸多疑惑。
要想开发顺利进行,首先要对业务流程有个清晰的认识。这里以微信公众号支付为例,因此也借用微信支付官方文档中的业务流程图:
接下来来关注几个开发过程中的关键点,包括:
&&&&& 1、生成商户订单与调用统一下单 API&
&&&&& 2、微信服务器交互的数据格式
&&&&& 3、公众号支付下网页内通过 JS-API 调起支付
&&&&& 4、异步通知商户支付结果(回调)&
一、生成商户订单与调用统一下单 API
这对应业务流程中的第 4 和 第 5 步,商户后台首先为用户生成订单,然后调用微信的【统一下单】接口向微信支付系统提交订单。这里有一个关键点就是签名的生成。
简单来讲分为以下几个步骤:
&&&&& 1、将所有有效参数以“k=v”的形式进行拼接,有效参数是指非空参数,也就是说如果参数为空,则不参与签名;
&&&&& 2、将所有的“k=v”对用“&”连接,得到“k1=v1&k2=v2&k3=v3”这样的字符串;
&&&&& 3、将微信支付 API 密钥 拼接在最后,如“k1=v1&k2=v2&k3=v3&key=secret”;
&&&&& 4、对整体进行 MD5 运算,即得到签名。
这种签名方法有一个高大上的名字叫做 HMAC(Hash-based Message Authentication Code,基于哈希的消息码)。基于此思路,可以实现如下签名方法:
def gen_sign(params, key):
签名生成函数
:param params: 参数,dict 对象
:param key: API 密钥
:return: sign string
param_list = []
for k in sorted(params.keys()):
v = params.get(k)
# 参数的值为空不参与签名
param_list.append(‘{0}={1}‘.format(k, v))
# 在最后拼接 key
param_list.append(‘key={}‘.format(key))
# 用 & 连接各 k-v 对,然后对字符串进行 MD5 运算
return md5(‘&‘.join(param_list).encode(‘utf8‘)).hexdigest()
参与签名的参数中有一个随机字符串,在 Python 中有很多方法,当然也可以利用&uuid&库来生成:
def gen_nonce_str():
生成随机字符串,有效字符a-zA-Z0-9
:return: 随机字符串
return ‘‘.join(str(uuid.uuid4()).split(‘-‘))
二、微信服务器交互的数据格式
微信服务器与商户服务器之间采用 XML 格式进行交互,这就涉及到与语言原生数据类型进行转换以方便处理。交互的数据参数都是 key-value 的形式,因此在 Python 中使用字典会更加方便。而要解析 XML,也有一大把第三方库供使用,比如&BeautifulSoup。
以下是具体实现:
def trans_xml_to_dict(xml):
将微信支付交互返回的 XML 格式数据转化为 Python Dict 对象
:param xml: 原始 XML 格式数据
:return: dict 对象
soup = BeautifulSoup(xml, features=‘xml‘)
xml = soup.find(‘xml‘)
if not xml:
# 将 XML 数据转化为 Dict
data = dict([(item.name, item.text) for item in xml.find_all()])
return data
def trans_dict_to_xml(data):
将 dict 对象转换成微信支付交互所需的 XML 格式数据
:param data: dict 对象
:return: xml 格式数据
for k in sorted(data.keys()):
v = data.get(k)
if k == ‘detail‘ and not v.startswith(‘&![CDATA[‘):
v = ‘&![CDATA[{}]]&‘.format(v)
xml.append(‘&{key}&{value}&/{key}&‘.format(key=k, value=v))
return ‘&xml&{}&/xml&‘.format(‘‘.join(xml))
注意&detail&参数,即商品详情,其值为 JSON 格式,在转换为 XML 数据时应前注意使用&CDATA&标签将其保护起来。
&detail&&![CDATA[{"goods_detail": [{"wxpay_goods_id": "", "price": 1, "goods_num": 1, "goods_name": "\\u82f9\\u679c", "goods_id": ""}, {"wxpay_goods_id": "", "price": 1, "goods_num": 1, "goods_name": "\\u9999\\u8549", "goods_id": ""}]}]]&&/detail&
三、公众号支付下网页内通过 JS-API 调起支付
这一点对应业务流程中的第 7 步。之所以提及它是因为微信官方文档在此给开发者挖了一个坑(至少截至我在写这篇文章时是的),就是在“网页端调起支付API”中关于 JS 的示例代码是采用的 WeixinJSBridge,这在很早以前就是 Deprecated 的“玩意儿”,如今更是已经不可用了。正确的做法是使用&JS-SDK,可以参考微信公众号的 wiki。
使用 JS-SDK 前需要先调用 config,这里也包含一个签名,但注意这个签名与之前微信支付的签名并不相干。其首先需要用微信公众号的 APPID 和 APPKEY 来换取 access_token,然后用该 access_token 调用 JS-SDK 换取 ticket 的接口得到 ticket,最后再使用该 ticket 和用户当前页面的 URI 通过 sha1 运算生成签名。
在此之后,即可调用&wx.chooseWXPay&来调起支付,这里也有一个坑:timestamp。wx.chooseWXPay 中的参数要求 timestamp 是全小写。而微信支付中签名时要求 timestamp 中的“s”是大写。真的是要傻傻分不清了。&
四、异步通知商户支付结果(回调)
最后是关于异步回调,对应业务流程中的第 10 步。在用户支付操作完成后,微信服务器会通过回调的形式告知商户服务器支付结果。回调的地址与【统一下单】中定义的&notify_url&一致。当接收到回调时,首先应验证签名的有效性以保证“来源可靠”,然后可以通过回调中所带的 openid、out_trade_no 等来定位唯一订单。
微信支付还有很多种形式,在业务流程上也不尽相同。不过只要能玩转其中一种,其他的也基本来说能很快实现。另外,支付功能的实现涉及业务流程中的安全性,因此一定要注意理清业务流程,并卡好各个关键结点。以上就是本文的全部内容,希望对大家使用Python开发微信支付能有所帮助。
转自/Pythonjc/1155053.html标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&国之画&&&& &&&&chrome插件&&
版权所有 京ICP备号-2
迷上了代码!}

我要回帖

更多关于 微信 python 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信