在PHP中,可以使用微信公众平台的API来发送语音消息。以下是一个示例代码:
<?php
// 设置微信公众平台的appid和appsecret
$appId = 'your_app_id';
$appSecret = 'your_app_secret';
// 获取access_token
$accessToken = getAccessToken($appId, $appSecret);
// 发送语音消息
sendVoiceMessage($accessToken, 'openid', 'media_id');
/**
* 获取access_token
* @param string $appId
* @param string $appSecret
* @return string
*/
function getAccessToken($appId, $appSecret)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
$response = file_get_contents($url);
$data = json_decode($response, true);
return $data['access_token'];
}
/**
* 发送语音消息
* @param string $accessToken
* @param string $openid
* @param string $mediaId
*/
function sendVoiceMessage($accessToken, $openid, $mediaId)
{
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$accessToken}";
$data = [
'touser' => $openid,
'msgtype' => 'voice',
'voice' => [
'media_id' => $mediaId
]
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
file_get_contents($url, false, $context);
}
请注意,以上代码仅仅是一个示例,实际使用时需要替换为您自己的appid、appsecret、openid和media_id。同时,您还需要根据自己的需求来设置其他参数,比如语音消息的内容、接收者等。
上一篇:php不等待url访问
下一篇:php if数值范围
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站