本文目录导读:

我来为您详细介绍PHP集成语音通知API的方法,以常见的阿里云语音服务为例:
基础环境准备
安装依赖
composer require alibabacloud/sdk
阿里云语音服务配置
// config.php
return [
'accessKeyId' => '您的AccessKeyId',
'accessSecret' => '您的AccessKeySecret',
'voiceTemplateCode' => 'TTS_模板编号',
'calledNumber' => '被叫号码',
'showNumber' => '主叫显号'
];
基础语音通知类
<?php
// VoiceNotification.php
namespace App\Services;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class VoiceNotification
{
private $config;
public function __construct($config = [])
{
$this->config = $config ?: require 'config.php';
$this->initClient();
}
private function initClient()
{
AlibabaCloud::accessKeyClient(
$this->config['accessKeyId'],
$this->config['accessSecret']
)->regionId('cn-hangzhou')->asDefaultClient();
}
/**
* 发送语音通知
* @param string $phoneNumber 手机号
* @param array $params 模板参数
* @return array
*/
public function sendVoiceNotify($phoneNumber, $params = [])
{
try {
$result = AlibabaCloud::rpc()
->product('Dyvmsapi')
->scheme('https') // https | http
->version('2017-05-25')
->action('SingleCallByTts')
->method('POST')
->host('dyvmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => 'cn-hangzhou',
'CalledNumber' => $phoneNumber,
'CalledShowNumber' => $this->config['showNumber'],
'TtsCode' => $this->config['voiceTemplateCode'],
'TtsParam' => json_encode($params)
],
])
->request();
return [
'success' => true,
'data' => $result->toArray(),
'message' => '语音通知发送成功'
];
} catch (ClientException $e) {
return [
'success' => false,
'message' => '客户端错误:' . $e->getErrorMessage()
];
} catch (ServerException $e) {
return [
'success' => false,
'message' => '服务端错误:' . $e->getErrorMessage(),
'httpCode' => $e->getHttpCode()
];
}
}
}
使用示例
<?php
// test.php
require 'vendor/autoload.php';
require 'VoiceNotification.php';
use App\Services\VoiceNotification;
// 创建实例
$voiceNotify = new VoiceNotification();
// 发送订单通知
$orderInfo = [
'customer' => '张三',
'orderId' => '20231201001',
'amount' => '299.00'
];
$result = $voiceNotify->sendVoiceNotify('13800138000', $orderInfo);
if ($result['success']) {
echo "语音通知发送成功!";
print_r($result['data']);
} else {
echo "发送失败:" . $result['message'];
}
其他语音平台集成
腾讯云语音通知
// 使用composer安装
// composer require tencentcloud/apigateway
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Vms\V20200902\VmsClient;
use TencentCloud\Vms\V20200902\Models\SendTtsVoiceRequest;
class TencentVoiceNotify
{
public function sendVoice($phone, $templateId, $params)
{
$cred = new Credential("你的SecretId", "你的SecretKey");
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("vms.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new VmsClient($cred, "ap-guangzhou", $clientProfile);
$req = new SendTtsVoiceRequest();
$req->setTemplateId($templateId);
$req->setCalledNumber($phone);
$req->setVoiceSdkAppid("您的应用ID");
$req->setTemplateParamSet($params);
try {
$resp = $client->SendTtsVoice($req);
return json_decode($resp->toJsonString(), true);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
}
封装通用接口类
<?php
// UnifiedVoiceAPI.php
namespace App\Services;
class UnifiedVoiceAPI
{
protected $provider;
protected $config;
public function __construct($provider = 'alibaba', $config = [])
{
$this->provider = $provider;
$this->config = $config;
}
public function send($phone, $templateCode, $params = [])
{
switch ($this->provider) {
case 'alibaba':
return $this->sendAlibaba($phone, $templateCode, $params);
case 'tencent':
return $this->sendTencent($phone, $templateCode, $params);
// 可以添加更多提供商
default:
throw new \Exception('不支持的语音服务提供商');
}
}
private function sendAlibaba($phone, $templateCode, $params)
{
$client = new VoiceNotification($this->config);
return $client->sendVoiceNotify($phone, $params);
}
private function sendTencent($phone, $templateCode, $params)
{
$client = new TencentVoiceNotify($this->config);
return $client->sendVoice($phone, $templateCode, $params);
}
}
注意事项
安全配置
// 配置验证中间件
public function validatePhoneNumber($phone)
{
// 手机号格式验证
if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
throw new \InvalidArgumentException('手机号格式不正确');
}
}
// 限流控制
public function checkRateLimit($phone, $limit = 5)
{
$key = "voice_notify:{$phone}:" . date('Y-m-d');
// 使用Redis或缓存实现限流
$count = Cache::get($key, 0);
if ($count >= $limit) {
throw new \Exception('今日语音通知已达上限');
}
Cache::increment($key);
}
错误处理
// 统一错误处理
public function handleError($exception)
{
Log::error('语音通知失败', [
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'trace' => $exception->getTraceAsString()
]);
// 根据错误码判断是否需要重试
if ($this->shouldRetry($exception->getCode())) {
return $this->retry();
}
return [
'success' => false,
'error' => $exception->getMessage()
];
}
- 选择服务商:推荐阿里云、腾讯云等主流服务商
- 配置参数:注意安全凭证的存储和保护
- 模板管理:提前在控制台创建并审核语音模板
- 异常处理:做好错误处理和重试机制
- 监控告警:记录发送日志,设置异常告警
根据您的具体业务需求,可以选择不同的语音服务提供商和实现方式。