#_*_coding:utf-8_*_
import requests
import json
import MySQLdb
def get_access_token():
"""
获取微信全局接口的凭证(默认有效期俩个小时)
如果不每天请求次数过多, 通过设置缓存即可
"""
result = requests.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": "xxxxxxxxx", # 微信公众号appid
"secret": "xxxxxxxx", # 微信公众号secret
}
).json()
print(result)
if result.get("access_token"):
access_token = result.get("access_token")
else:
access_token = None
return access_token
def sendmsg(openid,msg):
access_token = get_access_token()
body = {
"touser": openid,
"msgtype": "text",
"text": {
"content": msg
}
}
response = requests.post(
url="https://api.weixin.qq.com/cgi-bin/message/custom/send",
params={
"access_token": access_token
},
data=bytes(json.dumps(body, ensure_ascii=False), encoding="utf-8")
)
# 这里可根据回执code进行判定是否发送成功(也可以根据code根据错误信息)
result = response.json()
print(result)
path = r"C:\\Users\\Administrator\\Desktop\\weixingong\\user\\%s.txt" % (openid)
print(result["errcode"])
try:
db = MySQLdb.connect(host="192.168.1.4", user="root", db="public_opinion", port=3306, passwd="123456",
charset="utf8")
except Exception as e:
print(e, "数据库连接错误")
if result["errcode"] == 0:
with open(path, "a+") as f:
f.write("1")
f.close()
cursor = db.cursor()
# 使用execute方法执行SQL语句
sql = "update weixin_user set state = '%s' where userid = '%s'" % (str(result["errcode"]),openid)
print(sql)
cursor.execute(sql)
# 提交sql事五
db.commit()
# 关闭本次操作
cursor.close()
else:
cursor = db.cursor()
# 使用execute方法执行SQL语句
sql = "update weixin_user set state = '%s' where userid = '%s'" % (str(result["errcode"]),openid)
print(sql)
cursor.execute(sql)
# 提交sql事五
db.commit()
# 关闭本次操作
cursor.close()
if __name__ == "__main__":
sendmsg("ofDDs0SP9rsDT_pupCsSSgagVVu8","你好?")
# 参数1,要发送的用户tofakeid 微信公众号点击用户头像url连接中有
# 参数2,要发送的内容