微信公众号发送模板消息

前提条件:
1、微信公众号要认证。 300元每年。
2、只能给关注公众号的用户发。
3、要知道用户的openid。

1、怎么获取用户的openid?

可以登陆微信管理后台,点击 内容与互动->用户列表 查看关注的用户,然后按F12进入调试模式,fakeid和dataid就是openid, 注意,对于同一个用户在不同的公众号下的openid是不同的。

微信也提供了一个接口,可以获取关注者的openid列表,但是没有昵称,openid和昵称对应不起来。

2、发送模板消息的python模块

wechat_template_message.py

# coding=utf-8
# /usr/bin/env python

import requests
import json
from datetime import datetime,timedelta

token={}

def get_access_token():
    global  token
    if not token or token.get('expires_time')<datetime.now():
        appid="*****************"
        secret = "**********************"
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(appid,secret)
        response = requests.get(url)
        result = json.loads(response.text)
        token['access_token'] = result["access_token"]
        token['expires_time'] = datetime.now() + timedelta(seconds=7000)
    print(token)
    return token["access_token"]

def send_message(data):
    json_template = json.dumps(data)
    url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + get_access_token()
    try:
        respone = requests.post(url, data=json_template, timeout=50)
        # 拿到返回值
        errcode = respone.json().get("errcode")
        print("test--", respone.json())
        if (errcode == 0):
            print("模板消息发送成功")
        else:
            print("模板消息发送失败")
    except Exception as e:
        print("test++", e)

def send_test_message(open_id,name,phone):
    data = {
        "touser": open_id,
        "template_id": "SQqXmh8XY_ouKXJ7sGRLbMJTWgKEDNvPCEnP--ch5lY",  # 模板ID
        "url": "http://www.baidu.com",
        "data": {
            "first": {
                "value": "有新的客户预约,请及时处理!",
                "color": "#173177"
            },
            "keyword1": {
                "value": name,
                "color": "#173177"
            },
            "keyword2": {
                "value": phone,
                "color": "#173177"
            },
            "remark": {
                "value": "点击跳转处理!",
                "color": "#173177"
            }
        }
    }
    send_message(data)


if __name__ == '__main__':
    openid="****************"
    name = "zjh"
    phone = "111111"
    send_test_message(openid,name,phone)

通过模块变量token来保存token,token是微信api调用的唯一凭证,有效时间7200秒。 我设置了7000秒的过期时间,过期后重新获取。

然后就可以在其他模块里调用这个模块的工具函数进行发送短信了

from wechat_template_message import send_test_message

for i in range(10):
    openid="oUj705sY2MsTFToH_hrBIZqFFSho"
    name = "zjh"
    phone = "121313131"
    send_test_message(openid,name,phone)

从结果可以看到,token只获取了一次。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 PHP 中发送微信公众号模板消息,首先需要在微信公众平台中创建一个模板消息并获取模板 ID。接下来,您需要在 PHP 中使用 cURL 库向微信 API 发送 POST 请求,以便将模板消息发送给用户。以下是示例代码: ```php $access_token = 'YOUR_ACCESS_TOKEN'; $template_id = 'YOUR_TEMPLATE_ID'; $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; $data = array( 'touser' => 'OPENID', 'template_id' => $template_id, 'data' => array( 'first' => array('value' => 'Hello, world!'), 'keyword1' => array('value' => 'Keyword 1'), 'keyword2' => array('value' => 'Keyword 2'), 'remark' => array('value' => 'This is a remark.') ) ); $data_string = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string) )); $result = curl_exec($ch); curl_close($ch); echo $result; ``` 上述代码中,`$access_token` 是您的公众号访问令牌,`$template_id` 是您创建的模板消息的 ID。您需要将 `OPENID` 替换为要接收模板消息的用户的 OpenID。`$data` 数组包含模板消息的详细信息,其中 `first`、`keyword1`、`keyword2` 和 `remark` 分别对应模板消息中的不同部分。最后,使用 cURL 库将 `$data` 数组作为 JSON 字符串发送微信 API,然后解析响应以查看是否成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值