1、accesstoken獲取方法
def get_access_token():url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format('*****************', '***********')response = requests.get(url)res_html = response.json()access_token = res_html['access_token']return access_token
以上方法可以獲取到access_token
上面是2個小時時效的;還可以獲取2天時效的,自己改下url就可以了?
2、獲取圖片的thumb_media_id
這個字段是發布草稿時的必須要填的,所以,要提前獲取到,獲取方法:
def get_media_ids(access_token):url = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={}'.format(access_token)data = {"type":'image',"offset":0,"count":100}response = requests.post(url, json=data)js_data = response.json()medias = re.findall("'media_id': '(.*?)'", str(js_data))media_id = random.choice(medias) #我是隨機抽取的,測試用return media_id
3、注意發包數據格式
必須都是json數據包,其他格式報錯;
4、微信公眾號 調用api接口發草稿箱編碼有問題
發出去的草稿是\u編碼的錯誤,具體代碼如下,可以解決:
?
def push_draft(access_token, title, content, media_id):url = 'https://api.weixin.qq.com/cgi-bin/draft/add?access_token={}'.format(access_token)data = {"articles": [{"title": title,"content": content,"thumb_media_id": media_id,"need_open_comment": 0,"only_fans_can_comment": 0}]
}headers = {'Content-Type': 'application/json'}response = requests.post(url, data=json.dumps(data, ensure_ascii=False).encode('utf-8'), headers=headers)rt_data = response.json()print(rt_data)
通過上面代碼可以解決發出去的編碼是亂碼的問題。?
以上是今天測試遇到的問題,測試還沒有完成,后面會再開一貼進行記錄,有用記得點個贊!