python requests:微信公众号-客服发送消息接口-中文乱码问题

问题描述:访问 客服发送消息接口 中文出现乱码

  1. 实际发送的content:"小助手刷新有问题啦,快去看看吧"
  2. 实际显示的内容:\u5c0f\u52a9\u624b\u5237\u65b0\u6709\u95ee\u9898\u5566\uff0c\u5feb\u53bb\u770b\u770b\u5427


    9635164-127634851c95458e.png
    image.png

解决方法:将json转换为utf-8编码的bytes数据:data=bytes(json.dumps(data, ensure_ascii=False), encoding='utf-8')

代码演示:

#!/usr/bin/python3
# _._ encoding: utf-8 _._

import requests
import json

class WeiXin:

    def __init__(self):
        self.open_id = 输入需要发送的openid
        self.appid = 输入公众号的appid
        self.secret = 输入公众号的secret

    def get_token(self):
        """
        获取微信的access_token
        :return:返回access_token
        """
        url = "https://api.weixin.qq.com/cgi-bin/token"

        params = {"grant_type": "client_credential",
                  "appid": self.appid,
                  "secret": self.secret}

        return requests.get(url=url, params=params).json().get("access_token")

    def post_send(self):
        """
        客服接口-发消息
        :return:
        """
        url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"
        params = {"access_token": self.get_token()}
        header = {"Content-type": "application/json", "charset": "UTF-8"}
        data = {
            "touser": self.open_id,
            "msgtype": "text",
            "text": {
                 "content": "小助手测试失败,请及时查看"
            }}

        r = requests.post(url=url, headers=header, params=params,
                          data=bytes(json.dumps(data, ensure_ascii=False), encoding='utf-8'))

        return r.json()


a = WeiXin()
print(a. post_send())

结果展示:

9635164-5616a54b72415a6c.png
image.png

猜你喜欢

转载自blog.csdn.net/weixin_33966365/article/details/87221994