Skip to content

ตัวอย่าง PHP

ตัวอย่างโค้ด PHP สำหรับใช้งาน EasySlip API

ความต้องการ

  • PHP 7.4+
  • cURL extension

ตัวอย่างพื้นฐาน

ตรวจสอบด้วย Payload

php
<?php

function verifySlip(string $payload, bool $checkDuplicate = false): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://developer.easyslip.com/api/v1/verify',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'payload' => $payload,
            'checkDuplicate' => $checkDuplicate
        ])
    ]);

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

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

// การใช้งาน
try {
    $slip = verifySlip('00020101021230...');
    echo "จำนวนเงิน: " . $slip['amount']['amount'] . "\n";
    echo "ผู้โอน: " . $slip['sender']['displayName'] . "\n";
    echo "ผู้รับ: " . $slip['receiver']['displayName'] . "\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

ตรวจสอบด้วยรูปภาพ

php
<?php

function verifySlipImage(string $filePath, bool $checkDuplicate = false): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    if (!file_exists($filePath)) {
        throw new Exception('ไม่พบไฟล์');
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://developer.easyslip.com/api/v1/verify',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey
        ],
        CURLOPT_POSTFIELDS => [
            'file' => new CURLFile($filePath),
            'checkDuplicate' => $checkDuplicate ? 'true' : 'false'
        ]
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

// การใช้งาน
$slip = verifySlipImage('/path/to/slip.jpg', true);
echo "จำนวนเงิน: " . $slip['amount']['amount'] . "\n";

ตรวจสอบด้วย Base64

php
<?php

function verifySlipBase64(string $base64Image, bool $checkDuplicate = false): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://developer.easyslip.com/api/v1/verify',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'image' => $base64Image,
            'checkDuplicate' => $checkDuplicate
        ])
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

// การใช้งาน - แปลงไฟล์เป็น Base64
$imageData = base64_encode(file_get_contents('/path/to/slip.jpg'));
$base64Image = 'data:image/jpeg;base64,' . $imageData;
$slip = verifySlipBase64($base64Image, true);

ตรวจสอบด้วย URL

php
<?php

function verifySlipUrl(string $url, bool $checkDuplicate = false): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://developer.easyslip.com/api/v1/verify',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'url' => $url,
            'checkDuplicate' => $checkDuplicate
        ])
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

// การใช้งาน
$slip = verifySlipUrl('https://example.com/slips/slip.jpg', true);

API v2

ตรวจสอบสลิปธนาคาร (v2)

php
<?php

function verifySlipV2(string $payload, array $options = []): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    $body = array_merge(['payload' => $payload], $options);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://api.easyslip.com/v2/verify/bank',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode($body)
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

// การใช้งานกับ account matching
$slip = verifySlipV2('00020101021230...', [
    'receiverAccount' => '1234567890',
    'amount' => 1000.00
]);

if ($slip['receiver']['account']['match']) {
    echo "บัญชีผู้รับตรงกัน!\n";
}

if ($slip['amount']['match']) {
    echo "จำนวนเงินตรงกัน!\n";
}

ข้อมูลบัญชี (v2)

php
<?php

function getAccountInfoV2(): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://api.easyslip.com/v2/info',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey
        ]
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

$info = getAccountInfoV2();
echo "โควต้าคงเหลือ: " . $info['quota']['remaining'] . "\n";

สร้าง QR Code (v1)

php
<?php

function generateQR(array $config): array
{
    $apiKey = getenv('EASYSLIP_API_KEY');

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://developer.easyslip.com/api/v1/qr/generate',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode($config)
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($result['status'] !== 200) {
        throw new Exception($result['message']);
    }

    return $result['data'];
}

// สร้าง PromptPay QR
$qr = generateQR([
    'type' => 'PROMPTPAY',
    'msisdn' => '0812345678',
    'amount' => 100.00
]);

// บันทึกเป็นไฟล์
$imageData = base64_decode($qr['image']);
file_put_contents('qr-code.png', $imageData);

// หรือแสดงในหน้าเว็บ
echo '<img src="data:' . $qr['mime'] . ';base64,' . $qr['image'] . '">';

EasySlip Client Class

php
<?php

class EasySlipClient
{
    private string $apiKey;
    private string $baseUrl;

    public function __construct(string $apiKey, string $version = 'v1')
    {
        $this->apiKey = $apiKey;
        $this->baseUrl = "https://developer.easyslip.com/api/{$version}";
    }

    private function request(string $endpoint, array $options = []): array
    {
        $ch = curl_init();

        $curlOptions = [
            CURLOPT_URL => $this->baseUrl . $endpoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->apiKey
            ]
        ];

        if (isset($options['method']) && $options['method'] === 'POST') {
            $curlOptions[CURLOPT_POST] = true;
        }

        if (isset($options['json'])) {
            $curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
            $curlOptions[CURLOPT_POSTFIELDS] = json_encode($options['json']);
        }

        if (isset($options['formData'])) {
            $curlOptions[CURLOPT_POSTFIELDS] = $options['formData'];
        }

        curl_setopt_array($ch, $curlOptions);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new Exception('cURL Error: ' . $error);
        }

        $result = json_decode($response, true);

        if ($result['status'] !== 200) {
            throw new EasySlipException($result['message'], $result['status'], $result['data'] ?? null);
        }

        return $result['data'];
    }

    public function verifyByPayload(string $payload, bool $checkDuplicate = false): array
    {
        return $this->request('/verify', [
            'method' => 'POST',
            'json' => [
                'payload' => $payload,
                'checkDuplicate' => $checkDuplicate
            ]
        ]);
    }

    public function verifyByImage(string $filePath, bool $checkDuplicate = false): array
    {
        return $this->request('/verify', [
            'method' => 'POST',
            'formData' => [
                'file' => new CURLFile($filePath),
                'checkDuplicate' => $checkDuplicate ? 'true' : 'false'
            ]
        ]);
    }

    public function verifyByUrl(string $url, bool $checkDuplicate = false): array
    {
        return $this->request('/verify', [
            'method' => 'POST',
            'json' => [
                'url' => $url,
                'checkDuplicate' => $checkDuplicate
            ]
        ]);
    }

    public function verifyByBase64(string $image, bool $checkDuplicate = false): array
    {
        return $this->request('/verify', [
            'method' => 'POST',
            'json' => [
                'image' => $image,
                'checkDuplicate' => $checkDuplicate
            ]
        ]);
    }

    public function generateQR(array $config): array
    {
        return $this->request('/qr/generate', [
            'method' => 'POST',
            'json' => $config
        ]);
    }

    public function getAccountInfo(): array
    {
        return $this->request('/me');
    }
}

class EasySlipException extends Exception
{
    public ?array $data;

    public function __construct(string $message, int $code, ?array $data = null)
    {
        parent::__construct($message, $code);
        $this->data = $data;
    }
}

// การใช้งาน
$client = new EasySlipClient(getenv('EASYSLIP_API_KEY'));

try {
    $slip = $client->verifyByPayload('00020101021230...');
    echo "จำนวนเงิน: " . $slip['amount']['amount'] . "\n";
} catch (EasySlipException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    if ($e->data) {
        print_r($e->data);
    }
}

Laravel Integration

Service Provider

php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\EasySlipClient;

class EasySlipServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(EasySlipClient::class, function ($app) {
            return new EasySlipClient(config('services.easyslip.api_key'));
        });
    }
}

Controller

php
<?php

namespace App\Http\Controllers;

use App\Services\EasySlipClient;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function __construct(
        private EasySlipClient $easySlip
    ) {}

    public function verifySlip(Request $request)
    {
        $request->validate([
            'file' => 'required|image|max:4096'
        ]);

        try {
            $slip = $this->easySlip->verifyByImage(
                $request->file('file')->path(),
                true
            );

            return response()->json([
                'success' => true,
                'data' => $slip
            ]);
        } catch (EasySlipException $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }
}

จัดการ Error

php
<?php

function verifyWithErrorHandling(string $payload): array
{
    try {
        $slip = verifySlip($payload);
        return ['success' => true, 'data' => $slip];
    } catch (Exception $e) {
        $errorMessages = [
            'invalid_payload' => 'Payload ไม่ถูกต้อง',
            'slip_not_found' => 'ไม่พบสลิป',
            'quota_exceeded' => 'โควต้าหมด',
            'duplicate_slip' => 'สลิปซ้ำ',
            'unauthorized' => 'API Key ไม่ถูกต้อง'
        ];

        $message = $errorMessages[$e->getMessage()] ?? $e->getMessage();

        return ['success' => false, 'error' => $message];
    }
}

ที่เกี่ยวข้อง

Bank Slip Verification API for Thai Banking