• 配置IP 白名單

    在公眾號后臺的「設置與開發」-「基本配置」,“IP白名單”設置即可,把你的ip(執行api調用的機器ip)添加進去。沒有添加,發起請求會 “errcode: 40164,errmsg: invalid ip”。

  • 接口封裝發布文章

    接口封裝發布文章一共就四步:獲取token、上傳封面、保持草稿、發布。

    1 獲取token

    幾乎所有的接口都用token做身份認證的,接口功能調用的第一步。

    參考文檔:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

    image

    調用接口為:

    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={yourappid}&secret={yoursecret}

    用postman來做請求測試:

    image

    代碼:(去除了日志信息,下同)

    image

    2 新增一個永久素材

    主要是后面的操作,需要一個圖片作為封面,所以需要提前上傳一個圖片資源,對應的接口就是“新增永久素材”了

    參考文檔:https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Permanent_Assets.html

    image

    調用接口:

    https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image

    代碼:

    image

    提示:如果多次發布文章,使用同樣的封面,則可以先調用這個接口,把media_id 保存下來,之后這步就不是必要的了,后面新建草稿時候,直接用寫定的media_id就可。

    3 新建草稿

    參考文檔:https://developers.weixin.qq.com/doc/offiaccount/Draft_Box/Add_draft.html

    image

    調用接口:

    https://api.weixin.qq.com/cgi-bin/draft/add?access_token={access_token}

    填上我們關注的必填選就可,需要填寫的不多。

    代碼:

    image

    注意:如果發布后,內容有亂碼,如:

    image

    那是編碼問題,構造json 數據時候,ensure_ascii 用false。上例是python代碼,如果json.dumps(drafts)會出錯。需要改為:json.dumps(drafts, ensure_ascii=False).encode(‘utf-8’) 。其他語言也有對應的設置方法。

    4 發布接口

    最后一步就是發布了,這個接口最為簡單。直接把前面的增加草稿返回的media_id 提交下就可。

    參考文檔:https://developers.weixin.qq.com/doc/offiaccount/Publish/Publish.html

    image

    調用接口:

    https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token={access_token}

    代碼:

    image

    5 其他

    這步不是必要的,不關注發布狀態的就可以無視。由于發布文章是異步的,同時發布后的文章可能還被內容審核啥的,所以發布后的文章,可以通過publish_id 去請求“發布狀態輪詢接口”接口查詢狀態。

    整合發表功能基本函數封裝好之后,發表文章就是一步到位了:

    image

    特別提醒:現在公眾號是推薦制度,測試結果:通過api發布的文章,不會觸發微信系統推薦,也不會在主頁顯示,可用于菜單或者鏈接分享方式給用戶閱讀。

    完整代碼

    #-*- coding: UTF-8 -*-
    import json
    import os
    import requests
    def _str_of_json(content, key):
        res = json.loads(str(content, 'utf8'))
        if key not in res or res[key] == "":
            print(res)
            return False, ""
        return True, res[key]
    
    # 獲取token 返回(sucess, token)
    def get_token(appid, secret):
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (appid, secret)
        res = requests.get(url)
        return _str_of_json(res.content, "access_token")
    
    # 上傳圖片 返回(sucess, media_id)
    def upload_image(token, file_path):
        url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=image" % token
        with open(file=file_path, mode='rb') as fp:
            files = {'media': fp}
            resp = requests.post(url, files=files)
            return _str_of_json(resp.content, "media_id")
        return False, ""
    
    # 新建草稿 返回(sucess, media_id)
    def add_draft(token, cover_media_id, title, content):
        url = "https://api.weixin.qq.com/cgi-bin/draft/add?access_token=%s" % token
        article = {
            "title":title,
            "thumb_media_id":cover_media_id,
            "content":content,
            # "author":"author", # 非必填
            # "digest":"digest", # 非必填
        }
        drafts = {
            "articles":[
                article
            ]
        }
        headers = {'Content-Type': 'application/json'}
        # 直接post json.dumps(drafts) 會有亂碼,所以
        post_data = json.dumps(drafts, ensure_ascii=False).encode('utf-8')
        res = requests.post(url, data=post_data, headers=headers)
        return _str_of_json(res.content, "media_id")
    
    # 發布,返回(sucess, publish_id)
    def publish(token, draft_id):
        url = "https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token=%s" % token
        res = requests.post(url, json={"media_id":draft_id})
        return _str_of_json(res.content, "publish_id")
    
    def publish_article(appid, secret, title, content, cover_file_path):
        # 1 獲取token
        res, token = get_token(appid, secret)
        # 2 上傳封面
        res, cover_media_id = upload_image(token, cover_file_path)
        # 3 保存草稿
        ret, draft_id = add_draft(token, cover_media_id, title, content)
        # 4 發布
        ret, publish_id = publish(token, draft_id)
    
    if __name__ == '__main__':
        appid = "wx000000000000" # 你的 appid
        secret = "xxxxxxxxxxxxxxx" # 你的 secret
        file_path = "/Users/xxx/yyyy.jpg" # 你的文章封面圖片
        title = "你的文章標題"
        content = "你的文章內容"
        publish_article(appid, secret, title, content, file_path)

    原文轉載自:https://mp.weixin.qq.com/s/vu9Aep-QBwN0xu4i28W3UA

    上一篇:

    使用Python開發1688商品詳情API接口

    下一篇:

    API接口安全—webservice、Swagger、WEBpack
    #你可能也喜歡這些API文章!

    我們有何不同?

    API服務商零注冊

    多API并行試用

    數據驅動選型,提升決策效率

    查看全部API→
    ??

    熱門場景實測,選對API

    #AI文本生成大模型API

    對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

    25個渠道
    一鍵對比試用API 限時免費

    #AI深度推理大模型API

    對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

    10個渠道
    一鍵對比試用API 限時免費