콘텐츠로 이동

PHP 통합

내장된 cURL 라이브러리나 널리 사용되는 Guzzle HTTP 클라이언트를 사용하면 SMSBAT API를 PHP 애플리케이션에 통합하는 것이 간단합니다.

Guzzle HTTP 클라이언트 사용(권장)

먼저 Composer를 사용하여 Guzzle을 설치합니다.

composer require guzzlehttp/guzzle

그런 다음 다음 코드를 사용하여 메시지를 보냅니다.

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

$client = new Client([
    'base_uri' => 'https://api.smsbat.com',
    'timeout'  => 10.0,
]);

$apiKey = 'YOUR_API_KEY_HERE';

$payload = [
    'messages' => [
        [
            'from' => 'ALPHANAME',
            'to' => '380501234567',
            'text' => 'Hello from PHP and SMSBAT!',
            'type' => 'sms'
        ]
    ]
];

try {
    $response = $client->post('/bat/messagelist', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-Authorization-Key' => $apiKey
        ],
        'json' => $payload
    ]);

    echo "Status Code: " . $response->getStatusCode() . "\n";
    echo "Response: " . $response->getBody() . "\n";

} catch (RequestException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    if ($e->hasResponse()) {
        echo "Response: " . $e->getResponse()->getBody() . "\n";
    }
}

네이티브 cURL 사용

타사 패키지를 사용하지 않으려면 PHP의 기본 cURL 확장을 사용할 수 있습니다.

<?php

$url = 'https://api.smsbat.com/bat/messagelist';
$apiKey = 'YOUR_API_KEY_HERE';

$payload = json_encode([
    'messages' => [
        [
            'from' => 'ALPHANAME',
            'to' => '380501234567',
            'text' => 'Hello from PHP Native cURL!',
            'type' => 'sms'
        ]
    ]
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-Authorization-Key: ' . $apiKey
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
} else {
    echo "Status Code: $httpCode\n";
    echo "Response: $response\n";
}

curl_close($ch);