該函式庫要求 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
該庫正在積極開發中,我們很高興收到您的來信!請隨意建立問題或提出拉取請求,其中包含您的問題、評論、建議和回饋。