Important: While this package is largely compatible with PayTR’s official API documentation, there are a few differences in certain functions and parameters. In particular, the refund amount (pennies/decimal), BKM Express integration and basket encoding are explained in detail in their respective sections. Please review these notes carefully before integrating.

PayTR Laravel Client

A secure, modern and comprehensive PayTR payment integration package for Laravel projects.

Why use this documentation?

  • Up‑to‑date and comprehensive: All PayTR API functions, parameters, error handling and tests explained clearly in one place with examples.
  • Real‑world scenarios: Guidance not only for basic integration, but also for advanced needs like card storage, payment links, platform transfers and webhook verification.
  • Faster integration: Save time with common pitfalls, security tips and best practices.
  • Modern and user‑friendly: Dark mode, responsive layout, copyable code blocks and an easy navigation menu.
  • Test and security focused: Test coverage and error‑handling examples for all functions so you can verify your app before going live.
  • Community & open‑source: Use freely under the MIT licence, contribute or integrate into your own projects.
Whether you are just starting or building advanced flows, this documentation is designed to guide any Laravel project taking payments with PayTR.

  • ✔️ All PayTR API functions (payment, refund, card, link, platform, webhook)
  • 🛡️ Advanced security (HMAC, IP, SSL, signature, .env management)
  • ⚡ Simple setup & rapid integration
  • 🧪 100% test coverage with sample tests
  • 🌙 Dark mode and responsive documentation
  • MIT Licence fully open‑source
📄 Comprehensive documentation:
This page explains all package functions, parameters, error handling and tests in detail. Online: https://tugrulyildirim.com/opensource/paytr-laravel-client
PayTR Logo

Installation

  1. Install the package via Composer:
    composer require paytr/laravel-client
  2. The service provider is auto‑discovered. Add manually if needed:
    // config/app.php
    'providers' => [
        Paytr\PaytrServiceProvider::class,
    ],
  3. Publish the configuration file:
    php artisan vendor:publish --tag=paytr-config
  4. Add your PayTR credentials to .env:
    # PayTR Configuration
    PAYTR_MERCHANT_ID=your_merchant_id
    PAYTR_MERCHANT_KEY=your_merchant_key
    PAYTR_MERCHANT_SALT=your_merchant_salt
    PAYTR_SANDBOX=true
    PAYTR_DEBUG=true
    
    # API URLs
    PAYTR_API_URL=https://www.paytr.com/odeme/api/
    PAYTR_DIRECT_API_URL=https://www.paytr.com/odeme
    PAYTR_IFRAME_API_URL=https://www.paytr.com/odeme/api/get-token
    
    # Webhook settings
    PAYTR_WEBHOOK_SECRET=your_webhook_secret
    PAYTR_ALLOWED_IPS=
IMPORTANT: PAYTR_DIRECT_API_URL must be https://www.paytr.com/odeme. This URL is used for Direct API payments.

Usage

You can access PayTR services via the facade or using dependency injection. Examples:

// Facade ile payment start
use Paytr\Facades\Paytr;

$result = Paytr::payment()->pay($payload);
// Dependency Injection
public function __construct(Paytr\Services\PaymentService $paymentService) {
    $this->paymentService = $paymentService;
}

Direct API vs iFrame API

Feature Direct API iFrame API
Card Details Required (server‑side) Not required (entered on PayTR page)
3D Secure Automatic (redirect to bank page) Automatic (within iFrame)
Security High (processed on server) High (PayTR secure page)
Ease of Use Medium (collect card details) Easy (no card collection)
PCI DSS Required (card data processed) Not required (no card data processed)

Make a Payment (pay)

IMPORTANT: When using PayTR Direct API, card details are required. The Direct API processes card details server‑side and requires 3D Secure verification.

pay(array $payload): array function, allows you to start a payment with the PayTR Direct API. Direct API, processes card details server‑side and requires 3D Secure verification. All required and optional parameters, return values and error management are detailed below.

Parameters

INFO: The following parameters are automatically taken from config: merchant_id, user_ip, test_mode, debug_on, client_lang

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'token' => 'Payment token',
  // Other PayTR response fields
]

On failure, a PaytrException is thrown with an error message.

Example: Basic Payment (Direct API)

use Paytr\Facades\Paytr;

$payload = [
    // Required parameters (auto: merchant_id, user_ip, test_mode, debug_on, client_lang)
    'merchant_oid' => 'TEST_' . time(), // Unique order number
    'email' => 'user@example.com',
    'payment_amount' => 100.00, // Use decimal point
    'payment_type' => 'card',
    'installment_count' => 0,
    'currency' => 'TL',
    'non_3d' => 0,
    'request_exp_date' => date('Y-m-d H:i:s', strtotime('+1 hour')),

    // Customer information
    'user_name' => 'Test Customer',
    'user_address' => 'Adres',
    'user_phone' => '5551234567',

    // URLs (correct naming)
    'merchant_ok_url' => 'https://site.com/success',
    'merchant_fail_url' => 'https://site.com/fail',

    // Basket (PayTR format)
    'basket' => [
        ['Test Product', '100.00', 1], // [product_name, price, quantity]
    ],

    // Required card details for Direct API
        'cc_owner' => 'Test Customer',
    'card_number' => '4355084355084358', // Test card
    'expiry_month' => '12',
    'expiry_year' => '25',
    'cvv' => '000',

    // Optional parameters
    'lang' => 'tr',
    'sync_mode' => 0, // 0: async, 1: sync
    'non3d_test_failed' => 0,
    'card_type' => '', // Can be left blank
];

try {
    $result = Paytr::payment()->pay($payload);
    // $result['token'] ile payment start
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Example: Installment Payment

$payload['installment_count'] = 3; // 3 taksit
$result = Paytr::payment()->pay($payload);

Example: Payment with Different Currency

$payload['currency'] = 'USD';
$result = Paytr::payment()->pay($payload);

Error Handling

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->pay($payload);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Hata kodu: $e->getCode()
}

Notes

iFrame Payments (createIframeToken)

INFO: With the iFrame API, card details are not required. The customer enters card details on PayTR’s secure payment page.

createIframeToken(array $payload): array generates the token required to start a payment with the PayTR iFrame API. You can embed the iFrame form on your site using this token. Card details are provided by the customer on PayTR’s secure page.

Parameters

INFO: The following are taken automatically from config: merchant_id, user_ip, test_mode, debug_on, lang

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'token' => 'iFrame token',
  // Other PayTR response fields
]

On failure, a PaytrException is thrown with an error message.

Example: Create iFrame Token

use Paytr\Facades\Paytr;

$payload = [
        // Required parameters (auto: merchant_id, user_ip, test_mode, debug_on, lang)
    'merchant_oid' => 'TEST_' . time(), // Unique order number
    'email' => 'user@example.com',
    'payment_amount' => 100.00, // PayTR uses decimal point
    'currency' => 'TL',

    // Customer information
    'user_name' => 'Test Kullanıcı',
    'user_address' => 'Adres',
    'user_phone' => '5551234567',

    // URLs (correct naming)
    'merchant_ok_url' => 'https://site.com/success',
    'merchant_fail_url' => 'https://site.com/fail',

    // Basket (PayTR format)
    'basket' => [
        ['Test Ürün', '100.00', 1], // [product_name, price, quantity]
    ],

    // Optional parameters
    'no_installment' => 0, // Installment usage
    'max_installment' => 12, // Maximum 12 installments
    'timeout_limit' => 0, // Time limit
    // iFrame API does not require card details
];

try {
    $result = Paytr::payment()->createIframeToken($payload);
    // $result['token'] ile iFrame formu created
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Example: Integration of iFrame Form


Error Management

API or validation errors, PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->createIframeToken($payload);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Error code: $e->getCode()
}

Additional Notes

Query Payment Status (getPaymentStatus)

getPaymentStatus(string $merchantOid): array queries the payment status of the given order (merchant_oid) via the PayTR API.

Parameters

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'payment_status' => 'paid', // or 'pending', 'failed' etc.
  // Other PayTR response fields
]

On failure, a PaytrException is thrown with an error message.

Example: Query Payment Status

use Paytr\Facades\Paytr;

$merchantOid = 'ORDER123';

try {
    $result = Paytr::payment()->getPaymentStatus($merchantOid);
    if ($result['payment_status'] === 'paid') {
        // Payment successful
    } elseif ($result['payment_status'] === 'pending') {
        // Payment pending
    } else {
        // Payment failed or cancelled
    }
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Error Handling

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->getPaymentStatus($merchantOid);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Hata kodu: $e->getCode()
}

Notes

Query Instalment Rates (getInstallmentRates)

getInstallmentRates(string $bin): array queries instalment rates by the given card BIN (first 6 digits) via the PayTR API.

Parameters

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'installment_rates' => [
    ['count' => 1, 'rate' => 0],
    ['count' => 2, 'rate' => 1.5],
    // ...
  ],
  // Other PayTR response fields
]

On failure, a PaytrException is thrown with an error message.

Example: Query Instalment Rates

use Paytr\Facades\Paytr;

$bin = '454360';

try {
    $result = Paytr::payment()->getInstallmentRates($bin);
    foreach ($result['installment_rates'] as $rate) {
        echo $rate['count'] . ' taksit: ' . $rate['rate'] . "% oran\n";
    }
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Error Handling

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->getInstallmentRates($bin);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Hata kodu: $e->getCode()
}

Notes

BIN Lookup (lookupBin)

lookupBin(string $bin): array queries the issuing bank, card type and other details by the given BIN (first 6 digits) via the PayTR API.

Parameters

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'bank' => 'Bank Name',
  'card_type' => 'Credit Card',
  'brand' => 'Visa',
  // Other PayTR response fields
]

On failure, a PaytrException is thrown with an error message.

Example: BIN Lookup

use Paytr\Facades\Paytr;

$bin = '454360';

try {
    $result = Paytr::payment()->lookupBin($bin);
    echo 'Banka: ' . $result['bank'] . "\n";
    echo 'Kart Tipi: ' . $result['card_type'] . "\n";
    echo 'Marka: ' . $result['brand'] . "\n";
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Error Handling

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->lookupBin($bin);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Hata kodu: $e->getCode()
}

Notes

Query Transaction Detail (getTransactionDetail)

getTransactionDetail(string $merchantOid): array queries the transaction details for the given order (merchant_oid) via the PayTR API.

Parameters

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'transaction' => [
    'amount' => 10000,
    'status' => 'paid',
    'date' => '2024-01-01 12:00:00',
    // ... other transaction details
  ],
  // Diğer PayTR yanıt parametreleri
]

On failure, a PaytrException is thrown with an error message.

Example: Query Transaction Detail

use Paytr\Facades\Paytr;

$merchantOid = 'ORDER123';

try {
    $result = Paytr::payment()->getTransactionDetail($merchantOid);
    $transaction = $result['transaction'];
    echo 'Tutar: ' . $transaction['amount'] . "\n";
    echo 'Durum: ' . $transaction['status'] . "\n";
    echo 'Tarih: ' . $transaction['date'] . "\n";
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Error Handling

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->getTransactionDetail($merchantOid);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Hata kodu: $e->getCode()
}

Notes

Query Payment Statement (getPaymentStatement)

getPaymentStatement(array $payload): array fonksiyonu, belirli bir tarih aralığı için ödeme raporunu (statement) PayTR API üzerinden sorgular.

Parameters

Dönüş Değeri

On success, an array like below is returned:

[
  'status' => 'success',
  'payments' => [
    [
      'merchant_oid' => 'ORDER123',
      'amount' => 10000,
      'status' => 'paid',
      'date' => '2024-01-01 12:00:00',
      // ... other payment details
    ],
    // ...
  ],
  // Other PayTR response fields
]

On failure, a PaytrException is thrown with an error message.

Örnek: Ödeme Raporu Sorgulama

use Paytr\Facades\Paytr;

$payload = [
    'date_start' => '2024-01-01',
    'date_end' => '2024-01-31',
];

try {
    $result = Paytr::payment()->getPaymentStatement($payload);
    foreach ($result['payments'] as $payment) {
        echo $payment['merchant_oid'] . ': ' . $payment['amount'] . ' TL - ' . $payment['status'] . "\n";
    }
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Error Handling

API veya validasyon hatalarında PaytrException fırlatılır. Hata mesajı ve kodu exception üzerinden alınabilir.

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->getPaymentStatement($payload);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Hata kodu: $e->getCode()
}

Additional Notes

For API or validation errors, a PaytrException is thrown. You can read the message and code from the exception.

Query Payment Detail (getPaymentDetail)

getPaymentDetail(string $paymentId): array function queries the details of a specific payment ID via the PayTR API. PayTR API.

Parameters

Return Value

On success, an array like below is returned:

[
  'status' => 'success',
  'payment' => [
    'merchant_oid' => 'ORDER123',
    'amount' => 10000,
    'status' => 'paid',
    'date' => '2024-01-01 12:00:00',
    // ... other payment details
  ],
  // Other PayTR response parameters
]

On failure, a PaytrException is thrown with an error message.

Example: Query Payment Detail

use Paytr\Facades\Paytr;

$paymentId = '12345';

try {
    $result = Paytr::payment()->getPaymentDetail($paymentId);
    $payment = $result['payment'];
    echo 'Sipariş: ' . $payment['merchant_oid'] . "\n";
    echo 'Tutar: ' . $payment['amount'] . "\n";
    echo 'Durum: ' . $payment['status'] . "\n";
    echo 'Tarih: ' . $payment['date'] . "\n";
} catch (Paytr\Exceptions\PaytrException $e) {
            // Error management
    echo $e->getMessage();
}

Error Handling

API veya validation errors, PaytrException is thrown. You can read the message and code from the exception.

try {
    $result = Paytr::payment()->getPaymentDetail($paymentId);
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error message: $e->getMessage()
    // Error code: $e->getCode()
}

Additional Notes

Pre Provision (preProvision)

preProvision(array $payload): array function is used to start the pre-provision (pre-auth) process. It allows the provision to be taken before the amount is withdrawn from the card.

used to start the pre-provision (pre-auth) process. It allows the provision to be taken before the amount is withdrawn from the card.

Parameters

Return Value

[
  'status' => 'success',
  'token' => 'Provision token',
  // Other PayTR response fields
]

Example: Start Pre Provision Example: Start Pre Provision

$payload = [
    'merchant_oid' => 'ORDER123',
    'email' => 'user@example.com',
    'payment_amount' => 10000,
    'user_name' => 'Test User',
    'user_address' => 'Address',
    'user_phone' => '5551234567',
    'user_ip' => request()->ip(),
    'basket' => [
        ['name' => 'Ürün', 'price' => 10000, 'quantity' => 1],
    ],
];
$result = Paytr::payment()->preProvision($payload);

EFT iFrame (createEftIframe)

createEftIframe(array $payload): array function creates an iFrame token for EFT payment.

Parameters

Return Value

[
  'status' => 'success',
  'token' => 'EFT iFrame token',
  // Other PayTR response fields
]

Example: Create EFT iFrame Token

$payload = [
    'merchant_oid' => 'ORDER123',
    'email' => 'user@example.com',
    'payment_amount' => 10000,
    'user_name' => 'Test User',
    'user_address' => 'Address',
    'user_phone' => '5551234567',
    'user_ip' => request()->ip(),
    'basket' => [
        ['name' => 'Ürün', 'price' => 10000, 'quantity' => 1],
    ],
];
$result = Paytr::payment()->createEftIframe($payload);

Payment with BKM Express (payWithBkmExpress)

WARNING: This package uses a different endpoint for BKM Express payments from PayTR's official API. ayrı bir bkm/express endpoint'i kullanır. payment_type="bex" parametresi gerekmez. Entegrasyonun kolaylaştırılması için bu yol tercih edilmiştir.

payWithBkmExpress(array $payload): array function is used to start a payment with BKM Express. kullanılır.

Parameters

Return Value

[
  'status' => 'success',
  'token' => 'BKM Express token',
  // Other PayTR response fields
]

Example: Start Payment with BKM Express

$payload = [
    'merchant_oid' => 'ORDER123',
    'email' => 'user@example.com',
    'payment_amount' => 10000,
    'user_name' => 'Test User',
    'user_address' => 'Address',
    'user_phone' => '5551234567',
    'user_ip' => request()->ip(),
    'basket' => [
        ['name' => 'Ürün', 'price' => 10000, 'quantity' => 1],
    ],
];
$result = Paytr::payment()->payWithBkmExpress($payload);

Basket Encoding (encodeBasket)

encodeBasket(array $basket): string function encodes the basket data in the format expected by the PayTR API. kodlar.

PayTR Basket Format

INFO: The basket data must be sent in a special format in the PayTR API: [['Ürün Adı', 'Fiyat', 'Adet'], ...]
Not: encodeBasket method cannot be called directly. This method is protected defined and is usually automatically used by the package during payment operations.

Parameters

Return Value

Base64 encoded basket data is returned.

Example: Basket Encoding

Note: Basket encoding is automatically performed by the package during payment operations. If you want to use it in your own code, you can write a helper function like this:
// PayTR Basket Format: [['Ürün Adı', 'Fiyat', 'Adet'], ...]
$basket = [
    ['Test Product 1', '100.00', 1],     // [product_name, price, quantity]
    ['Test Product 2', '50.50', 2],      // [product_name, price, quantity]
    ['Test Ürün 3', '25.25', 3],      // [product_name, price, quantity]
];

function encodeBasket(array $basket): string {
    return base64_encode(json_encode($basket));
}

$encoded = encodeBasket($basket);

Supported Formats

// 1. PayTR Format (Recommended)
$basket = [
    ['Product Name', '100.00', 1],
];

// 2. Object Format (Automatically converted)
$basket = [
    ['name' => 'Product Name', 'price' => 100.00, 'quantity' => 1],
];

    // 3. Mixed Format
$basket = [
    ['Product 1', '100.00', 1],
    ['name' => 'Product 2', 'price' => 50.00, 'quantity' => 2],
];

Additional Notes

Refund (refund)

WARNING: This package handles refunds in cents (integer). So for 10 TL, you should write 1000. In PayTR's official API, the return_amount parameter is sent as a decimal point string (e.g. "10.00"). Please note this difference. decimal point string (e.g. "10.00") is sent. Please note this difference.

refund(string $merchantOid): array function starts a full refund for a payment.

Parameters

Return Value

[
  'status' => 'success',
  // Other PayTR response fields
]

Example: Full Refund

use Paytr\Facades\Paytr;

$merchantOid = 'ORDER123';

try {
    $result = Paytr::refund()->refund($merchantOid);
    // If the refund is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Partial Refund (partialRefund)

WARNING: This package handles partial refunds in cents (integer). So for 10 TL, you should write 1000. In PayTR's official API, the return_amount parameter is sent as a decimal point string (e.g. "10.00"). Please note this difference. decimal point string (e.g. "10.00") is sent. Please note this difference.

partialRefund(string $merchantOid, int $amount): array function starts a partial refund for a payment.

Parameters

Return Value

[
  'status' => 'success',
  // Other PayTR response fields
]

Example: Partial Refund

$merchantOid = 'ORDER123';
$amount = 5000; // 50 TL

try {
    $result = Paytr::refund()->partialRefund($merchantOid, $amount);
    // If the partial refund is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Refund Status Inquiry (getRefundStatus)

getRefundStatus(string $merchantOid): array function queries the current status of a refund operation. sorgular.

Parameters

Return Value

[
  'status' => 'success',
  'refund_status' => 'completed', // or 'pending', 'failed' etc.
  // Other PayTR response fields
]

Example: Refund Status Inquiry

$merchantOid = 'ORDER123';

try {
    $result = Paytr::refund()->getRefundStatus($merchantOid);
    if ($result['refund_status'] === 'completed') {
        // Refund completed
    } elseif ($result['refund_status'] === 'pending') {
        // Refund pending
    } else {
        // Refund failed or cancelled
    }
} catch (Paytr\Exceptions\PaytrException $e) {
        // Error management
    echo $e->getMessage();
}

Cancel (cancel)

cancel(string $merchantOid): array function starts a full cancellation for a payment.

Parameters

Return Value

[
  'status' => 'success',
  // Other PayTR response fields
]

Example: Full Cancel

use Paytr\Facades\Paytr;

$merchantOid = 'ORDER123';

try {
    $result = Paytr::cancel()->cancel($merchantOid);
    // If the cancel is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Partial Cancel (partialCancel)

partialCancel(string $merchantOid, int $amount): array function starts a partial cancellation for a payment.

Parameters

Return Value

[
  'status' => 'success',
  // Other PayTR response fields
]

Example: Partial Cancel

$merchantOid = 'ORDER123';
$amount = 5000; // 50 TL

try {
    $result = Paytr::cancel()->partialCancel($merchantOid, $amount);
    // If the partial cancel is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    // Error management
    echo $e->getMessage();
}

Store Card (storeCard)

storeCard(array $cardData): array function stores the user's card information in a secure way in the PayTR system.

Parameters

Return Value

[
  'status' => 'success',
  'token' => 'Card token',
  // Other PayTR response fields
]

Example: Store Card

$cardData = [
    'customer_id' => 'USER123',
    'cc_owner' => 'Test User',
    'card_number' => '4111111111111111',
    'expiry_month' => '12',
    'expiry_year' => '25',
    'cvv' => '123',
];

try {
    $result = Paytr::card()->storeCard($cardData);
    // $result['token'] ile stored card transactions can be performed
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Pay With Card (payWithCard)

payWithCard(string $token, array $paymentData): array function starts a payment with a stored card.

Parameters

Return Value

[
  'status' => 'success',
    // Other PayTR response fields
]

Example: Pay With Card

$token = 'CARD_TOKEN';
$paymentData = [
    'amount' => 10000,
    'merchant_oid' => 'ORDER123',
];

try {
    $result = Paytr::card()->payWithCard($token, $paymentData);
    // If the payment is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Recurring Payment (recurringPayment)

recurringPayment(string $token, array $paymentData): array function starts a recurring payment with a stored card.

Parameters

Return Value

[
  'status' => 'success',
  // Other PayTR response fields
]

Example: Recurring Payment

$token = 'CARD_TOKEN';
$paymentData = [
    'amount' => 10000,
    'merchant_oid' => 'ORDER123',
];

try {
    $result = Paytr::card()->recurringPayment($token, $paymentData);
    // If the payment is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

List Cards (listCards)

listCards(string $customerId): array function lists the stored cards for a user.

Parameters

Return Value

[
  'status' => 'success',
  'cards' => [
    [
      'token' => 'CARD_TOKEN',
      'cc_owner' => 'Test User',
      // ... other card information
    ],
    // ...
  ],
  // Other PayTR response fields
]

Example: List Cards

$customerId = 'USER123';

try {
    $result = Paytr::card()->listCards($customerId);
    foreach ($result['cards'] as $card) {
        echo $card['cc_owner'] . ' - ' . $card['token'] . "\n";
    }
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Delete Card (deleteCard)

deleteCard(string $token): array function deletes a stored card.

Parameters

Return Value

[
  'status' => 'success',
// Other PayTR response fields
]

Example: Delete Card

$token = 'CARD_TOKEN';

try {
    $result = Paytr::card()->deleteCard($token);
    // If the deletion is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Services

The library provides the following main services:

Example: Start payment with iFrame

$payload = [
    'merchant_oid' => 'ORDER123',
    'email' => 'user@example.com',
    'amount' => 10000,
        'user_name' => 'Test User',
    'user_address' => 'Address',
    'user_phone' => '5551234567',
    'ok_url' => 'https://site.com/success',
    'fail_url' => 'https://site.com/fail',
    'basket' => [
        ['name' => 'Product', 'price' => 10000, 'quantity' => 1],
    ],
];
$result = Paytr::payment()->createIframeToken($payload);

Example: Refund

$result = Paytr::refund()->refund('ORDER123');

Events

// Event listening example
Event::listen(Paytr\Events\PaymentSuccessEvent::class, function($event) {
    // You can access the event details with $event->data
});

Middleware

paytr.signature middleware verifies the signature of the webhook endpoints.

Route::post('/webhook', [WebhookController::class, 'handle'])
    ->middleware('paytr.signature');

Tests

The library is thoroughly tested with unit and feature tests. Tests cover all critical points, from event data transfer to service signature generation and middleware verification.

Create Platform Transfer (createTransfer)

createTransfer(array $payload): array function creates a transfer request on the platform.

Parameters

Return Value

[
  'status' => 'success',
  'transfer_id' => 'TRF123',
  // Other PayTR response fields
]

Example: Create Platform Transfer

$payload = [
    'amount' => 10000,
    'iban' => 'TR000000000000000000000000',
    'description' => 'Description',
];

try {
    $result = Paytr::platform()->createTransfer($payload);
    // $result['transfer_id'] ile transfer işlemi takip edilebilir
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Platform Transfer Result (getTransferResult)

getTransferResult(string $transferId): array function queries the result of a platform transfer.

Parameters

Return Value

[
  'status' => 'success',
  'result' => 'completed', // veya 'pending', 'failed' vb.
  // Other PayTR response fields
]

Example: Platform Transfer Result Query

$transferId = 'TRF123';

try {
    $result = Paytr::platform()->getTransferResult($transferId);
    if ($result['result'] === 'completed') {
        // Transfer completed
    } elseif ($result['result'] === 'pending') {
        // Transfer pending
    } else {
        // Transfer failed
    }
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Platform Refund List (getReturningPayments)

getReturningPayments(array $payload): array function lists payments refunded within a specific date range.

Parameters

Return Value

[
  'status' => 'success',
  'returning_payments' => [
    [
      'trans_id' => 'TRS123',
      'amount' => 10000,
      'iban' => 'TR000000000000000000000000',
        // ... other information
    ],
    // ...
  ],
  // Other PayTR response fields
]

Example: Platform Refund List Query

$payload = [
    'date_start' => '2024-01-01',
    'date_end' => '2024-01-31',
];

try {
    $result = Paytr::platform()->getReturningPayments($payload);
    foreach ($result['returning_payments'] as $payment) {
        echo $payment['trans_id'] . ': ' . $payment['amount'] . "\n";
    }
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Platform Refund Send (sendReturningPayment)

sendReturningPayment(array $payload): array function sends a refund payment from the account.

Parameters

Return Value

[
  'status' => 'success',
  // Other PayTR response fields
]

Example: Platform Refund Send

$payload = [
    'trans_id' => 'TRS123',
    'amount' => 10000,
    'iban' => 'TR000000000000000000000000',
    'name' => 'Receiver Name',
];

try {
    $result = Paytr::platform()->sendReturningPayment($payload);
    // If the refund is successful, $result['status'] == 'success'
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Platform Callback Handle (handleReturningCallback)

handleReturningCallback(array $payload): array function handles and verifies the incoming refund notification.

Parameters

Return Value

$result = Paytr::platform()->handleReturningCallback($payload);
// $result: refunded transactions array

Example: Callback Handling

$payload = [...];

try {
    $result = Paytr::platform()->handleReturningCallback($payload);
        // $result can be processed with the refunded transactions
} catch (Paytr\Exceptions\PaytrException $e) {
    echo $e->getMessage();
}

Platform Callback Verification (verifyCallback)

verifyCallback(array $payload, string $signature): bool function verifies the signature of a platform transfer callback request.

Parameters

Return Value

$isValid = Paytr::platform()->verifyCallback($payload, $signature);
// $isValid: true or false

Example: Callback Verification

$payload = [...];
$signature = $_SERVER['HTTP_X_PAYTR_SIGNATURE'] ?? '';

$isValid = Paytr::platform()->verifyCallback($payload, $signature);
if ($isValid) {
    // Callback valid
} else {
    // Invalid signature
}

PaymentSuccessEvent

Event triggered when a successful payment transaction occurs.

Tetiklenme Durumu

Veri Yapısı

$event->data = [
  'event' => 'payment_success',
  'merchant_oid' => 'ORDER123',
  'amount' => 10000,
    // ... other fields
];

Example: Event Listening

Event::listen(Paytr\Events\PaymentSuccessEvent::class, function($event) {
    // You can access the transaction details with $event->data
});

PaymentFailedEvent

Event triggered when a failed payment transaction occurs.

Tetiklenme Durumu

Data Structure

$event->data = [
  'event' => 'payment_failed',
  'merchant_oid' => 'ORDER123',
  'reason' => 'Insufficient funds',
  // ... other fields
];

Example: Event Listening

Event::listen(Paytr\Events\PaymentFailedEvent::class, function($event) {
    // You can access the error details with $event->data
});

RefundSuccessEvent

Event triggered when a successful refund transaction occurs.

Triggering Status

Data Structure

$event->data = [
  'event' => 'refund_success',
  'merchant_oid' => 'ORDER123',
  'refund_amount' => 5000,
  // ... other fields
];

Example: Event Listening

Event::listen(Paytr\Events\RefundSuccessEvent::class, function($event) {
    // You can access the refund details with $event->data
});

paytr.signature Middleware

Middleware that verifies the signature of incoming requests to webhook endpoints.

Usage

Route::post('/webhook', [WebhookController::class, 'handle'])
    ->middleware('paytr.signature');

Working Principle

Example: Invalid Signature

curl -X POST /webhook -H "X-PayTR-Signature: yanlis" -d '{...}'

WebhookController

Handles webhook notifications sent by PayTR. Performs IP and signature validation, and triggers the appropriate event. event is triggered. tetikler.

Example Route

Route::post('/webhook', [WebhookController::class, 'handle'])
    ->middleware('paytr.signature');

Working Principle

Example: Webhook Payload

{
  "event": "payment_success",
  "merchant_oid": "ORDER123",
  "amount": 10000,
  // ... other fields
}

Tests (Detailed)

The library is thoroughly tested with unit and feature tests. The purpose, scope, and example assertions are summarized below.

The library is thoroughly tested with unit and feature tests. The purpose, scope, and example assertions are summarized below.

Example: Test Assertion

$this->assertEquals($data, $event->data);
$response->assertStatus(500);
$this->assertArrayHasKey('paytr_token', $params);