微信内容安全检测接口使用示例
微信内容安全检测接口使用示例
本文介绍如何使用微信公众平台提供的接口进行内容安全检测,并提供一个简单的 Python 代码示例。
接口地址: 'https://api.weixin.qq.com/wxa/msg_sec_check'
代码示例:
@app.route('/wordcheck',methods=['POST'])
def wordcheck():
msg = request.json.get('msg')
openid = request.json.get('openid')
try:
stau = infocheck(msg,openid)
if stau:
return jsonify({'code':1})
else:
return jsonify({'code': 0, 'msg': 'err'})
except:
return jsonify({'code':0,'msg':'err'})
# 微信内容安全检测
def infocheck(text,openid):
try:
acctoken = Adj.query.filter(Adj.id == 2).first().adjinfo
checkurl = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={ACCESS_TOKEN}".format(
ACCESS_TOKEN=acctoken)
data = '{"content": "' + text + '","openid": "' + openid + '","scene": 2 ,"version": 2 }'
headers = {'Content-Type': 'application/json'}
print(data,type(data))
res = requests.post(checkurl, data=data.encode('utf-8'), headers=headers)
lev = res.json().get("result").get("label")
sug = res.json().get("result").get("suggest")
print(res.json())
print(lev,sug)
return True if lev == 100 and sug == 'pass' else False
except Exception as e:
getacctoken()
print('重新获取')
return jsonify('内容包含敏感文字,请重新编辑发送')
def getacctoken():
print('getroken')
access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential' \
'&appid={appid}&secret={secret}'.format(appid=APPID, secret=SECRET)
access_token_res = requests.get(access_token_url).json()['access_token']
atok = Adj.query.filter(Adj.id == 2).first()
if atok:
atok.adjinfo = access_token_res
else:
atok = Adj(id = 2,adjinfo=access_token_res)
db.session.add(atok)
db.session.commit()
return access_token_res
if access_token_res.json().get('errcode'):
raise 'AccessToken()'
@app.route('/test',methods=['POST'])
def test():
a = infocheck(text,openid)
return a
说明:
- 该代码示例使用 Python 语言编写,需要安装
requests库。 infocheck()函数用于调用微信内容安全检测接口。getacctoken()函数用于获取 access_token。- 具体的实现细节请参考微信公众平台的 API 文档。
注意事项:
- 为了确保安全,请不要将 access_token 硬编码到代码中,建议使用环境变量或配置中心来管理。
- 为了避免频繁调用接口,建议将 access_token 缓存起来,并设置过期时间。
总结:
本文介绍了如何使用微信公众平台提供的接口进行内容安全检测,并提供了一个简单的 Python 代码示例。希望本文能帮助你更好地理解和使用微信内容安全检测功能。
原文地址: https://www.cveoy.top/t/topic/lYFe 著作权归作者所有。请勿转载和采集!