该库要求 PHP 版本最低为 8.1
这是使用 Vonage API 的 PHP 客户端库。要使用此功能,您需要一个 Vonage 帐户。在这里免费注册。
要使用客户端库,您需要创建一个 Vonage 帐户。
要将 PHP 客户端库安装到您的项目中,我们建议使用 Composer。
composer require vonage/client
请注意,这实际上指向一个包含 HTTP 客户端和此核心库的包装器库。如果您愿意,您可以直接从 Composer 安装此库,并能够选择您的项目使用的 HTTP 客户端。
您无需克隆此存储库即可在自己的项目中使用此库。使用 Composer 从 Packagist 安装它。
如果您是 Composer 新手,以下是一些可能有用的资源:
如果您使用 Composer,请确保自动加载器包含在项目的引导文件中:
require_once " vendor/autoload.php " ;
使用您的 API 密钥和密码创建客户端:
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
出于测试目的,您可能需要将vonage/client
发出请求的 URL 从api.vonage.com
更改为其他内容。您可以通过在创建VonageClient
实例时提供一个包含base_api_url
的数组作为第二个参数来实现此目的。
$ client = new Vonage Client (
new Vonage Client Credentials Basic ( API_KEY , API_SECRET ),
[
' base_api_url ' => ' https://example.com '
]
);
对于通常会访问rest.nexmo.com
API,提供base_rest_url
作为构造函数的选项将更改这些请求。
要使用 Vonage 的 SMS API 发送 SMS 消息,请调用$client->sms()->send()
方法。
消息对象用于创建 SMS 消息。每个消息类型都可以使用所需的参数来构造,并且流畅的接口提供对可选参数的访问。
$ text = new Vonage SMS Message SMS ( VONAGE_TO , VONAGE_FROM , ' Test message using PHP client library ' );
$ text -> setClientRef ( ' test-message ' );
消息对象被传递给send
方法:
$ response = $ client -> sms ()-> send ( $ text );
发送后,消息对象可用于访问响应数据。
$ data = $ response -> current ();
echo " Sent message to " . $ data -> getTo () . " . Balance is now " . $ data -> getRemainingBalance () . PHP_EOL ;
由于每条 SMS 消息可以拆分为多条消息,因此响应包含生成的每条消息的一个对象。您可以使用 PHP 中的标准count()
函数检查生成了多少条消息。如果您想获取第一条消息,可以在响应上使用current()
方法。
$ data = $ response -> current ();
$ data -> getRemainingBalance ();
foreach ( $ response as $ index => $ data ){
$ data -> getRemainingBalance ();
}
发送示例还有完整的工作示例。
您可以在 SMS 客户端代码中使用静态isGsm7()
方法来确定是使用 GSM-7 编码还是使用 Unicode 发送消息。这是一个例子:
$ sms = new Vonage SMS Message SMS ( ' 123 ' , ' 456 ' , ' is this gsm7? ' );
if ( Vonage SMS Message SMS :: isGsm7 ( $ text )) {
$ sms -> setType ( ' text ' );
} else {
$ sms -> setType ( ' unicode ' );
}
入站消息作为 Webhook 发送到您的应用程序。客户端库提供了一种从 Webhook 创建入站消息对象的方法:
try {
$ inbound = Vonage SMS Webhook Factory:: createFromGlobals ();
error_log ( $ inbound -> getText ());
} catch ( InvalidArgumentException $ e ) {
error_log ( ' invalid message ' );
}
您可能还想阅读有关消息签名的文档。
SMS API 支持通过使用“签名密钥”而不是您的 API 密钥生成和添加签名来对消息进行签名的功能。支持的算法有:
md5hash1
md5
sha1
sha256
sha512
您的应用程序和 Vonage 都需要就使用哪种算法达成一致。在仪表板中,访问您的帐户设置页面,然后在“API 设置”下您可以选择要使用的算法。这也是您可以找到“签名密钥”的位置(它与 API 密钥不同)。
使用这些凭据以及要使用的算法创建客户端,例如:
$ client = new Vonage Client ( new Vonage Client Credentials SignatureSecret ( API_KEY , SIGNATURE_SECRET , ' sha256 ' ));
使用此客户端,您的 SMS API 消息将作为签名消息发送。
您可能还想阅读有关消息签名的文档。
如果您为传入消息启用了消息签名,则 SMS Webhook 将包含字段sig
、 nonce
和timestamp
。要验证签名是否来自 Vonage,您可以使用传入数据、签名密钥和签名方法创建一个 Signature 对象。然后使用check()
方法和收到的实际签名(通常是_GET['sig']
)来确保它是正确的。
$ signature = new Vonage Client Signature ( $ _GET , SIGNATURE_SECRET , ' sha256 ' );
// is it valid? Will be true or false
$ isValid = $ signature -> check ( $ _GET [ ' sig ' ]);
使用您的签名密钥和其他提供的参数,可以计算签名并根据传入的签名值进行检查。
消息 API 用于发送各种出站消息。目前支持以下平台:
这些平台中的每一个都有不同类别的您可以发送的消息(例如,使用 WhatsApp,您可以发送文本、图像、音频、视频、文件或模板,但对于 Viber,您只能发送文本或图像) 。您可以在命名空间VonageMessagesChannel
下找到所有可发送的消息类型。以这种方式分离每种类型的原因是平台和消息类型在 API 调用中需要不同的参数。
VonageMessagesClient
配置方式与 SMS API 客户端类似。不同之处在于身份验证可以是 JSON Web 令牌 (JWT) 或基本身份验证。您可以在本自述文件的“使用”部分找到有关如何设置客户凭据的更多信息。
这里有一些例子:
首先,我们需要创建一个新的 WhatsAppText 对象,如下所示:
$ whatsAppText = new Vonage Messages Channel WhatsApp WhatsAppText (
FROM_NUMBER ,
TO_NUMBER ,
' this is a WA text from vonage '
);
消息 API 客户端有一个方法send()
您可以在其中发送所提供的任何消息类型。因此,要发送此消息,假设您已经正确设置了 Vonage 客户端,则以下代码将执行此操作:
$ client -> messages ()-> send ( $ whatsAppText );
如果错误范围在 200 以内,您的响应将是 JSON 有效负载;如果在 400/500 以内,您的响应将抛出相关的APIException
。
某些Channel
对象需要更多参数才能创建。您可以通过比较构造函数参数与 API 文档来了解这些要求的粗略映射。其中一些消息采用自定义可重用对象(位于VonageMessagesMessageObjects
命名空间下)。其中之一是图像 - 因此这里是如何发送 Viber 图像的示例:
$ imageObject = Vonage Messages MessageObjects ImageObject (
' https://picsum.photos/200/300 ' ,
' image caption '
);
$ viberImage = new Vonage Messages Channel Viber ViberImage (
FROM_NUMBER ,
TO_NUMBER ,
$ imageObject
);
$ client -> messages ()-> send ( $ viberImage );
Vonage 的验证 API 可以轻松证明用户在注册过程中提供了自己的电话号码,或在登录过程中实施第二因素身份验证。
您可以使用如下代码开始验证过程:
$ request = new Vonage Verify Request ( ' 14845551212 ' , ' My App ' );
$ response = $ client -> verify ()-> start ( $ request );
echo " Started verification with an id of: " . $ response -> getRequestId ();
用户输入收到的 PIN 码后,使用请求 ID 和 PIN 调用check()
方法(见下文)以确认 PIN 正确。
要取消正在进行的验证,或触发下一次发送确认代码的尝试,您可以将现有验证对象传递给客户端库,或仅使用请求 ID:
$ client -> verify ()-> trigger ( ' 00e6c3377e5348cdaf567e1417c707a5 ' );
$ client -> verify ()-> cancel ( ' 00e6c3377e5348cdaf567e1417c707a5 ' );
同样,检查验证需要用户提供的 PIN 和请求 ID:
try {
$ client -> verify ()-> check ( ' 00e6c3377e5348cdaf567e1417c707a5 ' , ' 1234 ' );
echo " Verification was successful (status: " . $ verification -> getStatus () . " ) n" ;
} catch ( Exception $ e ) {
echo " Verification failed with status " . $ e -> getCode ()
. " and error text "" . $ e -> getMessage () . ""n" ;
}
您可以检查验证的状态,或使用请求 ID 访问过去验证的结果。然后验证对象将提供丰富的接口:
$ client -> verify ()-> search ( ' 00e6c3377e5348cdaf567e1417c707a5 ' );
echo " Codes checked for verification: " . $ verification -> getRequestId () . PHP_EOL ;
foreach ( $ verification -> getChecks () as $ check ){
echo $ check -> getDate ()-> format ( ' d-m-y ' ) . ' ' . $ check -> getStatus () . PHP_EOL ;
}
Vonage 的验证 API 具有 PSD2(支付服务指令)所要求的 SCA(安全客户身份验证)支持,并由需要获得客户付款确认的应用程序使用。它包括消息中的收款人和金额。
开始验证付款,如下所示:
$ request = new Vonage Verify RequestPSD2 ( ' 14845551212 ' , ' My App ' );
$ response = $ client -> verify ()-> requestPSD2 ( $ request );
echo " Started verification with an id of: " . $ response [ ' request_id ' ];
用户输入收到的 PIN 码后,使用请求 ID 和 PIN 码调用/check
端点以确认 PIN 码正确。
Vonage 的验证 v2 更多地依赖于异步工作流程。 webhooks 以及为开发人员提供的更多可定制验证工作流程。要开始验证,您需要 API 客户端,该客户端位于命名空间verify2
下。
发出验证请求需要一个“基本”通信通道来提供验证模式。您可以通过添加不同的“工作流程”来自定义这些交互。对于每种类型的工作流程,您都可以创建一个Verify2 类来为您处理初始工作流程。例如:
$ client = new Vonage Client (
new Vonage Client Credentials Basic ( API_KEY , API_SECRET ),
);
$ smsRequest = new Vonage Verify2 Request SMSRequest ( ' TO_NUMBER ' );
$ client -> verify2 ()-> startVerification ( $ smsRequest );
SMSRequest
对象将为您解析默认值,并将创建一个默认workflow
对象以使用 SMS。但是,您可以添加多个使用后备逻辑运行的工作流程。例如,如果您想创建一个尝试从用户处获取 PIN 码的验证。短信,但如果短信传送出现问题,您希望添加语音后备:您可以添加它。
$ client = new Vonage Client (
new Vonage Client Credentials Basic ( API_KEY , API_SECRET ),
);
$ smsRequest = new Vonage Verify2 Request SMSRequest ( ' TO_NUMBER ' , ' my-verification ' );
$ voiceWorkflow = new Vonage Verify2 VerifyObjects VerificationWorkflow ( Vonage Verify2 VerifyObjects VerificationWorkflow:: WORKFLOW_VOICE , ' TO_NUMBER ' );
$ smsRequest -> addWorkflow ( $ voiceWorkflow );
$ client -> verify2 ()-> startVerification ( $ smsRequest );
这会将语音工作流程添加到原始 SMS 请求中。验证请求将尝试按照给出的顺序解决该过程(从请求类型的默认值开始)。
基本请求类型如下:
SMSRequest
WhatsAppRequest
WhatsAppInterativeRequest
EmailRequest
VoiceRequest
SilentAuthRequest
对于添加工作流程,您可以将可用的有效工作流程视为VerificationWorkflow
对象中的常量。为了获得更好的开发人员体验,您不能因为对象上发生的验证而创建无效的工作流。
要提交代码,由于 API 的性质,您需要将方法包含在 try/catch 中。如果代码正确,该方法将返回一个true
布尔值。如果失败,它将从 API 中抛出需要捕获的相关异常。
$ code = ' 1234 ' ;
try {
$ client -> verify2 ()-> check ( $ code );
} catch ( Exception $ e ) {
var_dump ( $ e -> getMessage ())
}
当验证工作流程期间发生事件时,事件和更新将作为 Webhook 触发。符合 PSR-7 标准的传入服务器请求可以合并到 Webhook 值对象中,以实现更好的交互。您还可以从原始阵列中水合它们。如果成功,您将收到一个事件/更新类型的值对象。可能的网络钩子有:
VerifyEvent
VerifyStatusUpdate
VerifySilentAuthUpdate
// From a request object
$ verificationEvent = Vonage Verify2 Webhook Factory:: createFromRequest ( $ request );
var_dump ( $ verificationEvent -> getStatus ());
// From an array
$ payload = $ request -> getBody ()-> getContents ()
$ verificationEvent = Vonage Verify2 Webhook Factory:: createFromArray ( $ payload );
var_dump ( $ verificationEvent -> getStatus ());
如果需要,您可以在最终用户采取任何操作之前取消请求。
$ requestId = ' c11236f4-00bf-4b89-84ba-88b25df97315 ' ;
$ client -> verify2 ()-> cancel ( $ requestId );
所有$client->voice()
方法都要求使用VonageClientCredentialsKeypair
或包含密钥Keypair
的VonageClientCredentialsContainer
构建客户端:
$ basic = new Vonage Client Credentials Basic ( VONAGE_API_KEY , VONAGE_API_SECRET );
$ keypair = new Vonage Client Credentials Keypair (
file_get_contents ( VONAGE_APPLICATION_PRIVATE_KEY_PATH ),
VONAGE_APPLICATION_ID
);
$ client = new Vonage Client ( new Vonage Client Credentials Container ( $ basic , $ keypair ));
您可以使用OutboundCall
对象启动呼叫:
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ outboundCall
-> setAnswerWebhook (
new Vonage Voice Webhook ( ' https://example.com/webhooks/answer ' )
)
-> setEventWebhook (
new Vonage Voice Webhook ( ' https://example.com/webhooks/event ' )
)
;
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
如果您想让系统从链接到应用程序的号码中随机选择一个 FROM 号码,您可以省略VonageVoiceOutboundCall
构造函数的第二个参数,系统将为您随机选择一个号码。
SimSwap 使用 CAMARA 标准来确定 SIM 卡在蜂窝设备中的使用时间。这意味着身份验证机制比其他 API 稍微复杂一些。您将需要:
拥有已在 Vonage 全球网络平台注册的您自己的订户号码。您的仪表板应用程序 ID 您的私钥
此 API 有两种可用方法: checkSimSwap
和checkSimSwapDate
。
这是使用两者的示例:
$ credentials = new Vonage Client Credentials Gnp (
' 0777888888 ' ,
file_get_contents ( ' ./private.key ' ),
' 0dadaeb4-7c79-4d39-b4b0-5a6cc08bf537 '
);
$ client = new Vonage Client ( $ credentials );
$ swapResult = $ client -> simswap ()-> checkSimSwap ( ' 07999999999 ' , 500 );
if ( $ swapResult ) {
echo " Warning: SIM Swapped recently "
} else {
echo " SIM OK "
};
// Finding the swap date
echo $ client -> simswap ()-> checkSimSwapDate ( ' 07999999999 ' );
号码验证使用 CAMARA API 标准,用于确定请求是否有效。与其他 SDK 不同,SDK 分为进程开始和进程结束。
您将需要:
拥有已在 Vonage 全球网络平台注册的您自己的订户号码。您的仪表板应用程序 ID 您的私钥,从 Vonage 仪表板下载
buildFrontEndUrl()
方法。调用此方法时,您需要提供应用程序预期接收包含唯一code
回调的路由。您需要在授权地区拥有授权电话号码才能使用此功能。这是虚拟示例: class VerificationController extends MyFrameworkAbsractController
{
$ credentials = new Vonage Client Credentials Gnp(
' 077380777111 ' ,
file_get_contents ( ' ../private.key ' ),
' 0dadaeb4-7c79-4d39-b4b0-5a6cc08bf537 '
)
$ client = new Vonage Client ( $ credentials );
$ verifyUrl = $ client -> numberVerification ()-> buildFrontEndUrl (
' 07777777777 ' ,
' https://myapp.com/auth/numberVerify '
);
return $ this -> render ( ' verify.html.twig ' , [
' verifyLink ' => $ verifyUrl
]);
}
code
,SDK 将负责处理执行此操作所需的 Auth 方法。该方法从 API 返回一个布尔值。这是一个例子: $ code = $ request -> get ( ' code ' );
$ result = $ client -> numberVerification ()-> verifyNumber (
' 09947777777 ' ,
$ code
);
if ( $ result ) {
Auth:: login ( $ request -> user ())
}
return redirect ( ' login ' );
}
该 API 用于应用内消息传递,包含广泛的功能和概念。有关更多信息,请查看 API 文档
$ credentials = new Vonage Client Credentials Keypair ( file_get_contents ( ' ./path-to-my-key.key ' , ' my-app-id ' ));
$ client = new Vonage Client ( $ credentials );
$ filter = new Vonage Conversation Filter ListConversationFilter ();
$ filter -> setStartDate ( ' 2018-01-01 10:00:00 ' );
$ filter -> setEndDate ( ' 2019-01-01 10:00:00 ' )
$ conversations = $ client -> conversations ()-> listConversations ( $ filter )
var_dump ( $ conversations );
$ credentials = new Vonage Client Credentials Keypair ( file_get_contents ( ' ./path-to-my-key.key ' , ' my-app-id ' ));
$ client = new Vonage Client ( $ credentials );
$ conversation = new CreateConversationRequest ( ' customer_chat ' , ' Customer Chat ' , ' https://example.com/image.png ' );
$ conversation -> setTtl ( 60 );
$ conversationNumber = new ConversationNumber ( ' 447700900000 ' );
$ conversationCallback = new ConversationCallback ( ' https://example.com/eventcallback ' );
$ conversationCallback -> setEventMask ( ' member:invited, member:joined ' );
$ conversationCallback -> setApplicationId ( ' afa393df-2c46-475b-b2d6-92da4ea05481 ' );
$ conversationCallback -> setNccoUrl ( ' https://example.com/ncco ' );
$ conversation -> setNumber ( $ conversationNumber );
$ conversation -> setConversationCallback ( $ conversationCallback );
$ response = $ this -> conversationsClient -> createConversation ( $ conversation );
var_dump ( $ response );
$ credentials = new Vonage Client Credentials Keypair ( file_get_contents ( ' ./path-to-my-key.key ' , ' my-app-id ' ));
$ client = new Vonage Client ( $ credentials );
$ filter = new ListUserConversationsFilter ();
$ filter -> setState ( ' INVITED ' );
$ filter -> setIncludeCustomData ( true );
$ filter -> setOrderBy ( ' created ' );
$ filter -> setStartDate ( ' 2018-01-01 10:00:00 ' );
$ filter -> setEndDate ( ' 2018-01-01 12:00:00 ' );
$ filter -> setPageSize ( 5 );
$ filter -> setOrder ( ' asc ' );
$ response = $ this -> conversationsClient -> listUserConversationsByUserId ( ' CON-d66d47de-5bcb-4300-94f0-0c9d4b948e9a ' );
foreach ( $ response as $ member ) {
$ members [] = $ member ;
}
var_dump ( $ members );
$ channel = Channel:: createChannel (Channel:: CHANNEL_TYPE_APP );
$ channel -> addUserFromTypes ([
' sms ' ,
' phone '
]);
$ channel -> addUserToField ( ' USR-82e028d9-9999-4f1e-8188-604b2d3471ec ' );
$ createMemberRequest = new CreateMemberRequest (
' invited ' ,
$ channel ,
' USR-82e028d9-5201-4f1e-8188-604b2d3471ec ' ,
' my_user_name ' ,
);
$ createMemberRequest -> setAudioPossible ( true );
$ createMemberRequest -> setAudioEnabled ( true );
$ createMemberRequest -> setAudioEarmuffed ( false );
$ createMemberRequest -> setAudioMuted ( false );
$ createMemberRequest -> setKnockingId ( ' 4f1e-8188 ' );
$ createMemberRequest -> setMemberIdInviting ( ' MEM-63f61863-4a51-4f6b-86e1-46edebio0391 ' );
$ createMemberRequest -> setFrom ( ' value ' );
$ response = $ this -> conversationsClient -> createMember (
$ createMemberRequest ,
' CON-63f61863-4a51-4f6b-86e1-46edebio0391 '
);
var_dump ( $ response );
NCCO 操作的完整参数列表可以在语音 API 文档中找到。
每个示例都使用以下结构向调用添加操作:
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ ncco = new NCCO ();
// ADD ACTIONS TO THE NCCO OBJECT HERE
$ outboundCall -> setNCCO ( $ ncco );
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ ncco = new NCCO ();
$ ncco -> addAction ( Vonage Voice NCCO Action Record:: factory ([
' eventUrl ' => ' https://example.com/webhooks/event '
]);
$ outboundCall -> setNCCO ( $ ncco );
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
您的 webhook url 将收到如下有效负载:
{
"start_time": "2020-10-29T14:30:24Z",
"recording_url": "https://api.nexmo.com/v1/files/<recording-id>",
"size": 27918,
"recording_uuid": "<recording-id>",
"end_time": "2020-10-29T14:30:31Z",
"conversation_uuid": "<conversation-id>",
"timestamp": "2020-10-29T14:30:31.619Z"
}
然后您可以像这样获取并存储录音:
$recordingId = '<recording-id>';
$recordingUrl = 'https://api.nexmo.com/v1/files/' . $recordingId;
$data = $client->get($recordingUrl);
file_put_contents($recordingId.'.mp3', $data->getBody());
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ ncco = new NCCO ();
$ ncco -> addAction ( new Vonage Voice NCCO Action Talk ( ' This is a text to speech call from Vonage ' ));
$ outboundCall -> setNCCO ( $ ncco );
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ ncco = new NCCO ();
$ ncco -> addAction ( new Vonage Voice NCCO Action Stream ( ' https://example.com/sounds/my-audio.mp3 ' ));
$ outboundCall -> setNCCO ( $ ncco );
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
支持键盘输入和语音输入。注意。输入操作必须遵循bargeIn
设置为true
操作
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ ncco = new NCCO ();
$ ncco -> addAction ( Vonage Voice NCCO Action Talk:: factory ( ' Please record your name. ' ,[
' bargeIn ' => true ,
]));
$ ncco -> addAction ( Vonage Voice NCCO Action Input:: factory ([
' eventUrl ' => ' https://example.com/webhooks/event ' ,
' type ' => [
' speech ' ,
],
' speech ' => [
' endOnSilence ' => true ,
],
]));
$ outboundCall -> setNCCO ( $ ncco );
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
Webhook URL 将接收包含用户输入的有效负载以及语音输入的相对置信度评级。
$ outboundCall = new Vonage Voice OutboundCall (
new Vonage Voice Endpoint Phone ( ' 14843331234 ' ),
new Vonage Voice Endpoint Phone ( ' 14843335555 ' )
);
$ ncco = new NCCO ();
$ ncco -> addAction ( new Vonage Voice NCCO Action Talk ( ' We are just testing the notify function, you do not need to do anything. ' ));
$ ncco -> addAction ( new Vonage Voice NCCO Action Notify ([
' foo ' => ' bar ' ,
], new Vonage Voice Webhook ( ' https://example.com/webhooks/notify ' )));
$ outboundCall -> setNCCO ( $ ncco );
$ response = $ client -> voice ()-> createOutboundCall ( $ outboundCall );
Webhook URL 将接收请求中指定的有效负载。
您可以使用VonageCallCall
对象或字符串形式的呼叫 UUID 来获取呼叫:
$ call = $ client -> voice ()-> get ( ' 3fd4d839-493e-4485-b2a5-ace527aacff3 ' );
echo $ call -> getDirection ();
您还可以使用过滤器搜索呼叫。
$ filter = new Vonage Voice Filter VoiceFilter ();
$ filter -> setStatus ( ' completed ' );
foreach ( $ client -> search ( $ filter ) as $ call ){
echo $ call -> getDirection ();
}
应用程序是配置容器。您可以使用数组结构创建一个:
$ application = new Vonage Application Application ();
$ application -> fromArray ([
' name ' => ' test application ' ,
' keys ' => [
' public_key ' => ' -----BEGIN PUBLIC KEY-----nMIIBIjANBgkqhkiG9w0BAQEFAAOCAnKOxjsU4pf/sMFi9N0jqcSLcjxu33Gnd/vynKnlw9SENi+UZR44GdjGdmfm1ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3n0kYWekeIZawIwe/g9faFgkev+1xsOnOUNhPx2LhuLmgwWSRS4L5W851Xe3fnUQIDAQABn-----END PUBLIC KEY-----n '
],
' capabilities ' => [
' voice ' => [
' webhooks ' => [
' answer_url ' => [
' address ' => ' https://example.com/webhooks/answer ' ,
' http_method ' => ' GET ' ,
],
' event_url ' => [
' address ' => ' https://example.com/webhooks/event ' ,
' http_method ' => ' POST ' ,
],
]
],
' messages ' => [
' webhooks ' => [
' inbound_url ' => [
' address ' => ' https://example.com/webhooks/inbound ' ,
' http_method ' => ' POST '
],
' status_url ' => [
' address ' => ' https://example.com/webhooks/status ' ,
' http_method ' => ' POST '
]
]
],
' rtc ' => [
' webhooks ' => [
' event_url ' => [
' address ' => ' https://example.com/webhooks/event ' ,
' http_method ' => ' POST ' ,
],
]
],
' vbc ' => []
]
]);
$ client -> applications ()-> create ( $ application );
您还可以向客户端传递一个应用程序对象:
$ a = new Vonage Application Application ();
$ a -> setName ( ' PHP Client Example ' );
$ a -> getVoiceConfig ()-> setWebhook ( ' answer_url ' , ' https://example.com/webhooks/answer ' , ' GET ' );
$ a -> getVoiceConfig ()-> setWebhook ( ' event_url ' , ' https://example.com/webhooks/event ' , ' POST ' );
$ a -> getMessagesConfig ()-> setWebhook ( ' status_url ' , ' https://example.com/webhooks/status ' , ' POST ' );
$ a -> getMessagesConfig ()-> setWebhook ( ' inbound_url ' , ' https://example.com/webhooks/inbound ' , ' POST ' );
$ a -> getRtcConfig ()-> setWebhook ( ' event_url ' , ' https://example.com/webhooks/event ' , ' POST ' );
$ a -> disableVbc ();
$ client -> applications ()-> create ( $ a );
您可以迭代所有应用程序:
foreach ( $ client -> applications ()-> getAll () as $ application ){
echo $ application -> getName () . PHP_EOL ;
}
或者,您可以使用字符串 UUID 或应用程序对象来获取应用程序。
$ application = $ client -> applications ()-> get ( ' 1a20a124-1775-412b-b623-e6985f4aace0 ' );
一旦有了应用程序对象,您就可以修改并保存它。
$ application = $ client -> applications ()-> get ( ' 1a20a124-1775-412b-b623-e6985f4aace0 ' );
$ application -> setName ( ' Updated Application ' );
$ client -> applications ()-> update ( $ application );
您可以列出您的帐户拥有的号码,并可以选择包括过滤:
search_pattern
:
0
- 数字以pattern
开头1
- 数字包含pattern
2
- 数字以pattern
结尾 $ filter = new Vonage Numbers Filter OwnedNumbers ();
$ filter
-> setPattern ( 234 )
-> setSearchPattern ( Vonage Numbers Filter OwnedNumbers:: SEARCH_PATTERN_CONTAINS )
;
$ response = $ client -> numbers ()-> searchOwned ( null , $ filter );
has_application
:
true
- 该号码已附加到申请中false
- 该号码未附加到申请中 $ filter = new Vonage Numbers Filter OwnedNumbers ();
$ filter -> setHasApplication ( true );
$ response = $ client -> numbers ()-> searchOwned ( $ filter );
application_id
:
$ filter = new Vonage Numbers Filter OwnedNumbers ();
$ filter -> setApplicationId ( " 66c04cea-68b2-45e4-9061-3fd847d627b8 " );
$ response = $ client -> numbers ()-> searchOwned ( $ filter );
您可以搜索特定国家/地区可购买的号码:
$ numbers = $ client -> numbers ()-> searchAvailable ( ' US ' );
默认情况下,这只会返回前 10 个结果。您可以添加额外的VonageNumbersFilterAvailableNumbers
过滤器来缩小搜索范围。
购买号码时,可以传入号码搜索返回的值:
$ numbers = $ client -> numbers ()-> searchAvailable ( ' US ' );
$ number = $ numbers -> current ();
$ client -> numbers ()-> purchase ( $ number -> getMsisdn (), $ number -> getCountry ());
或者您可以手动指定号码和国家/地区:
$ client -> numbers ()-> purchase ( ' 14155550100 ' , ' US ' );
要更新号码,请使用numbers()->update
并传入要更改的配置选项。要清除设置,请传入空值。
$ number = $ client -> numbers ()-> get ( VONAGE_NUMBER );
$ number
-> setAppId ( ' 1a20a124-1775-412b-b623-e6985f4aace0 ' )
-> setVoiceDestination ( ' 447700900002 ' , ' tel ' )
-> setWebhook (
Vonage Number Number:: WEBHOOK_VOICE_STATUS ,
' https://example.com/webhooks/status '
)
-> setWebhook (
Vonage Number Number:: WEBHOOK_MESSAGE ,
' https://example.com/webhooks/inbound-sms '
)
;
$ client -> numbers ()-> update ( $ number );
echo " Number updated " . PHP_EOL ;
要取消号码,请提供msisdn
:
$ client -> numbers ()-> cancel ( ' 447700900002 ' );
提供的 API 允许您轮换 API 机密。您可以创建一个新密钥(最多两个密钥),并在更新所有应用程序后删除现有密钥。
要获取秘密列表:
$ secretsCollection = $ client -> account ()-> listSecrets ( API_KEY );
/** @var VonageAccountSecret $secret */
foreach ( $ secretsCollection -> getSecrets () as $ secret ) {
echo " ID: " . $ secret -> getId () . " (created " . $ secret -> getCreatedAt () . " ) n" ;
}
您可以创建一个新的秘密(创建日期将帮助您知道哪个是哪个):
$ client -> account ()-> createSecret ( API_KEY , ' awes0meNewSekret!!; ' );
并删除旧密钥(任何仍在使用这些凭据的应用程序将停止工作):
try {
$ response = $ client -> account ()-> deleteSecret ( API_KEY , ' d0f40c7e-91f2-4fe0-8bc6-8942587b622c ' );
} catch ( Vonage Client Exception Request $ e ) {
echo $ e -> getMessage ();
}
如果您知道要拨打的国家/地区的前缀,则可以使用prefix-pricing
端点来了解拨打该号码的费用。每个前缀可以返回多个国家/地区(例如1
返回US
、 CA
和UM
):
$ results = $ client -> account ()-> getPrefixPricing ( ' 1 ' );
foreach ( $ results as $ price ) {
echo $ price -> getCountryCode (). PHP_EOL ;
echo $ price -> getCountryName (). PHP_EOL ;
foreach ( $ price -> getNetworks () as $ network ) {
echo $ network -> getName () . ' :: ' . $ network -> getCode (). ' :: ' . $ network -> getPrefixPrice (). PHP_EOL ;
}
echo " ---------------- " . PHP_EOL ;
}
检查您帐户上剩余的信用额度:
$ response = $ client -> account ()-> getBalance ();
echo round ( $ response -> getBalance (), 2 ) . " EUR n" ;
检查帐户的当前设置:
$ response = $ client -> account ()-> getConfig ();
print_r ( $ response -> toArray ());
更新传入 SMS 消息和送达回执的默认回调 URL:
$ response = $ client -> account ()-> updateConfig ([
" sms_callback_url " => " http://example.com/webhooks/incoming-sms " ,
" dr_callback_url " => " http://example.com/webhooks/delivery-receipt "
]);
print_r ( $ response -> toArray ());
为了使用 Vonage 的网络 API,您需要在 Vonage 网络注册表中启用
注册 MSNDIN 后,您就可以使用 SimSwap。
SimSwap 使用 Global Network Platform 身份验证机制,因此授权流程看起来与其他 API 客户端略有不同。在后台,SDK 将处理多个调用,以便您配置 CAMARA 标准访问令牌。
以下是检查最近是否更换过 SIM 卡的示例:
$ credentials = new Vonage Client Credentials Gnp (
' tel:+447700900000 ' ,
fopen ( ' ./my-private-key ' ),
' my-application-id '
);
$ client = new Vonage Client ( $ credentials );
if ( $ client -> simswap ()-> checkSimSwap ( ' 07700009999 ' , 240 )) {
echo ' Warning: SIM Swap Check Failed '
} else {
echo ' SIM Swap Check Pass '
}
以下是检索交换日期的方法:
$ credentials = new Vonage Client Credentials Gnp (
' tel:+447700900000 ' ,
fopen ( ' ./my-private-key ' ),
' my-application-id '
);
$ client = new Vonage Client ( $ credentials );
$ date = $ client -> simswap ()-> checkSimSwapDate ( ' 07700009999 ' )
echo $ date;
Number Insights API 允许用户检查号码是否有效并了解有关如何使用该号码的更多信息。
您可以使用basic()
或standard()
方法(可以使用advanced()
方法,但建议使用 async 选项来获取高级信息),如下所示:
try {
$ insights = $ client -> insights ()-> basic ( PHONE_NUMBER );
echo $ insights -> getNationalFormatNumber ();
} catch ( Exception $ e ) {
// for the Vonage-specific exceptions, try the `getEntity()` method for more diagnostic information
}
在上例中,数据返回到$insights
变量中。
要获得高级见解,请使用异步功能并提供要发送到的 Webhook 的 URL:
try {
$ client -> insights ()-> advancedAsync ( PHONE_NUMBER , ' http://example.com/webhooks/number-insights ' );
} catch ( Exception $ e ) {
// for the Vonage-specific exceptions, try the `getEntity()` method for more diagnostic information
}
查看文档,了解包含您请求的数据的传入 Webhook 中的内容。
该API用于创建和配置与您的主帐户相关的子帐户,并在帐户之间转移信用、余额和购买的号码。默认情况下,子账户 API 处于禁用状态。如果您想使用子帐户,请联系支持人员以在您的帐户上启用 API。
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' 34kokdf ' ;
$ subaccounts = $ client -> subaccount ()-> getSubaccounts ( $ apiKey );
var_dump ( $ subaccounts );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ payload = [
' name ' => ' sub name ' ,
' secret ' => ' s5r3fds ' ,
' use_primary_account_balance ' => false
];
$ account = new Account ();
$ account -> fromArray ( $ payload );
$ response = $ client -> subaccount ()-> createSubaccount ( $ apiKey , $ account );
var_dump ( $ response );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ subaccountKey = ' bbe6222f ' ;
$ response = $ client -> subaccount ()-> getSubaccount ( $ apiKey , $ subaccountKey );
var_dump ( $ response );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ subaccountKey = ' bbe6222f ' ;
$ payload = [
' suspended ' => true ,
' use_primary_account_balance ' => false ,
' name ' => ' Subaccount department B '
];
$ account = new Account ();
$ account -> fromArray ( $ payload );
$ response = $ client -> subaccount ()-> updateSubaccount ( $ apiKey , $ subaccountKey , $ account )
var_dump ( $ response );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ filter = new Vonage Subaccount Filter Subaccount([ ' subaccount ' => ' 35wsf5 ' ])
$ transfers = $ client -> subaccount ()-> getCreditTransfers ( $ apiKey );
var_dump ( $ transfers );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ transferRequest = ( new TransferCreditRequest ( $ apiKey ))
-> setFrom ( ' acc6111f ' )
-> setTo ( ' s5r3fds ' )
-> setAmount ( ' 123.45 ' )
-> setReference ( ' this is a credit transfer ' );
$ response = $ this -> subaccountClient -> makeCreditTransfer ( $ transferRequest );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ filter = new Vonage Subaccount Filter Subaccount ([ ' end_date ' => ' 2022-10-02 ' ]);
$ transfers = $ client -> subaccount ()-> getBalanceTransfers ( $ apiKey , $ filter );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ transferRequest = ( new TransferBalanceRequest ( $ apiKey ))
-> setFrom ( ' acc6111f ' )
-> setTo ( ' s5r3fds ' )
-> setAmount ( ' 123.45 ' )
-> setReference ( ' this is a credit transfer ' );
$ response = $ client -> subaccount ()-> makeBalanceTransfer ( $ transferRequest );
var_dump ( $ response );
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( API_KEY , API_SECRET ));
$ apiKey = ' acc6111f ' ;
$ numberTransferRequest = ( new NumberTransferRequest ( $ apiKey ))
-> setFrom ( ' acc6111f ' )
-> setTo ( ' s5r3fds ' )
-> setNumber ( ' 4477705478484 ' )
-> setCountry ( ' GB ' );
$ response = $ client -> subaccount ()-> makeNumberTransfer ( $ numberTransferRequest );
var_dump ( $ response );
应用程序编程接口 | API发布状态 | 支持吗? |
---|---|---|
账户接口 | 一般可用性 | |
警报API | 一般可用性 | |
应用程序接口 | 一般可用性 | |
审计API | 贝塔 | |
对话API | 贝塔 | |
调度API | 贝塔 | |
外部账户API | 贝塔 | |
媒体API | 贝塔 | |
会议API | 一般可用性 | |
消息API | 一般可用性 | |
号码洞察API | 一般可用性 | |
号码管理API | 一般可用性 | |
定价API | 一般可用性 | |
主动连接API | 贝塔 | |
编辑API | 一般可用性 | |
报告API | 贝塔 | |
短信接口 | 一般可用性 | |
子账户API | 一般可用性 | |
验证API | 一般可用性 | |
验证 API(版本 2) | 一般可用性 | |
语音API | 一般可用性 |
随着时间的推移,Vonage API 不断发展并添加新功能,改变现有功能的工作方式,并弃用和删除旧的方法和功能。为了帮助开发人员了解何时进行弃用更改,SDK 将触发E_USER_DEPRECATION
警告。这些警告不会停止代码的执行,但在生产环境中可能会带来麻烦。
为了解决这个问题,默认情况下这些通知是被隐藏的。在开发中,您可以通过向VonageClient
构造函数传递一个名为show_deprecations
的附加配置选项来启用这些警告。启用此选项将显示所有弃用通知。
$ client = new Vonage Client (
new Vonage Client Credentials Basic ( API_KEY , API_SECRET ),
[
' show_deprecations ' => true
]
);
如果您在生产环境中发现过多的弃用通知,请确保配置选项不存在,或至少设置为false
。
unable to get local issuer certificate
由于以下错误,某些用户在发出请求时遇到问题:
Fatal error: Uncaught exception 'GuzzleHttpExceptionRequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)'
这是由于某些 PHP 安装未附带受信任的 CA 证书列表。这是一个系统配置问题,并不特定于 cURL 或 Vonage。
重要提示:在下一段中,我们提供了 CA 证书捆绑包的链接。 Vonage 不保证该捆绑包的安全性,您应该在计算机上安装任何 CA 捆绑包之前自行检查。
要解决此问题,请下载受信任的 CA 证书列表(例如,curl 捆绑包)并将其复制到您的计算机上。完成此操作后,编辑php.ini
并设置curl.cainfo
参数:
# Linux/MacOS
curl.cainfo = "/etc/pki/tls/cacert.pem"
# Windows
curl.cainfo = "C:phpextrassslcacert.pem"
我们允许使用任何 HTTPlug 适配器或 PSR-18 兼容的 HTTP 客户端,因此您可以根据需要创建具有替代配置的客户端,例如考虑本地代理,或处理特定于您的设置的其他内容。
以下示例将默认超时减少到 5 秒,以避免在您没有到我们服务器的路由时出现长时间延迟:
$ adapter_client = new Http Adapter Guzzle6 Client ( new GuzzleHttp Client ([ ' timeout ' => 5 ]));
$ vonage_client = new Vonage Client ( new Vonage Client Credentials Basic ( $ api_key , $ api_secret ), [], $ adapter_client );
当出现问题时,您将收到Exception
。 Vonage 异常类VonageClientExceptionRequest
和VonageClientExceptionServer
支持额外的getEntity()
方法,除了getCode()
和getMessage()
之外,您还可以使用该方法来查找有关出错原因的更多信息。返回的实体通常是与操作相关的对象,或者来自 API 调用的响应对象。
如果您安装的软件包存在冲突,无法与我们推荐的guzzlehttp/guzzle
软件包共存,那么您可以安装vonage/client-core
软件包以及任何满足php-http/client-implementation
要求的软件包。
有关选项,请参阅 Packagist 客户端实现页面。
我们的客户端库支持记录请求和响应,以便通过 PSR-3 兼容的日志记录机制进行调试。如果将debug
选项传递到客户端,并且在客户端的服务工厂中设置了 PSR-3 兼容记录器,我们将使用该记录器进行调试。
$ client = new Vonage Client ( new Vonage Client Credentials Basic ( ' abcd1234 ' , ' s3cr3tk3y ' ), [ ' debug ' => true ]);
$ logger = new Monolog Logger ( ' test ' );
$ logger -> pushHandler ( new Monolog Handler StreamHandler ( __DIR__ . ' /log.txt ' , Monolog Logger:: DEBUG ));
$ client -> getFactory ()-> set ( PSR Log LoggerInterface::class, $ logger );
启用调试日志记录有可能记录敏感信息,请勿在生产中启用
该库有一个完整的测试套件,旨在与 PHPUnit 一起运行。
要运行,请使用 Composer:
composer test
请注意:此测试套件很大,可能需要大量内存才能运行。如果您在 MacOS 或 Linux 中遇到“打开的文件太多”错误,可以使用一种方法来增加允许的文件指针数量。通过在命令行中输入以下命令来增加可打开的文件数量(10240 是 MacOS 当前可打开的最大指针数量):
ulimit -n 10240
该库正在积极开发中,我们很高兴收到您的来信!请随意创建问题或提出拉取请求,其中包含您的问题、评论、建议和反馈。