
이 라이브러리를 사용하면 최신 PHP7 및 OOP 구조를 사용하여 프로젝트에서 GatewayApi.com API를 통합 할 수 있습니다. API, 오류 코드 등에 대한 전체 설명은 https://gatewayapi.com/docs를 참조하십시오.
이 라이브러리를 사용하려면 https://www.gatewayapi.com에서 활성 계정이 필요합니다. 일단 있으면 API- > API 키 에서 API 키/비밀 쌍을 생성해야합니다.
프로젝트에 포함 시키려면 작곡가를 사용하여 설치하십시오.
이 라이브러리에는 PHP> = 7.1이 필요하며 8.0, 8.1 및 8.2에서 작동합니다.
composer require nickdnk/gatewayapi-php
use nickdnk GatewayAPI GatewayAPIHandler ;
use nickdnk GatewayAPI Entities Request Recipient ;
use nickdnk GatewayAPI Entities Request SMSMessage ;
// Pass `true` as the third parameter to use GatewayAPI in EU-only mode.
// This requires an EU account. See https://gatewayapi.com/blog/new-eu-setup-for-gatewayapi-customers/.
$ handler = new GatewayAPIHandler ( ' my_key ' , ' my_secret ' , false );
$ message1 = new SMSMessage (
// The message you want to send. Include any placeholder tag strings.
' Hello, %FIRSTNAME%! Your code is: %CODE%. ' ,
// The name of the sender as seen by the recipient.
// 1-11 ASCII characters, spaces are removed.
' MyService ' ,
// An array containing the recipient(s) you want to send the message
// to. You can also pass an empty array and add recipients later on.
// See the example below the constructor.
[ new Recipient ( 4512345678 , [ ' John ' , ' 23523 ' ])],
// Arbitrary label added to your message(s).
// Pass null if you don't need this.
' customer1 ' ,
// The strings to replace in your message with tag values for each
// recipient. Pass an empty array if you don't use tags in your message.
[ ' %FIRSTNAME% ' , ' %CODE% ' ],
// The UNIX timestamp for when you want your message to be sent.
// Pass null to send immediately. This should *not* be less than
// the current UNIX time. This example sends in 1 hour.
time () + 3600 ,
// The message class to use. Note that prices vary. The secret class
// requires approval by GatewayAPI on your account before you can use
// it, otherwise you will get an error.
SMSMessage:: CLASS_STANDARD
);
// If you prefer a shorter constructor, you can use the default values
// and set your parameters after construction.
$ message2 = new SMSMessage ( ' Hello %NAME%! Your code is: %CODE% ' , ' MyService ' );
$ message2 -> setSendTime ( time () + 3600 );
$ message2 -> setClass (SMSMessage:: CLASS_PREMIUM );
$ message2 -> setUserReference ( ' customer1 ' );
$ message2 -> setTags ([ ' %NAME% ' , ' %CODE% ' ]);
$ message2 -> setCallbackUrl ( ' https://example.com/callback ' );
$ message2 -> addRecipient ( new Recipient ( 4587652222 , [ ' Martha ' , ' 42442 ' ]));
try {
// Note that a single SMSMessage must not contain more than 10,000
// recipients. If you want to send to more than 10,000 you should split
// your recipients into several SMSMessages. You can, however, send
// multiple SMSMessages in a single request.
$ result = $ handler -> deliverMessages (
[
$ message1 ,
$ message2
]
);
// All message IDs returned.
$ result -> getMessageIds ();
// The total cost of this request (all message IDs combined).
$ result -> getTotalCost ();
// Currency you were charged in.
$ result -> getCurrency ();
// The number of messages sent. For a message that's 3 SMSes long
// with 1000 recipients, this will be 3000.
$ totalMessagesSent = $ result -> getTotalSMSCount ();
// Messages sent to UK only.
$ ukMessages = isset ( $ result -> getCountries ()[ ' UK ' ])
? $ result -> getCountries ()[ ' UK ' ]
: 0 ;
} catch ( nickdnk GatewayAPI Exceptions InsufficientFundsException $ e ) {
/**
* Extends GatewayRequestException.
*
* Your account has insufficient funds and you cannot send the
* message(s) before you buy more credits at gatewayapi.com.
*
* The request body can be retried after you top up your balance.
*/
} catch ( nickdnk GatewayAPI Exceptions MessageException $ e ) {
/**
* Extends GatewayRequestException.
*
* This should not happen if you properly use the library and pass
* correct data into the functions, but it indicates that whatever
* you're doing is not allowed by GatewayAPI.
*
* It can happen if you add the same phone number (recipient) twice
* to an SMSMessage or if you don't use the tags function correctly,
* such as not providing a tag value for a recipient within a message
* that has a defined set of tags, or if you provide a tag value as
* an integer.
*
* To add the same phone number twice to one request it must be in
* different SMSMessage objects.
*
* Requests that throw this exception should *not* be retried!
*/
// The error code (may be null)
$ e -> getGatewayAPIErrorCode ();
// Error message, if present.
$ e -> getMessage ();
// Full response.
$ e -> getResponse ()-> getBody ();
} catch ( nickdnk GatewayAPI Exceptions SuccessfulResponseParsingException $ e ) {
/**
* Extends GatewayRequestException.
*
* If you implement automatic retries of failed requests, you should
* check for this exception. It is unlikely to ever occur, but it
* could happen if GatewayAPI changed their API or there was an error
* in the library. This could potentially trigger retries for requests
* that succeeded which would be expensive as well as problematic
* for recipients.
*/
// Error message.
$ e -> getMessage ();
// Full response.
$ e -> getResponse ()-> getBody ();
} catch ( nickdnk GatewayAPI Exceptions UnauthorizedException $ e ) {
/**
* Extends GatewayRequestException.
*
* Something is wrong with your credentials or your IP is
* banned. Make sure you API key and secret are valid or contact
* customer support.
*
* The request body can be retried if you provide different
* credentials (or fix whatever is wrong).
*/
// The error code (may be null)
$ e -> getGatewayAPIErrorCode ();
// Error message, if present.
$ e -> getMessage ();
// Full response.
$ e -> getResponse ()-> getBody ();
} catch ( nickdnk GatewayAPI Exceptions GatewayServerException $ e ) {
/**
* Extends GatewayRequestException.
*
* Something is wrong with GatewayAPI.com. This exception simply
* extends GatewayRequestException but only applies to 500-range
* errors.
*
* The request body can (most likely) be retried.
*/
// The error code (may be null)
$ e -> getGatewayAPIErrorCode ();
// Error message.
$ e -> getMessage ();
// Full response.
$ e -> getResponse ()-> getBody ();
} catch ( nickdnk GatewayAPI Exceptions ConnectionException $ e ) {
/**
* Connection to GatewayAPI failed or timed out. Try again or
* check their server status at https://status.gatewayapi.com/
*
* The request can/should be retried. This library does not
* automatically retry requests that fail for this reason.
*/
// Error message.
$ e -> getMessage ();
} catch ( nickdnk GatewayAPI Exceptions BaseException $ e ) {
/**
* Something else is wrong.
* All exceptions inherit from this one, so you can catch this error
* to handle all errors the same way or implement your own error
* handler based on the error code. Remember to check for nulls.
*
* This exception is abstract, so you can check which class it is
* and go from there.
*/
// Error message.
$ e -> getMessage ();
if ( $ e instanceof nickdnk GatewayAPI Exceptions GatewayServerException) {
// The error code (may be null).
$ e -> getGatewayAPIErrorCode ();
$ response = $ e -> getResponse ();
$ response -> getBody ();
$ response -> getStatusCode ();
}
} 보낼 때 반환 된 ID에 따라 예정된 SMS를 취소 할 수 있습니다. 이 메소드는 요청 풀 (메시지 ID 당 1 개)을 생성하므로 예외를 던지지 않지만 CancelResult 배열을 반환합니다. 이들 각각에는 상태가 포함되며 (실패한 경우) 요청의 예외.
use nickdnk GatewayAPI Entities CancelResult ;
use nickdnk GatewayAPI GatewayAPIHandler ;
$ handler = new GatewayAPIHandler ( ' my_key ' , ' my_secret ' );
$ results = $ handler -> cancelScheduledMessages ([ 1757284 , 1757288 ]);
foreach ( $ results as $ cancelResult ) {
// The ID of the canceled message is always available.
$ cancelResult -> getMessageId ();
if ( $ cancelResult -> getStatus () === CancelResult:: STATUS_SUCCEEDED ) {
// Success. Obviously.
} elseif ( $ cancelResult -> getStatus () === CancelResult:: STATUS_FAILED ) {
// Get the exception of a failed request.
$ cancelResult -> getException ();
}
} Webhook 클래스를 사용하여 GatewayApi에서 서버로 전송 된 WebHooks를 쉽게 구문 분석 할 수 있습니다. 이것은 JWT 헤더를 사용하여 Webhook이 변조되지 않았으며 실제로 신뢰할 수있는 소스에서 나오는지 확인합니다.
WebHooks를 설정하려면 API- > 웹 후크 -> REST 로 이동하십시오. WebHook을 만든 후 인증중인 JWT 비밀을 지정하십시오.
두 가지 유형의 webhooks를 보낼 수 있습니다. 배송 상태 알림 및 들어오는 메시지 (MO 트래픽). 둘 다 Webhook 에 의해 구문 분석되어 해당 클래스로 돌아 왔습니다. 들어오는 메시지를 읽으려면 구독 하의 키워드 또는 숫자를 구독하고 키워드 / 번호 를 구독하고 키워드 또는 번호를 Webhook에 할당해야합니다.
use nickdnk GatewayAPI Entities Webhooks DeliveryStatusWebhook ;
use nickdnk GatewayAPI Entities Webhooks IncomingMessageWebhook ;
use nickdnk GatewayAPI Entities Webhooks Webhook ;
use Psr Http Message RequestInterface ;
use Psr Http Message ResponseInterface ;
/**
* The webhook parser is based on PSR-7 allowing you to pass a $request
* object directly into the class and get a webhook back.
*/
function ( RequestInterface $ request , ResponseInterface $ response ) {
try {
$ webhook = Webhook:: constructFromRequest ( $ request , ' my_jwt_secret ' );
// Determine the type of webhook if you don't already know.
if ( $ webhook instanceof DeliveryStatusWebhook) {
$ webhook -> getPhoneNumber ();
$ webhook -> getStatus ();
} elseif ( $ webhook instanceof IncomingMessageWebhook) {
$ webhook -> getPhoneNumber ();
$ webhook -> getWebhookLabel ();
$ webhook -> getMessageText ();
}
} catch ( nickdnk GatewayAPI Exceptions WebhookException $ exception ) {
// Something is wrong with the webhook or it was not correctly
// signed. Take a look at your configuration.
$ exception -> getMessage ();
}
}
/**
* Or if you don't have a PSR-7 request handy, you can pass the JWT
* directly into this method instead. Note that the JWT contains
* the entire payload, which is duplicated unsigned in the body of the
* request. We don't read the request body at all.
*/
// JWT as a string, read from where-ever:
$ jwt = ' eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ' ;
try {
$ webhook = Webhook:: constructFromJWT ( $ jwt , ' my_jwt_secret ' );
} catch ( nickdnk GatewayAPI Exceptions WebhookException $ exception ) {
$ exception -> getMessage ();
} SMSMessage 및 Recipient API로 전송 된 실제 JSON으로 인코딩됩니다. 이 출력을 대기열에 넣거나 유사한 것들에 넣고 나중에 PHP 객체로 다시 원한다면이 방법을 사용하여 그렇게 할 수 있습니다.
use nickdnk GatewayAPI Entities Request Recipient ;
use nickdnk GatewayAPI Entities Request SMSMessage ;
$ recipient = new Recipient ( 4587652222 , [ ' Martha ' , ' 42442 ' ]);
$ json = json_encode ( $ recipient );
$ recipient = Recipient:: constructFromJSON ( $ json );
$ message = new SMSMessage ( ' Hello %NAME%! Your code is: %CODE% ' , ' MyService ' );
$ message -> setSendTime ( time () + 3600 );
$ message -> setUserReference ( ' reference ' );
$ message -> setTags ([ ' %NAME% ' , ' %CODE% ' ]);
$ message -> addRecipient ( $ recipient );
$ json = json_encode ( $ message );
$ smsMessage = SMSMessage:: constructFromJSON ( $ json );
$ smsMessage -> getMessage ();
$ smsMessage -> getRecipients (); 자격 증명이 필요하지 않은 단위 테스트를 실행하려면 프로젝트의 루트에서 vendor/bin/phpunit 실행하십시오.
API와 상호 작용하는 부분을 테스트하려면 GatewayAPIHandlerTest.php 에서 자격 증명을 제공하고 위 명령을 실행해야합니다. 이것은 라이브 SMS를 발송하며 실행 당 크레딧 1 SMS 비용이 소요됩니다.
[email protected]으로 저에게 연락 할 수 있습니다.
이 라이브러리를 자신의 위험으로 사용하십시오. PR은 환영합니다 :)