Giter Site home page Giter Site logo

gusibi / python-weixin Goto Github PK

View Code? Open in Web Editor NEW
831.0 41.0 271.0 151 KB

微信(weixin|wechat) Python SDK 支持开放平台和公众平台 支持微信小程序云开发

Home Page: https://github.com/gusibi/python-weixin/wiki/快速开始

License: Other

Python 100.00%
weixin python python-weixin wechat-sdk wechat weixin-sdk wxapp wechat-app wxcloud

python-weixin's Introduction

python-weixin

Build Status

A Python client for the Weixin REST APIs

Compatibility

component compatibility
Python 2.*, 3.*

Installation

pip install python-weixin

Requires

* requests
* simplejson
* six
* xmltodict
* pycryptodome

微信小程序使用示例:

微信小程序登录文档

微信小程序登录获取用户信息

Python 实现小程序登录注册

from weixin import WXAPPAPI
from weixin.lib.wxcrypt import WXBizDataCrypt

api = WXAPPAPI(appid=APP_ID,
                  app_secret=APP_SECRET)
session_info = api.exchange_code_for_session_key(code=code)

# 获取session_info 后

session_key = session_info.get('session_key')
crypt = WXBizDataCrypt(WXAPP_APPID, session_key)

# encrypted_data 包括敏感数据在内的完整用户信息的加密数据
# iv 加密算法的初始向量
# 这两个参数需要js获取
user_info = crypt.decrypt(encrypted_data, iv)

Authentication

Weixin API 使用 OAuth2 认证方式 详情见: https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&lang=zh_CN

Authenticating a user

具体使用方法参考 sample app

Using an access token

获取到access token 后,可以使用token 获取 用户信息等:

微信开放平台使用示例:

from weixin.client import WeixinAPI

scope = ("snsapi_login", )
api = WeixinAPI(appid=APP_ID,
                app_secret=APP_SECRET,
                redirect_uri=REDIRECT_URI)
authorize_url = api.get_authorize_url(scope=scope)

access_token = api.exchange_code_for_access_token(code=code)

api = WeixinAPI(access_token=access_token)

user = api.user(openid="openid")

微信公众平台使用示例:

from weixin.client import WeixinMpAPI

scope = ("snsapi_base", )
api = WeixinMpAPI(appid=APP_ID,
                  app_secret=APP_SECRET,
                  redirect_uri=REDIRECT_URI)
authorize_url = api.get_authorize_url(scope=scope)

access_token = api.exchange_code_for_access_token(code=code)

api = WeixinMpAPI(access_token=access_token)

user = api.user(openid="openid")

微信支付使用示例:

from weixin.pay import WeixinPay

wxpay = WeixinPay(appid='appid',
                  mch_id='mchid',
                  notify_url='url',
                  partner_key='key')
                  create_pay_info= {}

# 统一下单
wxpay.unifiedorder(**create_pay_info)
# 查询订单
wxapp.order_query(out_trade_no='out_trade_no')

# 企业付款
wxepay = WeixinEnterprisePay(appid='appid',
                             mch_id='mchid',
                             mch_key='mch_key',
                             mch_cert='mch_cert',
                             partner_key='key')

wxepay.transfers(partner_trade_no,
                 openid,
                 amount,
                 desc=u'结算')

# 企业付款查询
wxepay_query = WeixinEnterprisePayQuery(appid='appid',
                                        mch_id='mchid',
                                        mch_key='mch_key',
                                        mch_cert='mch_cert',
                                        partner_key='key')
wxepay_query.gettransferinfo(partner_trade_no)

创建自定义菜单

支持的按钮类型

  1. click:点击推事件用户点击click类型按钮后,微信服务器会通过消息接口推送消息类型为event的结构给开发者(参考消息接口指南),并且带上按钮中开发者填写的key值,开发者可以通过自定义的key值与用户进行交互;
  2. view:跳转URL用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的网页URL,可与网页授权获取用户基本信息接口结合,获得用户基本信息。
  3. scancode_push:扫码推事件用户点击按钮后,微信客户端将调起扫一扫工具,完成扫码操作后显示扫描结果(如果是URL,将进入URL),且会将扫码的结果传给开发者,开发者可以下发消息。
  4. scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框用户点击按钮后,微信客户端将调起扫一扫工具,完成扫码操作后,将扫码的结果传给开发者,同时收起扫一扫工具,然后弹出“消息接收中”提示框,随后可能会收到开发者下发的消息。
  5. pic_sysphoto:弹出系统拍照发图用户点击按钮后,微信客户端将调起系统相机,完成拍照操作后,会将拍摄的相片发送给开发者,并推送事件给开发者,同时收起系统相机,随后可能会收到开发者下发的消息。
  6. pic_photo_or_album:弹出拍照或者相册发图用户点击按钮后,微信客户端将弹出选择器供用户选择“拍照”或者“从手机相册选择”。用户选择后即走其他两种流程。
  7. pic_weixin:弹出微信相册发图器用户点击按钮后,微信客户端将调起微信相册,完成选择操作后,将选择的相片发送给开发者的服务器,并推送事件给开发者,同时收起相册,随后可能会收到开发者下发的消息。
  8. location_select:弹出地理位置选择器用户点击按钮后,微信客户端将调起地理位置选择工具,完成选择操作后,将选择的地理位置发送给开发者的服务器,同时收起位置选择工具,随后可能会收到开发者下发的消息。
  9. media_id:下发消息(除文本消息)用户点击media_id类型按钮后,微信服务器会将开发者填写的永久素材id对应的素材下发给用户,永久素材类型可以是图片、音频、视频、图文消息。请注意:永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id。
  10. view_limited:跳转图文消息URL用户点击view_limited类型按钮后,微信客户端将打开开发者在按钮中填写的永久素材id对应的图文消息URL,永久素材类型只支持图文消息。请注意:永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id。

自定义菜单参数说明

参数 是否必须 说明
button 一级菜单数组,个数应为1~3个
sub_button 二级菜单数组,个数应为1~5个
type 菜单的响应动作类型
name 菜单标题,不超过16个字节,子菜单不超过40个字节
key click等点击类型必须 菜单KEY值,用于消息接口推送,不超过128字节
url view类型必须 网页链接,用户点击菜单可打开链接,不超过1024字节
media_id media_id类型和view_limited类型必须 调用新增永久素材接口返回的合法media_id

消息管理

被动回复

被动回复是在用户发出请求后在respone 中包含的内容

消息体见官方参考文档: 被动回复用户消息

客服消息

API 列表

  • add_customservice 添加客服帐号
  • update_customservice 修改客服帐号
  • delete_customservice 删除客服帐号
  • getall_customservice 获取所有客服帐号
  • custom_message_send 发送客服消息

消息体见官方参考文档: 客服消息

模板消息

API 列表

  • template_message_send

消息体见官方参考文档: 模板消息

有问题可以在公号讨论

关注公号

感谢

jetbrains

python-weixin's People

Contributors

gojuukaze avatar gusibi avatar oidiotlin avatar xddotcom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-weixin's Issues

请教如何传中文参数

`result = wxpay.unifiedorder(trade_type='JSAPI', total_fee=order.total_fee, spbill_create_ip=settings.ServerIp, openid=user.openid, body='积分充值', out_trade_no=shortuuid.uuid())

`
报错如下:

Exception Value: 'latin-1' codec can't encode characters in position 362-365: Body ('积分充值') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.

weixin小程序登陆

1.OAuth2API里面没有找到获取openid的方法,openid难道是要反向解密user_info才有吗,但我看小程序开发者文档openid跟session_key是可以用code换取得,access_token反倒没提
2.另外,消息模板没有封装回复消息方法吗,需自己调微信相关接口?

Scope 参数错误或没有 Scope 权限

使用的版本是最新的。
代码:
api = WeixinAPI(appid=APP_ID,
app_secret=APP_SECRET,
redirect_uri=REDIRECT_URI)
redirect_uri = api.get_authorize_login_url(scope=("snsapi_login"), state='login_pc')
我通过检查源码发现在oauth2.py文件中第118行把scope用join方法以空格加入导致回调地址变成
scope=s+n+s+a+p+i+_+l+o+g+i+n
删掉源码的空格方法就好了。
我想知道,为什么要这样做呢。。

请写个目录吧

求写一个功能目录,方便我们查看,现在只写了登录和支付两个功能,实际肯定不止啊;写个功能目录也方便看,现在这样一个个看,我自己写的时间也差不多了

Python3.x 'dict_keys' object has no attribute 'sort'

# weixin/pay.py
def params_filter(params, delimiter='&', charset='utf-8',
                  excludes=['sign', 'sign_type']):
    ks = params.keys()
    ks.sort()
   # ...

# weixin/helper.py
def genarate_js_signature(params):
    keys = params.keys()
    keys.sort()

change

ks = params.keys()
ks.sort()

to

ks = sorted(params.keys())

will be fine

unionId无法获取到

你好,最近的使用中,发现 “Python 实现小程序登录注册” 这一功能,通过iv,code 登录后解密的用户信息中没有 unionid,这是微信返回数据做了限制还是代码修改的问题呢

TypeError: can't concat bytearray to str

File "/usr/local/lib/python3.5/dist-packages/weixin/helper.py", line 297, in url_quote
safe = frozenset(bytearray(safe) + _always_safe) - frozenset(bytearray(unsafe))
TypeError: can't concat bytearray to str

数据解密报错

'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte

UnicodeEncodeError: 'latin-1' codec can't encode characters in position

I'm using python 3.6.x

in weixin.pay.py, when Chinese chars in params like below

{'body': '中文中文中文', 'total_fee': 1, 'out_trade_no': '20180820164216MQE0TD', 'openid': 'xxxxxx', 'fee_type': 'CNY', 'spbill_create_ip': '1.1.1.1', 'notify_url': 'https://xxx.com/callback', 'trade_type': 'JSAPI', 'device_info': '', 'detail': {'cost_price': 1, 'receipt_id': 'xxxxMQE0TD', 'goods_detail': [{'goods_id': '254', 'quantity': 1, 'price': 1}]}, 'attach': '', 'time_start': '20180821004221', 'time_expire': '20180821024221', 'goods_tag': '', 'product_id': '', 'limit_pay': 'no_credit'}

will throw above error before sending the request to WX server

Fix the problem as belows

  • from weixin.helper import smart_bytes
  • replace smart_str to smart_bytes

kwargs['data'] = smart_str(xmltodict.unparse(xml_dict))
to
kwargs['data'] = smart_bytes(xmltodict.unparse(xml_dict))

detail like below

# add this import
from weixin.helper import smart_bytes

class WeixinPay(object):

# ...
    def prepare_request(self, method, path, params):
        kwargs = {}
        _params = self.get_base_params()
        params.update(_params)
        newparams, prestr = params_filter(params)
        sign = build_mysign(prestr, self.partner_key)
        # 将内容转化为unicode xmltodict 只支持unicode
        newparams = params_encoding(newparams)
        newparams['sign'] = sign
        xml_dict = {'xml': newparams}

        # comment this line to `smart_bytes`
        #kwargs['data'] = smart_str(xmltodict.unparse(xml_dict))
        kwargs['data'] = smart_bytes(xmltodict.unparse(xml_dict))

        url = self._full_url(path)
        if self.mch_cert and self.mch_key:
            kwargs['cert'] = (self.mch_cert, self.mch_key)
        return method, url, kwargs

upgrade requirements.txt

upgrade all versions in requirements.txt to the latest

avoid any risk in pipenv conflicts
remove version number for requests, chardet

simplejson
requests==2.4.1
chardet==2.3.0
six
lxml
xmltodict
pycrypto

to

...
requests
chardet
...

error msg

image

pip安装报错“段错误 (核心已转储)”,以及python3的"TypeError: can't concat str to bytearray"

pip提示信息:
Installing collected packages: pycrypto, simplejson, six, certifi, idna, chardet, urllib3, requests, xmltodict, python-weixin
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 pycrypto-2.6.1 python-weixin-0.4.5 requests-2.21.0 simplejson-3.16.0 six-1.12.0 urllib3-1.24.1 xmltodict-0.11.0
段错误 (核心已转储)

环境:
系统:ubuntu18.04
Python:3.6.7

python3.5.5遇到的问题及修改

1)
File "/usr/local/lib/python3.5/site-packages/weixin/pay.py", line 16, in
from weixin.helper import smart_str, smart_unicode, md5_constructor as md5
ImportError: cannot import name 'smart_unicode'
修改
smart_unicode->smart_text

2)
File "/usr/local/lib/python3.5/site-packages/weixin/pay.py", line 42, in params_filter
ks.sort()
AttributeError: 'dict_keys' object has no attribute 'sort'
修改
ks.sort() --> ks = sorted(ks)

3)
File "/usr/local/lib/python3.5/site-packages/weixin/pay.py", line 61, in build_mysign
return md5(prestr).hexdigest().upper()
TypeError: Unicode-objects must be encoded before hashing

修改
return md5(prestr).hexdigest().upper() --> md5(prestr.encode(encoding='utf-8')).hexdigest().upper()

4)
File "/usr/local/lib/python3.5/site-packages/weixin/pay.py", line 34, in params_encoding
newparams[k] = smart_unicode(v)
NameError: name 'smart_unicode' is not defined
修改
newparams[k] = smart_unicode(v) --> newparams[k] = smart_text(v)

startswith first arg must be bytes or a tuple of bytes, not str

支付调用统一支付接口的时候,我基本上只填了最基本的信息 ,不知道哪里出的问题。

File "/Users/ ** /lib/python3.6/site-packages/weixin/pay.py", line 464, in unifiedorder
method, url, kwargs = self.prepare_request('POST', path, params)
File "/Users/ ** /lib/python3.6/site-packages/weixin/pay.py", line 115, in prepare_request
kwargs['data'] = smart_bytes(xmltodict.unparse(xml_dict))
File "/Users/ ** /lib/python3.6/site-packages/xmltodict.py", line 449, in unparse
**kwargs)
File "/Users/ ** /lib/python3.6/site-packages/xmltodict.py", line 386, in _emit
if ik.startswith(attr_prefix):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str

阿里云服务器中python-wexin失效?

我在本地服务器可以拿到用户的openid,
但部署到阿里云服务器后死活取不到啊,状态码是500.
我尝试用requests访问外部链接是成功的,说明服务器配置没问题啊。

python3.x 不支持,字符连接报错

(Pdb) n

/Users/yxy/.local/share/virtualenvs/dash-1Aup7SaT/lib/python3.6/site-packages/weixin/helper.py(323)_url_encode_impl()
-> yield url_quote_plus(key) + '=' + url_quote_plus(value)
(Pdb) n
TypeError: can't concat str to bytearray
/Users/yxy/.local/share/virtualenvs/dash-1Aup7SaT/lib/python3.6/site-packages/weixin/helper.py(323)_url_encode_impl()
-> yield url_quote_plus(key) + '=' + url_quote_plus(value)
(Pdb) p key, value
(b'appid', b'wx2*******325cfb67f')

照文档写的样例子跑不通, 调试看了下,字符链接出现了问题, 传递给 WeixinMpAPI 的所有参数都是 默认的 string 类型。

repository details url error

The url should be https://github.com/gusibi/python-weixin/wiki#快速开始 instead https://github.com/gusibi/python-weixin/wiki/快速开始

python3.5+smart_unicode

File "/usr/local/lib/python3.5/site-packages/weixin/pay.py", line 16, in
from weixin.helper import smart_str, smart_unicode, md5_constructor as md5
ImportError: cannot import name 'smart_unicode'

smart_unicode->smart_text

解密时概率发生错误

对encryptedData解码概率发生错误:

Traceback (most recent call last):
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/ken/Developer/projects/2018/littledrothy/account/views.py", line 43, in post
    crypted_user_info = crypt.decrypt(encrypted_data, iv)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/weixin/lib/wxcrypt.py", line 32, in decrypt
    decrypted = json.loads(self._unpad(cipher.decrypt(encrypted_data)))
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/simplejson/__init__.py", line 518, in loads
    return _default_decoder.decode(s)
  File "/Users/ken/.pyenv/versions/venvdjango/lib/python3.6/site-packages/simplejson/decoder.py", line 369, in decode
    s = s.decode(self.encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 0: invalid continuation byte

encryptedData:

U0ETwC6fwCvShS/y0xS97WBsut9AR2Ez5hkSLkr49YJHRAO/4byPpMGuFx0tPfJ9ar1bBoh+BORTxTPdZOVSWH467srw6zxHmTZC0XJcH4ZQEaVWZdodItcQdG1PvCSu6eD29K1nmCvs2pLNaV1ELSd1qBEP+7vTrxzMVzS+oN3l5WvZIUr+RoHicIXR9aV3Ck+eRFdYC3ApEaPcHqlgR6UY8F8WzkwFEVK3ruSK5oCj54ybJLwT7K0qQq0LwqxcIxi0rkinjIpYRv+3aWK5gxQv3gnWFqkJ7A9DZPZObieatobMKUrpDrk3gsI5+adRVzE8ZydmdC4df1Lms5VTD1w7moJtLV6mADCPAe/AH/WVnFwSgTqipkVJwirdsblYGojELCpZyqfmliLqzPfl7C/OOAVbYYvz70paTrXSFVJcgNge7UxT7/5U3Z6TwtMI1DQVsRgyHl62QT4ZUOzC0UQxmgYS5Dy+SX7GBL/8Tqw=

iv

N96nLnUOTyTlOfQtBGojaA==

我用的是post的方法直接用json格式发送过来的,应该不存在urlencode的问题,请问可能会是什么原因?

python版本: python3.6

谢谢

如何插入动态数据

cloud_api.db_add()指令中,data数据是写死的,如何传递动态数据[](url)
resp = cloud_api.db_add( json_body={"env": env, "query": 'db.collection("example").add({data: [{age: 12}]})'} )
如何修改data数据

Potential dependency conflicts between python-weixin and chardet

Hi, as shown in the following full dependency graph of python-weixin, python-weixin requires chardet (the latest version), while the installed version of requests(2.22.0) requires chardet>=3.0.2,<3.1.0.

According to Pip's “first found wins” installation strategy, chardet 3.0.4 is the actually installed version.

Although the first found package version chardet 3.0.4 just satisfies the later dependency constraint (chardet>=3.0.2,<3.1.0), it will lead to a build failure once developers release a newer version of chardet in the near future, which is greater than 3.1.0.

Dependency tree--------

python-weixin(version range:)
| +-simplejson(version range:)
| +-requests(version range:)
| | +-chardet(version range:>=3.0.2,<3.1.0)
| | +-idna(version range:>=2.5,<2.9)
| | +-urllib3(version range:>=1.21.1,<1.26)
| | +-certifi(version range:>=2017.4.17)
| +-chardet(version range:)
| +-six(version range:)
| +-xmltodict(version range:)
| +-pycryptodome(version range:)```

Thanks for your attention.
Best,
Neolith

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 3: invalid start byte

Python 版本:Python 3.6

    user_info = crypt.decrypt(encrypted_data, iv)
  File "/usr/local/lib/python3.6/site-packages/weixin/lib/wxcrypt.py", line 32, in decrypt
    decrypted = json.loads(self._unpad(cipher.decrypt(encrypted_data)))
  File "/usr/local/lib/python3.6/site-packages/simplejson/__init__.py", line 518, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.6/site-packages/simplejson/decoder.py", line 369, in decode
    s = str(s, self.encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 3: invalid start byte

小程序获取到的加密串的信息

{"encryptedData":"zqLRlz5pRd2mi5c4YgWnen7YyiY87iMfCup6/HX/m6JVxuKw/y5knNKdJnI51jxj5gskU+XJKjqSATifeHrr1+poCWmHYdEnWGjR+yC8e9ltMM4VXLz1B6/g7BcGeMByoKHOytSGOulGfKn8vY2bKzxo1ZydoTndKy9qHlfvLC+L6QlPU/DwtkpguzSaBcbVta/q619bACmdzPoa9Xr8c/soCXNidsbjUMvjr5BpnG8Nhl+QR0mDQCTdrk6hNv6mwBKPm62R51Wx2U7mmqyOdycVBf986GUSY3erYwEa3GIQgr2EstzftKkLIm/q5Z/SHSt15aFk/V1jifME/BBA390Vd3O0AwYjk8ATvlkiX6+/JbDFRSCqD7md5HSSKwcPuwvUOav1qRS8Gv/BAoCda+nLrhcW3/Bfb9gZ8HoVMW2Mjb+LUlQIg5JZeSV+LEioM8jniAlVybzE0/a7bhfHog==","iv":"RHkIka4HBxvByJ8tQ1tNpg=="}

python3 pay模块 无法载入smart_unicode

表现

  • python3.6 from weixin.pay import WXAppPay

ImportError: cannot import name 'smart_unicode'

仔细看了一下 这个smart_unicode是向py2做的兼容 但是在一个函数中又有引用 哥们 能帮忙更新一下判断py3别载入这个东东么!

python3不兼容

调用统一支付接口的时候报错,按以下改动后可以正常运行了

\weixin\pay.py", line 41, in params_filter
ks.sort()
AttributeError: 'dict_keys' object has no attribute 'sort'

以下代码
ks = params.keys()
ks.sort()
改为
if six.PY3:
ks = sorted(params)
else:
ks = params.keys()
ks.sort()

\weixin\pay.py", line 65, in build_mysign
return md5(prestr).hexdigest().upper()
TypeError: Unicode-objects must be encoded before hashing

以下代码
prestr += '&key=%s' % str(key)
return md5(prestr).hexdigest().upper()
改为
prestr += '&key=%s' % str(key)
if six.PY3:
prestr = prestr.encode("utf8")
return md5(prestr).hexdigest().upper()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.