由于微信公众号发送服务需要与微信服务器进行交互,需要先申请一个微信公众号的开发者账号,获取 appID 和 appsecret 等信息。接下来是一个简单的 PHP 代码示例,实现了文本消息的发送服务:

<?php
// 设置参数
$appid = 'your_appid';
$appsecret = 'your_appsecret';
$token = 'your_token';
$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=';

// 获取 access_token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$json = json_decode($output, true);
$access_token = $json['access_token'];

// 发送文本消息
$json = '{
    "touser":"openid",
    "msgtype":"text",
    "text":
    {
         "content":"Hello World"
    }
}';
$url .= $access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>

需要注意的是,上述代码中的 your_appidyour_appsecretyour_token 需要替换为自己的参数。同时,由于微信公众号发送服务需要使用 curl 库进行 HTTP 请求,需要确保服务器已经安装了 curl 库。

PHP 微信公众号发送文本消息代码示例

原文地址: https://www.cveoy.top/t/topic/l207 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录