码迷,mamicode.com
首页 > 微信 > 详细

Python 微信公众号发送消息

时间:2017-12-28 17:22:41      阅读:454      评论:0      收藏:0      [点我收藏+]

标签:python   grant   tom   sts   red   src   use   get   log   

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,发送消息内容)

 

Python 微信公众号发送消息

标签:python   grant   tom   sts   red   src   use   get   log   

原文地址:https://www.cnblogs.com/supery007/p/8136295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!