Skip to content

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

@ace-han

Description

@ace-han

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions