微信公众号开发遇到的一些坑

微信公众号开发遇到的一些坑,这里记录一下

前言

最近做了微信公众号的一些简单的开发,我是用flask+flask-Restful开发的,这里记录一下踩的坑。

坑1——flask-Restful中文返回是unicode问题

在代码中配置如下就好了

1
2
app.config['JSON_AS_ASCII'] = False
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))

坑2——被动回复用户消息,回复文本消息中使用了\n换行符不解析

这里需要我们返回一个response对象,而不是普通的字符串。因为我是用flask-restful开发的,使用make_response就好了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# -*- coding: utf-8 -*-
# filename: reply.py

import time
from flask import make_response


class Msg(object):
def __init__(self):
pass

def send(self):
return "success"

# 文本消息回复
class TextMsg(Msg):
def __init__(self, toUserName, fromUserName, content):
self.__dict = dict()
self.__dict['ToUserName'] = toUserName
self.__dict['FromUserName'] = fromUserName
self.__dict['CreateTime'] = int(time.time())
self.__dict['Content'] = content

def send(self):
xmlform = """
<xml>
<ToUserName><![CDATA[{ToUserName}]]></ToUserName>
<FromUserName><![CDATA[{FromUserName}]]></FromUserName>
<CreateTime>{CreateTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{Content}]]></Content>
</xml>
"""
return make_response(xmlform.format(**self.__dict))

坑3—— 被动回复用户消息,回复图文消息

这里已经写好了,直接复制用就好了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# -*- coding: utf-8 -*-
# filename: reply.py

import time
from flask import make_response


class Msg(object):
def __init__(self):
pass

def send(self):
return "success"

# 图文消息回复
class News(Msg):
def __init__(self, toUserName, fromUserName,sourceList):
self.toUserName = toUserName
self.fromUserName = fromUserName
self.CreateTime = int(time.time())
self.ArticleCount = len(sourceList)
self.SourceList = sourceList

def send(self):
self.itemxml = []
for source in self.SourceList:
# source = [title1, description1, picurl, url]
singlexml = """
<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
""" % (source[0], source[1], source[2], source[3])
self.itemxml.append(singlexml)

xmlform = """
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%d</ArticleCount>
<Articles>
%s
</Articles>
</xml>
""" % (self.toUserName, self.fromUserName, self.CreateTime, self.ArticleCount, " ".join(self.itemxml))
return make_response(xmlform)

Reference

  1. flask-restful 中文返回的响应变成了 unicode literal

  2. 微信公众号开发被动回复用户消息,回复内容Content使用了”\n”换行符还是没有换行

  3. 用python开发微信图文消息回复系统——新闻检索系统

本文标题:微信公众号开发遇到的一些坑

文章作者:xianyu123

发布时间:2021年02月15日 - 23:45

最后更新:2021年02月18日 - 20:19

原始链接:http://0clickjacking0.github.io/2021/02/15/微信公众号开发遇到的一些坑/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------    本文结束  感谢您的阅读    -------------