需要去申请一个企业微信,然后新建一个应用,记住图中红色区域的字符串,代码里要用到
微信企业号官网:https://work.weixin.qq.com/wework_admin/loginpage_wx?from=myhome_qyh_redirect&ref_from=myhome_baidu
python代码如下:******用自己应用的secret代替
#!/usr/bin/python
# coding: utf-8
import urllib, urllib2
import json
import sys
import os
import time
import datetime
def get_unixtime_now():
dtime = datetime.datetime.now()
unix_time = time.mktime(dtime.timetuple())
return unix_time
def gettoken_from_qq(corpid, corpsecret, pid):
gettoken_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret
print gettoken_url
try:
token_file = urllib2.urlopen(gettoken_url)
except urllib2.HTTPError as e:
print e.code
print e.read().decode("utf8")
sys.exit()
token_data = token_file.read().decode("utf-8")
filepath = "./%s_%s" % (corpid, corpsecret)
print filepath
token_json = json.loads(token_data)
token_json.keys()
token = token_json["access_token"]
expires_in = token_json["expires_in"]
errcode = token_json["errcode"]
errmsg = token_json["errmsg"]
token_file = open(filepath, "wb")
expires_time = expires_in + get_unixtime_now() - 200
try:
qqstr = "{\"QQ\":"
token_file.write(qqstr)
token_file.write(token_data)
spdbstr = ",\"SPDB\":{\"expires_time\":\"%.0f\"}}" % (expires_time)
token_file.write(spdbstr)
finally:
token_file.close()
return (token, expires_in, errcode, errmsg)
def gettoken_from_file(corpid, corpsecret, pid):
filepath = "./%s_%s" % (corpid, corpsecret)
print filepath
if not os.path.exists(filepath):
return ("", 0, "except error", "except error", 0)
token_file = open(filepath, "rb")
try:
token_data = token_file.read();
token_json = json.loads(token_data)
token_json.keys()
token = token_json["QQ"]["access_token"]
expires_in = token_json["QQ"]["expires_in"]
errcode = token_json["QQ"]["errcode"]
errmsg = token_json["QQ"]["errmsg"]
expires_time = token_json["SPDB"]["expires_time"]
except:
return ("", 0, "except error", "except error", 0)
finally:
token_file.close()
return (token, expires_in, errcode, errmsg, expires_time)
def senddata(access_token, user, content, appid, pid):
send_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
send_values = {
"touser": user,
"toparty": "1",
"msgtype": "text",
"agentid": appid,
"text": {
"content": content
},
"safe": "0"
}
now = datetime.datetime.now()
dt = now.strftime("%Y%m%d %H:%M:%S.") + now.strftime('%f')[:3]
print "P=%08d %s SENDVALUE=(%s)" % (pid, dt, send_values)
send_data = json.dumps(send_values, ensure_ascii=False)
send_request = urllib2.Request(send_url, send_data)
response = json.loads(urllib2.urlopen(send_request).read())
response.keys()
errcode = response["errcode"]
errmsg = response["errmsg"]
now = datetime.datetime.now()
dt = now.strftime("%Y%m%d %H:%M:%S.") + now.strftime('%f')[:3]
print "P=%08d %s RESPONSE=(%s)" % (pid, dt, str(response))
return (errcode, errmsg);
if __name__ == "__main__":
reload(sys)
content = u"你好test"
appid=1000002
user="@all"
corpid = "******"
corpsecret = "*****************************"
pid = 1234 #anyway
expires_time = 0
sys.setdefaultencoding('utf-8')
(accesstoken, expires_in, errcode, errmsg, expires_time) = gettoken_from_file(corpid, corpsecret, pid)
if accesstoken == "":
print "accesstoken gettoken_form_file is null!!"
print "Get new token from QQ,because token is nul"
(accesstoken, expires_in, errcode, errmsg) = gettoken_from_qq(corpid, corpsecret, pid)
else:
unix_time = int(get_unixtime_now())
vi_expires_time = int(expires_time)
print "unix_time=%ld diff expires_time=%ld" % (unix_time, vi_expires_time)
if unix_time > vi_expires_time:
print "accesstoken expiretims differ: now=%ld > last expirestime =%ld" % (unix_time, vi_expires_time)
print "Get new token from QQ,because expire time"
(accesstoken, expires_in, errcode, errmsg) = gettoken_from_qq(corpid, corpsecret, pid)
else:
print "Get token from file "
print "accesstoken=%s" % (accesstoken)
print "expires_in=%s" % (expires_in)
print "errcode=%s" % (errcode)
print "errmsg=%s" % (errmsg)
print "expires_time=%s" % (expires_time)
print "unixtime=%.0f" % (get_unixtime_now())
(errcode, errmsg) = senddata(accesstoken, user, content, appid, pid)
print "RESPONSE errcode=%s" % (errcode)
print "RESPONSE errmsg=%s" % (errmsg)
# errcode = 40001
# 40001 invalid credential, access_token is invalid or not latest
# 42001 access_token expired
if errcode == 42001 or errcode == 40001:
print "Get new token from QQ,because 42001 or 40001"
(accesstoken, expires_in, errcode, errmsg) = gettoken_from_qq(corpid, corpsecret, pid)
(errcode, errmsg) = senddata(accesstoken, user, content, appid, pid)
print "RESPONSE errcode=%s" % (errcode)
print "RESPONSE errmsg=%s" % (errmsg)
来源:CSDN
作者:OoXiaoLiuoO
链接:https://blog.csdn.net/qqDai1/article/details/78899125