引言
准备工作
在开始之前,请确保以下准备工作已完成:
- 注册微信公众号:访问微信公众平台官网(),注册并获取相应的AppID和AppSecret。
- 设置服务器:准备一个可以运行PHP的服务器环境。
- 获取access_token:通过AppID和AppSecret获取access_token,这是与微信服务器通信的凭证。
获取access_token
<?php
$AppID = '你的AppID';
$AppSecret = '你的AppSecret';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$AppID&secret=$AppSecret";
$result = json_decode(file_get_contents($url), true);
$access_token = $result['access_token'];
echo "Access Token: " . $access_token . "\n";
?>
发送文本消息
<?php
$access_token = '你的access_token';
$toUser = '接收者的OpenID';
$fromUser = '发送者的OpenID';
$content = '这是一条测试消息';
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
$data = json_encode([
'touser' => $toUser,
'fromuser' => $fromUser,
'msgtype' => 'text',
'text' => ['content' => $content]
]);
$result = http_post($url, $data);
echo "发送结果:" . $result . "\n";
?>
发送图片消息
<?php
$access_token = '你的access_token';
$toUser = '接收者的OpenID';
$fromUser = '发送者的OpenID';
$media_id = '上传图片后获得的media_id';
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
$data = json_encode([
'touser' => $toUser,
'fromuser' => $fromUser,
'msgtype' => 'image',
'image' => ['media_id' => $media_id]
]);
$result = http_post($url, $data);
echo "发送结果:" . $result . "\n";
?>
发送图文消息
<?php
$access_token = '你的access_token';
$toUser = '接收者的OpenID';
$fromUser = '发送者的OpenID';
$media_id = '上传图文消息后获得的media_id';
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
$data = json_encode([
'touser' => $toUser,
'fromuser' => $fromUser,
'msgtype' => 'news',
'news' => [
'articles' => [
[
'title' => '标题',
'thumb_media_id' => $media_id,
'author' => '作者',
'digest' => '摘要',
'show_cover_pic' => 1,
'content' => '内容',
'content_source_url' => '链接'
]
]
]
]);
$result = http_post($url, $data);
echo "发送结果:" . $result . "\n";
?>