1.遇到的坑
{"errcode":40001,"errmsg":"invalid credential, hint: [1507881186_cb1093c9bcaedaf108b7ce2ea10f2d38]"} 40001 不合法的secret參數 secret在應用詳情/通訊錄管理助手可查看 排查secret的取值也沒有錯啊。就郁悶了。 最后發現問題:是corpid寫錯了。把企業id寫成了應用id。 因為“全局錯誤碼”里沒有提到corpid錯誤了會造成40001錯誤,所以一直以為是scerent的錯。 參考:https://www.cnblogs.com/luoahong/articles/9018223.html
2.實用Python腳本
[root@cm ~]# cat test_jj.py #!python3 # -*- coding: utf-8 -*- import json import requests class WeChat(object): def __init__(self, corpid, secret, agentid): self.url = "https://qyapi.weixin.qq.com" self.corpid = corpid self.secret = secret self.agentid = agentid # 獲取企業微信的 access_token def access_token(self): url_arg = '/cgi-bin/gettoken?corpid={id}&corpsecret={crt}'.format( id=self.corpid, crt=self.secret) url = self.url + url_arg response = requests.get(url=url) print('i am here') text = response.text print(text) self.token = json.loads(text)['access_token'] # 構建消息格式 def messages(self, msg): values = { "touser": '@all', "msgtype": 'text', "agentid": self.agentid, "text": {'content': msg}, "safe": 0 } # python 3 # self.msg = (bytes(json.dumps(values), 'utf-8')) # python 2 self.msg = json.dumps(values) # 發送信息 def send_message(self, msg): self.access_token() self.messages(msg) send_url = '{url}/cgi-bin/message/send?access_token={token}'.format( url=self.url, token=self.token) response = requests.post(url=send_url, data=self.msg) errcode = json.loads(response.text)['errcode'] if errcode == 0: print('Succesfully') else: print('Failed') #使用示例: corpid = "wwdbe2bhaha48965a3012" secret = "-rLV8ahtMIcYlRZMhahaik7y5ikASozwjjppx8ZPaBXyk" agentid = '10200237' msg = "supply high quolity and low price product......" wechat = WeChat(corpid, secret, agentid) wechat.access_token() wechat.send_message(msg)