Python 微信公眾號發送消息


1. 公眾號測試地址

https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index

 

 

 

2. 代碼

# pip3 install requests
import requests
import json


def get_access_token():
    """
    獲取微信全局接口的憑證(默認有效期倆個小時)
    如果不每天請求次數過多, 通過設置緩存即可
    """
    result = requests.get(
        url="https://api.weixin.qq.com/cgi-bin/token",
        params={
            "grant_type": "client_credential",
            "appid": "wx2499da7621f818e8",
            "secret": "6239e3dfc5af686777ea40b9f3df5f48",
        }
    ).json()

    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)



if __name__ == '__main__':
    sendmsg('關注者的ID','發送消息內容')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM