如何使用 PHP 发送微信消息?获取微信公众平台的 Access Token;生成包含要发送信息的 JSON 请求体;设置请求头,包括 Content-Type 和 Authorization;使用 cURL 库向微信公众平台发送 HTTP POST 请求。

如何在 PHP 中使用微信开发发送消息
使用 PHP 发送微信消息的步骤:
获取微信公众平台的 Access Token
生成请求体
立即学习“PHP免费学习笔记(深入)”;
设置请求头
发送 HTTP POST 请求
详细步骤:
1. 获取微信公众平台的 Access Token
<code class="php">// 微信公众平台的 AppID $appid = 'YOUR_APPID'; // 微信公众平台的 AppSecret $appsecret = 'YOUR_APPSECRET'; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); $access_token = $result['access_token'];</code>
2. 生成请求体
<code class="php">$data = array(
'touser' => 'OPENID',
'msgtype' => 'text',
'text' => array(
'content' => 'Hello, world!'
)
);
$json_data = json_encode($data);</code>3. 设置请求头
<code class="php">$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $access_token
);</code>4. 发送 HTTP POST 请求
<code class="php">$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch);</code>
以上就是微信开发教php如何发送消息的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号