### Example Payment Configuration File
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
This example shows the structure of the `config/payment.php` file, including default driver and driver-specific configurations for Zarinpal, Jibit, and Payfa.
```php
env('PAYMENT_DEFAULT_DRIVER', 'zarinpal'),
/*
|--------------------------------------------------------------------------
| Payment Drivers
|--------------------------------------------------------------------------
|
| Here you may configure all the payment drivers used by your application.
| Each driver must have at least a merchantId and callbackUrl configured.
|
*/
'drivers' => [
'zarinpal' => [
'merchantId' => env('ZARINPAL_MERCHANT_ID'),
'callbackUrl' => env('ZARINPAL_CALLBACK_URL', 'http://localhost:8000/payment/verify'),
'description' => 'Payment for ' . config('app.name'),
],
'jibit' => [
'merchantId' => env('JIBIT_MERCHANT_ID'),
'callbackUrl' => env('JIBIT_CALLBACK_URL'),
'apiKey' => env('JIBIT_API_KEY'),
],
'payfa' => [
'merchantId' => env('PAYFA_MERCHANT_ID'),
'callbackUrl' => env('PAYFA_CALLBACK_URL'),
],
// Additional drivers...
],
];
```
--------------------------------
### Example .env Configuration
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
Define default payment driver and credentials for various payment gateways in your .env file.
```env
# Default payment driver
PAYMENT_DEFAULT_DRIVER=zarinpal
# Zarinpal credentials
ZARINPAL_MERCHANT_ID=your-merchant-id-here
ZARINPAL_CALLBACK_URL=https://yourapp.com/payment/verify
# Jibit credentials
JIBIT_MERCHANT_ID=your-merchant-id
JIBIT_CALLBACK_URL=https://yourapp.com/payment/jibit/verify
JIBIT_API_KEY=your-api-key
# Payfa credentials
PAYFA_MERCHANT_ID=your-merchant-id
PAYFA_CALLBACK_URL=https://yourapp.com/payment/payfa/verify
```
--------------------------------
### Install Shetabit Payment Package
Source: https://github.com/shetabit/payment/blob/master/_autodocs/index.md
Install the package using Composer. Publish configuration and optional views using Artisan commands.
```bash
composer require shetabit/payment
```
```bash
php artisan vendor:publish --tag=payment-config
```
```bash
php artisan vendor:publish --tag=payment-views
```
--------------------------------
### Complete Invoice Example with Purchase
Source: https://github.com/shetabit/payment/blob/master/_autodocs/invoices.md
Demonstrates how to create a detailed invoice, set payment details, and initiate a purchase with a callback to store transaction information.
```php
use Shetabit\Multipay\Invoice;
use Shetabit\Payment\Facade\Payment;
// Create and configure invoice
$invoice = (new Invoice)
->uuid('INV-' . now()->timestamp)
->amount(50000)
->detail('orderId', 'ORD-001')
->detail('customerId', 'CUST-123')
->detail('product', 'Premium Plan')
->via('zarinpal');
// Purchase the invoice
Payment::purchase($invoice, function($driver, $transactionId) {
// Store transaction details
DB::table('payments')->insert([
'invoice_uuid' => $invoice->getUuid(),
'transaction_id' => $transactionId,
'amount' => $invoice->getAmount(),
'driver' => $driver->getName(),
'order_id' => $invoice->getDetail('orderId'),
'status' => 'pending'
]);
});
```
--------------------------------
### Install Shetabit Payment Package
Source: https://github.com/shetabit/payment/blob/master/_autodocs/README.md
Install the package using Composer. Then, publish the configuration file to your Laravel project.
```bash
composer require shetabit/payment
php artisan vendor:publish --tag=payment-config
```
--------------------------------
### Default Payment Configuration Structure
Source: https://github.com/shetabit/payment/blob/master/_autodocs/service-provider.md
Example structure of the `config/payment.php` file, showing default driver settings and environment variable usage for credentials.
```php
return [
'default' => 'zarinpal', // Default driver to use
'drivers' => [
'zarinpal' => [
'apiPurchaseUrl' => 'https://...',
'apiPaymentUrl' => 'https://...',
'apiVerificationUrl' => 'https://...',
'merchantId' => env('ZARINPAL_MERCHANT_ID'),
'callbackUrl' => 'https://yourapp.com/payment/callback',
// ... other driver-specific settings
],
// Additional drivers...
]
];
```
--------------------------------
### Configuration Merging Example
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
Illustrates how the service provider merges the default package configuration with the user's `config/payment.php` file. User configurations and environment variables take precedence.
```php
// In PaymentServiceProvider::register()
$this->mergeConfigFrom(Payment::getDefaultConfigPath(), 'payment');
// User's config/payment.php overrides these defaults
```
--------------------------------
### Invoice with Default Values
Source: https://github.com/shetabit/payment/blob/master/_autodocs/invoices.md
Example of creating an invoice and setting default details such as a unique identifier, timestamp, and IP address.
```php
$invoice = (new Invoice)
->amount(50000)
->uuid(uniqid('inv_'))
->detail('timestamp', now()->timestamp)
->detail('ipAddress', request()->ip());
```
--------------------------------
### Create New Invoice Instance
Source: https://github.com/shetabit/payment/blob/master/_autodocs/invoices.md
Instantiate a new, empty Invoice object. This is the starting point for creating a payment request.
```php
use Shetabit\Multipay\Invoice;
$invoice = new Invoice;
```
--------------------------------
### Initiate Purchase Request
Source: https://github.com/shetabit/payment/blob/master/_autodocs/api-reference.md
The `purchase()` method starts a payment transaction. It accepts an Invoice object and an optional callback function that is executed after the purchase is finalized, allowing you to store transaction details.
```php
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
$invoice = (new Invoice)
->amount(50000)
->detail('orderId', 'ORDER-123')
->detail('description', 'Purchase of Product X');
Payment::purchase($invoice, function($driver, $transactionId) {
// Save transaction ID to database
DB::table('payments')->insert([
'driver' => $driver->getName(),
'transaction_id' => $transactionId,
'amount' => 50000,
'status' => 'pending'
]);
});
```
--------------------------------
### AzkiVam Driver Configuration
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configuration for the AzkiVam installment payment driver. Requires merchant ID and callback URL.
```php
'azkivam' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### View Customization
Source: https://github.com/shetabit/payment/blob/master/_autodocs/TABLE-OF-CONTENTS.txt
Instructions and examples for customizing the views and forms used in the payment process.
```APIDOC
## View Customization
### Description
This section provides guidance on customizing the visual elements and forms involved in the payment process, allowing for tailored user interfaces.
### Customization Options
Details on what aspects of the views can be customized.
### Implementation Guide
Instructions and code examples for implementing view customizations.
```
--------------------------------
### Create Payment Verification Route
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Define a GET route in `routes/web.php` to handle payment verification callbacks from the gateway.
```php
// routes/web.php
Route::get('/payment/verify', 'PaymentController@verify')->name('payment.verify');
```
--------------------------------
### Etebarino Driver Configuration
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configuration for the Etebarino installment payment driver. Requires merchant ID and callback URL.
```php
'etebarino' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Error Handling with Event Dispatching
Source: https://github.com/shetabit/payment/blob/master/_autodocs/error-handling.md
This example shows how to dispatch events based on payment verification outcomes. A `PaymentVerifiedEvent` is dispatched on success, and a `PaymentFailedEvent` is dispatched on failure, passing relevant details.
```php
try {
$receipt = Payment::amount(50000)
->transactionId($transactionId)
->verify();
// Dispatch success event
event(new PaymentVerifiedEvent($receipt));
} catch (InvalidPaymentException $e) {
// Dispatch failure event
event(new PaymentFailedEvent($transactionId, $e->getMessage()));
}
```
--------------------------------
### Listen to InvoiceVerifiedEvent
Source: https://github.com/shetabit/payment/blob/master/_autodocs/events.md
Example of listening to the InvoiceVerifiedEvent using Laravel's Event::listen. This demonstrates how to access event properties like receipt, driver, and invoice to update order status and send confirmation emails.
```php
use Shetabit\Payment\Events\InvoiceVerifiedEvent;
use Illuminate\Support\Facades\Event;
Event::listen(InvoiceVerifiedEvent::class, function (InvoiceVerifiedEvent $event) {
// Access the receipt, driver, and invoice
$referenceId = $event->receipt->getReferenceId();
$transactionId = $event->receipt->getTransactionId();
$driverName = $event->driver->getName();
// Update order status in database
Order::where('transaction_id', $transactionId)->update([
'status' => 'paid',
'reference_id' => $referenceId,
'paid_at' => now()
]);
// Send confirmation email
\Mail::send('payment.confirmed', [
'reference_id' => $referenceId,
'amount' => $event->invoice->getAmount()
]);
});
```
--------------------------------
### Add Custom Payment Driver Configuration
Source: https://github.com/shetabit/payment/blob/master/README.md
To add a custom payment driver, first define its name and any configuration parameters in the `drivers` array within the payment configuration. This example shows how to add 'my_driver'.
```php
'drivers' => [
'zarinpal' => [...],
'my_driver' => [
... // Your Config Params here.
]
]
```
--------------------------------
### Listening to InvoicePurchasedEvent with Event::listen
Source: https://github.com/shetabit/payment/blob/master/_autodocs/events.md
Example of how to register a closure-based listener for the InvoicePurchasedEvent using Laravel's Event facade. This is useful for immediate handling of events directly within routes or service providers.
```php
use Shetabit\Payment\Events\InvoicePurchasedEvent;
use Illuminate\Support\Facades\Event;
// Register a listener in your EventServiceProvider or route service provider
Event::listen(InvoicePurchasedEvent::class, function (InvoicePurchasedEvent $event) {
// Access the driver and invoice
$driverName = $event->driver->getName();
$amount = $event->invoice->getAmount();
// Log the purchase
\Log::info("Invoice purchased via $driverName for amount $amount");
// Send notification
\Mail::send('payment.purchased', [
'driver' => $driverName,
'amount' => $amount
]);
});
```
--------------------------------
### Switch Payment Driver at Runtime
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Demonstrates how to dynamically switch to a specific payment driver like 'jibit' before initiating a purchase. This allows for flexible payment method selection.
```php
use Shetabit\Payment\Facade\Payment;
// Use a specific driver
Payment::via('jibit')->purchase($invoice, ...);
```
--------------------------------
### Implement Payment Controller Logic
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Create a PaymentController with a `create` method to handle payment initiation. This involves creating an invoice, setting the amount and details, and then using the Payment facade to purchase and render the payment form.
```php
// app/Http/Controllers/PaymentController.php
namespace App\Http\Controllers;
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
class PaymentController extends Controller
{
public function create()
{
// Create an invoice
$invoice = (new Invoice)
->amount(50000) // 500 units
->detail('orderId', 'ORD-001');
// Purchase and redirect to payment gateway
return Payment::purchase($invoice, function($driver, $transactionId) {
// Store transaction ID for later verification
session(['transaction_id' => $transactionId]);
\Log::info('Payment initiated', [
'transaction_id' => $transactionId,
'driver' => $driver->getName(),
]);
})->pay()->render();
}
}
```
--------------------------------
### Create and Configure an Invoice
Source: https://github.com/shetabit/payment/blob/master/README.md
Initialize an Invoice object and set its amount and details. Multiple syntaxes are available for adding details.
```php
// At the top of the file.
use Shetabit\Multipay\Invoice;
...
// Create new invoice.
$invoice = new Invoice;
// Set invoice amount.
$invoice->amount(1000);
// Add invoice details: There are 4 syntax available for this.
// 1
$invoice->detail(['detailName' => 'your detail goes here']);
// 2
$invoice->detail('detailName','your detail goes here');
// 3
$invoice->detail(['name1' => 'detail1','name2' => 'detail2']);
// 4
$invoice->detail('detailName1','your detail1 goes here')
->detail('detailName2','your detail2 goes here');
```
--------------------------------
### Switch to Jibit Gateway
Source: https://github.com/shetabit/payment/blob/master/_autodocs/index.md
Demonstrates how to switch the payment gateway to 'jibit' for the purchase operation.
```php
purchase($invoice, ...)->pay()->render();
```
--------------------------------
### Initiate Payment Creation
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Simulates the user initiating a payment by sending a POST request to the payment creation endpoint.
```http
POST /payment/create
```
--------------------------------
### Initiate a Payment
Source: https://github.com/shetabit/payment/blob/master/_autodocs/index.md
Initiate a payment by creating an Invoice and using the Payment facade's `purchase` method. A callback can be provided to store the transaction ID.
```php
amount(50000);
return Payment::purchase($invoice, function($driver, $transactionId) {
// Store transaction ID
})->pay()->render();
```
--------------------------------
### Error Handling and Exceptions
Source: https://github.com/shetabit/payment/blob/master/_autodocs/TABLE-OF-CONTENTS.txt
Guide to error handling and exceptions within the payment API, providing patterns and solutions for troubleshooting production issues.
```APIDOC
## Error Handling and Exceptions
### Description
This guide details the error handling mechanisms and common exceptions encountered within the payment API. It offers production-ready patterns and solutions for troubleshooting.
### Error Codes
List of common error codes and their meanings.
### Exception Patterns
Examples and explanations of exception scenarios and how to handle them.
### Troubleshooting
Steps and advice for diagnosing and resolving issues.
```
--------------------------------
### Accessing Payment Instance via Facade and Container
Source: https://github.com/shetabit/payment/blob/master/_autodocs/service-provider.md
Demonstrates how to access the bound Payment instance using either the Payment facade or the application's service container.
```php
// Via facade
Payment::purchase($invoice, ...);
// Via service container
app('shetabit-payment')->purchase($invoice, ...);
```
--------------------------------
### Handle InvalidPaymentException
Source: https://github.com/shetabit/payment/blob/master/_autodocs/error-handling.md
Use a try-catch block to handle `InvalidPaymentException` during payment verification. This example shows how to catch the exception and display a user-friendly error message.
```php
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
use Shetabit\Payment\Facade\Payment;
try {
$receipt = Payment::amount(50000)
->transactionId($transactionId)
->verify();
// Payment successful
echo "Payment verified!";
} catch (InvalidPaymentException $e) {
// Payment verification failed
echo "Error: " . $e->getMessage();
}
```
--------------------------------
### Create Payment Initiation Route
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Define a POST route in `routes/web.php` to handle the initiation of a payment process. This route will point to your PaymentController.
```php
// routes/web.php
Route::post('/payment/create', 'PaymentController@create')->name('payment.create');
```
--------------------------------
### Add Payment Instructions to Redirect Form
Source: https://github.com/shetabit/payment/blob/master/_autodocs/views-and-customization.md
Customize the redirect form to include clear payment instructions for the user. This helps guide users through the payment process.
```php
```
--------------------------------
### Set Driver Configurations on the Fly
Source: https://github.com/shetabit/payment/blob/master/README.md
The `config` method allows setting specific driver configurations or multiple configurations at runtime before purchase. This is useful for overriding default settings or providing dynamic credentials.
```php
// At the top of the file.
use Shetabit\\Multipay\\Invoice;
use Shetabit\\Payment\\Facade\\Payment;
...
// Create new invoice.
$invoice = (new Invoice)->amount(1000);
// Purchase the given invoice with custom driver configs.
Payment::config('mechandId', 'your mechand id')->purchase(
$invoice,
function($driver, $transactionId) {
// We can store $transactionId in database.
}
);
// Also we can change multiple configs at the same time.
Payment::config(['key1' => 'value1', 'key2' => 'value2'])->purchase(
$invoice,
function($driver, $transactionId) {
// We can store $transactionId in database.
}
);
```
--------------------------------
### ProcessVerifiedPayment Listener
Source: https://github.com/shetabit/payment/blob/master/_autodocs/events.md
An example of an event listener class that handles the InvoiceVerifiedEvent. This listener updates the order status and sends a webhook to a third-party service upon successful payment verification.
```php
// app/Listeners/ProcessVerifiedPayment.php
namespace App\Listeners;
use Shetabit\Payment\Events\InvoiceVerifiedEvent;
class ProcessVerifiedPayment
{
public function handle(InvoiceVerifiedEvent $event)
{
$receipt = $event->receipt;
$invoice = $event->invoice;
// Mark order as paid
Order::where('id', $invoice->getDetail('orderId'))
->update([
'payment_status' => 'completed',
'reference_id' => $receipt->getReferenceId()
]);
// Send webhook to third-party service
\Http::post('https://api.example.com/webhooks/payment', [
'reference_id' => $receipt->getReferenceId(),
'amount' => $invoice->getAmount()
]);
}
}
```
--------------------------------
### Create an Invoice Instance
Source: https://github.com/shetabit/payment/blob/master/_autodocs/index.md
Instantiate an Invoice object to represent a payment request. Set the amount and details like order ID.
```php
amount(50000)
->detail('orderId', 'ORD-001');
```
--------------------------------
### Configure Aqayepardakht Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Aqayepardakht driver with your merchant ID and callback URL.
```php
'aqayepardakht' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### config
Source: https://github.com/shetabit/payment/blob/master/README.md
Allows setting driver configurations on the fly, either individually or in batches.
```APIDOC
## `config`
### Description
Sets driver configurations on the fly. This can be a single key-value pair or an array of configurations.
### Method
`Payment::config('key', 'value')` or `Payment::config(['key1' => 'value1', 'key2' => 'value2'])`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
use Shetabit\Multipay\Invoice;
use Shetabit\Payment\Facade\Payment;
// Create new invoice.
$invoice = (new Invoice)->amount(1000);
// Purchase with a specific configuration.
Payment::config('mechandId', 'your mechand id')->purchase(
$invoice,
function($driver, $transactionId) {
// Store transactionId in database.
}
);
// Purchase with multiple configurations.
Payment::config(['key1' => 'value1', 'key2' => 'value2'])->purchase(
$invoice,
function($driver, $transactionId) {
// Store transactionId in database.
}
);
```
### Response
None directly from this method, but it affects the subsequent `purchase` operation.
```
--------------------------------
### Custom Redirect Form View (Blade)
Source: https://github.com/shetabit/payment/blob/master/_autodocs/service-provider.md
Example of a custom redirect form view. This HTML template is used when the default Blade rendering is overridden. It includes a form that automatically submits on page load.
```html
Processing Payment
```
--------------------------------
### config()
Source: https://github.com/shetabit/payment/blob/master/_autodocs/api-reference.md
Configure driver-specific settings at runtime. This method allows you to set configuration values either individually or as an array of key-value pairs, enabling dynamic adjustments to payment configurations.
```APIDOC
## config()
### Description
Configure driver-specific settings at runtime. This method allows you to set configuration values either individually or as an array of key-value pairs, enabling dynamic adjustments to payment configurations.
### Method
`public static function config($key, $value = null): MultipayPayment`
### Parameters
#### Path Parameters
—
#### Query Parameters
—
#### Request Body
—
### Parameters
- **$key** (string|array) - Required - Configuration key or array of key-value pairs
- **$value** (mixed) - Optional - Configuration value (ignored if $key is an array)
### Returns
`MultipayPayment` — Payment instance for method chaining
### Example
```php
use Shetabit\Payment\Facade\Payment;
// Set a single configuration value
Payment::config('merchantId', 'your-merchant-id')->purchase($invoice, ...);
// Set multiple configuration values at once
Payment::config([
'merchantId' => 'id123',
'apiKey' => 'key456'
])->purchase($invoice, ...);
```
```
--------------------------------
### Configure Asanpardakht Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Asanpardakht driver with your merchant ID and callback URL.
```php
'asanpardakht' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Configure SEP Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the SEP driver (for Keshavarzi and Saderat banks) with your merchant ID and callback URL.
```php
'sep' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### via()
Source: https://github.com/shetabit/payment/blob/master/_autodocs/api-reference.md
Allows switching the payment driver at runtime. This is useful when you need to use a specific driver other than the default one configured.
```APIDOC
## via()
### Description
Switch to a different payment driver at runtime.
### Method
`public static function via($driver): MultipayPayment`
### Parameters
#### Path Parameters
- **driver** (string) - Required - Driver name as defined in configuration
### Returns
`MultipayPayment` — Payment instance for method chaining
### Example
```php
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
$invoice = (new Invoice)->amount(50000);
// Use zarinpal driver instead of the default
Payment::via('zarinpal')->purchase($invoice, function($driver, $transactionId) {
// Store transaction ID
});
// Or use another driver
Payment::via('jibit')->purchase($invoice, ...);
```
```
--------------------------------
### Configure NextPay Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the NextPay driver with your API key and callback URL.
```php
'nextpay' => [
'apiKey' => 'your-api-key',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Quick Invoice Creation and Payment
Source: https://github.com/shetabit/payment/blob/master/_autodocs/invoices.md
Shows a concise way to create an invoice with a minimal amount and chain methods for immediate payment processing and rendering.
```php
// Minimal invoice
$invoice = (new Invoice)->amount(50000);
// Full chain with payment
return Payment::purchase($invoice, function($driver, $transactionId) {
// Process transaction
})->pay()->render();
```
--------------------------------
### Configure Payment Gateway Credentials
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Configure your default payment gateway and its credentials in the `config/payment.php` file. Add your merchant ID and callback URL to the environment file.
```php
return [
'default' => 'zarinpal',
'drivers' => [
'zarinpal' => [
'merchantId' => env('ZARINPAL_MERCHANT_ID'),
'callbackUrl' => env('ZARINPAL_CALLBACK_URL'),
],
],
];
```
```env
ZARINPAL_MERCHANT_ID=your-merchant-id
ZARINPAL_CALLBACK_URL=http://localhost:8000/payment/verify
```
--------------------------------
### Environment Variables for Credentials
Source: https://github.com/shetabit/payment/blob/master/_autodocs/service-provider.md
Demonstrates how sensitive credentials for payment drivers should be stored in the `.env` file for security.
```env
ZARINPAL_MERCHANT_ID=your_merchant_id
JIBIT_API_KEY=your_api_key
# ... other driver credentials
```
--------------------------------
### Configure Saman Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Saman driver with your merchant ID and callback URL.
```php
'saman' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Switch Payment Driver at Runtime
Source: https://github.com/shetabit/payment/blob/master/_autodocs/api-reference.md
Use the `via()` method to select a specific payment driver other than the default one configured. This is useful for dynamic driver selection based on certain conditions.
```php
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
$invoice = (new Invoice)->amount(50000);
// Use zarinpal driver instead of the default
Payment::via('zarinpal')->purchase($invoice, function($driver, $transactionId) {
// Store transaction ID
});
// Or use another driver
Payment::via('jibit')->purchase($invoice, ...);
```
--------------------------------
### Configure Atipay Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Atipay driver with your merchant ID and callback URL.
```php
'atipay' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Switch Payment Gateway at Runtime
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Use the `via()` method to specify a payment gateway other than the default for a specific transaction. This is useful when you need to use a different provider for certain payments.
```php
return Payment::via('jibit')
->purchase($invoice, function($driver, $transactionId) {
// Handle Jibit transaction
})->pay()->render();
```
--------------------------------
### Storing and Retrieving Invoice Details
Source: https://github.com/shetabit/payment/blob/master/_autodocs/invoices.md
Illustrates how to add multiple details to an invoice using an associative array and how to retrieve specific details later.
```php
$invoice = (new Invoice)
->amount(50000)
->detail([
'orderId' => 'ORD-2024-001',
'customerId' => '789',
'email' => 'user@example.com'
]);
// Later retrieve details
$details = $invoice->getDetails();
$orderId = $details['orderId']; // 'ORD-2024-001'
```
--------------------------------
### Configure Behpardakht (Mellat) Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Behpardakht (Mellat) driver with terminal ID, username, password, and callback URL.
```php
'behpardakht' => [
'terminalId' => 'your-terminal-id',
'username' => 'your-username',
'password' => 'your-password',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Pay an Invoice and Render
Source: https://github.com/shetabit/payment/blob/master/README.md
After purchasing, redirect the user to the bank payment page. The `pay()->render()` methods handle the redirection process.
```php
// At the top of the file.
use Shetabit\Multipay\Invoice;
use Shetabit\Payment\Facade\Payment;
...
// Create new invoice.
$invoice = (new Invoice)->amount(1000);
// Purchase and pay the given invoice.
// You should use return statement to redirect user to the bank page.
return Payment::purchase($invoice, function($driver, $transactionId) {
// Store transactionId in database as we need it to verify payment in the future.
})->pay()->render();
// Do all things together in a single line.
return Payment::purchase(
(new Invoice)->amount(1000),
function($driver, $transactionId) {
// Store transactionId in database.
// We need the transactionId to verify payment in the future.
}
)->pay()->render();
// Retrieve json format of Redirection (in this case you can handle redirection to bank gateway)
return Payment::purchase(
(new Invoice)->amount(1000),
function($driver, $transactionId) {
// Store transactionId in database.
// We need the transactionId to verify payment in the future.
}
)->pay()->toJson();
```
--------------------------------
### Implement Custom Payment Driver
Source: https://github.com/shetabit/payment/blob/master/README.md
Create a custom driver class by extending `Shetabit
Payment
Abstracts
Driver`. This class must implement `purchase`, `pay`, and `verify` methods to handle payment transactions.
```php
namespace App\Packages\PaymentDriver;
use Shetabit\Multipay\Abstracts\Driver;
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
use Shetabit\Multipay\{Contracts\ReceiptInterface, Invoice, Receipt};
class MyDriver extends Driver
{
protected $invoice; // Invoice.
protected $settings; // Driver settings.
public function __construct(Invoice $invoice, $settings)
{
$this->invoice($invoice); // Set the invoice.
$this->settings = (object) $settings; // Set settings.
}
// Purchase the invoice, save its transactionId and finaly return it.
public function purchase() {
// Request for a payment transaction id.
...
$this->invoice->transactionId($transId);
return $transId;
}
// Redirect into bank using transactionId, to complete the payment.
public function pay() {
// It is better to set bankApiUrl in config/payment.php and retrieve it here:
$bankUrl = $this->settings->bankApiUrl; // bankApiUrl is the config name.
// Prepare payment url.
$payUrl = $bankUrl.$this->invoice->getTransactionId();
// Redirect to the bank.
return redirect()->to($payUrl);
}
// Verify the payment (we must verify to ensure that user has paid the invoice).
public function verify(): ReceiptInterface {
$verifyPayment = $this->settings->verifyApiUrl;
$verifyUrl = $verifyPayment.$this->invoice->getTransactionId();
...
/**
Then we send a request to $verifyUrl and if payment is not valid we throw an InvalidPaymentException with a suitable message.
**/
throw new InvalidPaymentException('a suitable message');
/**
We create a receipt for this payment if everything goes normally.
**/
return new Receipt('driverName', 'payment_receipt_number');
}
}
```
--------------------------------
### Configure IranKish Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the IranKish driver with your merchant ID and callback URL.
```php
'irankish' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Configure Payping Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Payping driver with your API token and callback URL.
```php
'payping' => [
'token' => 'your-api-token',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Handle Payment Events
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Create a listener for the `InvoicePurchasedEvent` to log payment details. Register this listener in your `EventServiceProvider`.
```php
// app/Listeners/LogPaymentPurchase.php
namespace App\Listeners;
use Shetabit\Payment\Events\InvoicePurchasedEvent;
class LogPaymentPurchase
{
public function handle(InvoicePurchasedEvent $event)
{
\Log::info('Invoice purchased', [
'driver' => $event->driver->getName(),
'amount' => $event->invoice->getAmount(),
]);
}
}
```
```php
protected $listen = [
InvoicePurchasedEvent::class => [
\App\Listeners\LogPaymentPurchase::class,
],
];
```
--------------------------------
### Create and Purchase Invoice
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Controller logic to create an invoice and initiate a purchase using the payment system.
```php
// Controller creates invoice and initiates purchase
$invoice = (new Invoice)->amount(50000);
Payment::purchase($invoice, ...)->pay()->render();
```
--------------------------------
### purchase()
Source: https://github.com/shetabit/payment/blob/master/_autodocs/api-reference.md
Initiates a purchase request with the payment gateway. It can optionally take an Invoice object and a callback function to be executed after the purchase is finalized.
```APIDOC
## purchase()
### Description
Initiate a purchase request with the payment gateway.
### Method
`public static function purchase(Invoice $invoice = null, $finalizeCallback = null): MultipayPayment`
### Parameters
#### Path Parameters
- **invoice** (Invoice|null) - Optional - Invoice object with payment details
- **finalizeCallback** (callable) - Optional - Callback function executed after purchase
### Callback Parameters
- `$driver`: DriverInterface — The payment driver instance
- `$transactionId`: string — Unique transaction ID from the gateway
### Returns
`MultipayPayment` — Payment instance for method chaining
### Example
```php
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
$invoice = (new Invoice)
->amount(50000)
->detail('orderId', 'ORDER-123')
->detail('description', 'Purchase of Product X');
Payment::purchase($invoice, function($driver, $transactionId) {
// Save transaction ID to database
DB::table('payments')->insert([
'driver' => $driver->getName(),
'transaction_id' => $transactionId,
'amount' => 50000,
'status' => 'pending'
]);
});
```
```
--------------------------------
### Configure Callback URL
Source: https://github.com/shetabit/payment/blob/master/_autodocs/error-handling.md
Ensure the callback URL is correctly configured in `config/payment.php` and is publicly accessible. For local development, use a tunneling service like ngrok.
```php
// Verify callback URL is correct in config/payment.php
'zarinpal' => [
'merchantId' => env('ZARINPAL_MERCHANT_ID'),
'callbackUrl' => 'https://yourdomain.com/payment/verify', // Must be publicly accessible
]
// In production, always use HTTPS
// For testing, use a tunneling service like ngrok if developing locally
```
--------------------------------
### Configure Payment Settings
Source: https://github.com/shetabit/payment/blob/master/_autodocs/api-reference.md
Use this method to set configuration values for the payment driver at runtime. It accepts a single key-value pair or an array of multiple settings.
```php
use Shetabit\Payment\Facade\Payment;
// Set a single configuration value
Payment::config('merchantId', 'your-merchant-id')->purchase($invoice, ...);
// Set multiple configuration values at once
Payment::config([
'merchantId' => 'id123',
'apiKey' => 'key456'
])->purchase($invoice, ...);
```
--------------------------------
### Handle Purchase Initiation Errors
Source: https://github.com/shetabit/payment/blob/master/_autodocs/error-handling.md
Use a try-catch block to handle exceptions during the payment purchase initiation. This catches errors related to the initial request to the payment gateway.
```php
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
$invoice = (new Invoice)->amount(50000);
try {
Payment::purchase($invoice, function($driver, $transactionId) {
// This callback is called only if purchase was successful
// Store the transaction ID for verification later
Order::create([
'transaction_id' => $transactionId,
'driver' => $driver->getName(),
'status' => 'pending'
]);
});
} catch (\Exception $e) {
// Errors during purchase initiation
\Log::error('Purchase failed', [
'error' => $e->getMessage(),
'driver' => $invoice->getDriver()
]);
return redirect()->back()->with('error', 'Failed to initiate payment');
}
```
--------------------------------
### Configure Static Callback URL
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
Set a default callback URL for a specific driver in the configuration file. This URL is used to redirect users after payment attempts if no dynamic URL is specified.
```php
'zarinpal' => [
'merchantId' => env('ZARINPAL_MERCHANT_ID'),
'callbackUrl' => env('ZARINPAL_CALLBACK_URL', 'https://yourapp.com/payment/verify'),
]
```
--------------------------------
### Use Different Payment Drivers
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
Switch between configured payment drivers using the `via()` method before initiating a purchase. This allows you to select a specific gateway for a transaction.
```php
use Shetabit\Payment\Facade\Payment;
use Shetabit\Multipay\Invoice;
$invoice = (new Invoice)->amount(50000);
// Use the default driver (zarinpal)
Payment::purchase($invoice, ...);
// Use jibit driver
Payment::via('jibit')->purchase($invoice, ...);
// Use payfa driver
Payment::via('payfa')->purchase($invoice, ...);
```
--------------------------------
### API Reference - Facade Methods
Source: https://github.com/shetabit/payment/blob/master/_autodocs/TABLE-OF-CONTENTS.txt
Details on all facade methods available for direct use in the payment API. This section covers the primary interface for interacting with the payment system.
```APIDOC
## API Reference - Facade Methods
### Description
This section details the facade methods provided by the payment API, which serve as the primary interface for developers to interact with the payment system. It includes information on all 10 available methods.
### Method
Details for each facade method (e.g., create, capture, refund) would be listed here, including HTTP method if applicable, endpoint, parameters, and examples.
### Endpoint
Specific endpoints for each facade method would be detailed here.
### Parameters
Information on path, query, and request body parameters for each method.
### Request Example
Examples of request payloads for various facade methods.
### Response
Details on success and error responses, including status codes and response body structures.
```
--------------------------------
### Use Payment Facade for Operations
Source: https://github.com/shetabit/payment/blob/master/_autodocs/index.md
The Payment facade is the main entry point for payment operations. Use it to purchase, pay, and verify transactions.
```php
pay()->render();
Payment::verify();
```
--------------------------------
### Configure Zarinpal Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Zarinpal driver with your merchant ID and callback URL.
```php
'zarinpal' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Map Custom Driver in Payment Configuration
Source: https://github.com/shetabit/payment/blob/master/README.md
After creating a custom driver class, map it to a driver name in the `map` section of the `payment.php` configuration file. Ensure the key in `map` matches the key in `drivers`.
```php
'map' => [
...
'my_driver' => App\Packages\PaymentDriver\MyDriver::class,
]
```
--------------------------------
### Configure Parsian Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Parsian driver with your login ID and callback URL.
```php
'parsian' => [
'loginId' => 'your-login-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Create a Payment with Invoice
Source: https://github.com/shetabit/payment/blob/master/_autodocs/README.md
Create a new payment invoice with a specified amount and initiate the purchase process. The callback function can be used to store the transaction ID.
```php
use Shetabit\Multipay\Invoice;
use Shetabit\Payment\Facade\Payment;
$invoice = (new Invoice)->amount(50000);
return Payment::purchase($invoice, function($driver, $transactionId) {
// Store transaction ID for later verification
})->pay()->render();
```
--------------------------------
### Configure Sadad (Melli Bank) Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Sadad (Melli Bank) driver with your merchant ID and callback URL.
```php
'sadad' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### Configure Jibit Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
Configuration for the Jibit payment driver. Requires merchant ID, callback URL, and API key.
```php
'jibit' => [
'merchantId' => env('JIBIT_MERCHANT_ID'),
'callbackUrl' => env('JIBIT_CALLBACK_URL'),
'apiKey' => env('JIBIT_API_KEY'),
]
```
--------------------------------
### Create Subscription Payment Invoice
Source: https://github.com/shetabit/payment/blob/master/_autodocs/invoices.md
Creates an invoice for a user's subscription payment, including subscription details. It initiates the purchase process and logs the transaction ID.
```php
$subscription = $user->subscription();
$invoice = (new Invoice)
->amount($subscription->price * 100)
->detail('userId', $user->id)
->detail('subscriptionId', $subscription->id)
->detail('plan', $subscription->plan_name)
->detail('duration', '1 month');
Payment::purchase($invoice, function($driver, $transactionId) use ($subscription) {
Log::info('Subscription payment initiated', ['transactionId' => $transactionId]);
});
```
--------------------------------
### Jibit Payment Gateway Configuration
Source: https://github.com/shetabit/payment/blob/master/_autodocs/index.md
Configures the Jibit payment driver. Provide your merchant ID, callback URL, and API key.
```env
JIBIT_MERCHANT_ID=your-merchant-id
JIBIT_CALLBACK_URL=https://yourapp.com/payment/jibit/verify
JIBIT_API_KEY=your-api-key
```
--------------------------------
### Store Order Before Initiating Payment
Source: https://github.com/shetabit/payment/blob/master/_autodocs/quick-start.md
Create an order record in your database before initiating the payment process. This ensures that order details are saved even if the payment fails. The transaction ID is stored during the purchase callback.
```php
public function create(Request $request)
{
// Create order
$order = Order::create([
'user_id' => auth()->id(),
'amount' => 50000,
'status' => 'pending'
]);
// Create invoice
$invoice = (new Invoice)
->amount($order->amount)
->detail('orderId', $order->id);
// Initiate payment
return Payment::purchase($invoice, function($driver, $transactionId) use ($order) {
$order->update(['transaction_id' => $transactionId]);
})->pay()->render();
}
```
--------------------------------
### Configure Payfa Driver
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configure the Payfa driver with your merchant ID and callback URL.
```php
'payfa' => [
'merchantId' => 'your-merchant-id',
'callbackUrl' => 'https://yourapp.com/payment/verify',
]
```
--------------------------------
### callbackUrl
Source: https://github.com/shetabit/payment/blob/master/README.md
Allows changing the callback URL at runtime before initiating a purchase.
```APIDOC
## `callbackUrl`
### Description
Changes the callback URL for the payment process at runtime.
### Method
`Payment::callbackUrl($url)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
use Shetabit\Multipay\Invoice;
use Shetabit\Payment\Facade\Payment;
// Create new invoice.
$invoice = (new Invoice)->amount(1000);
// Purchase the given invoice with a custom callback URL.
Payment::callbackUrl($url)->purchase(
$invoice,
function($driver, $transactionId) {
// Store transactionId in database.
}
);
```
### Response
None directly from this method, but it affects the subsequent `purchase` operation.
```
--------------------------------
### Select Payment Driver Dynamically
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Selects a payment driver dynamically based on user request or application configuration. It then uses the selected driver to initiate a purchase.
```php
// User chooses payment method
$driver = request('payment_method') ?? config('payment.default');
Payment::via($driver)->purchase($invoice, ...);
```
--------------------------------
### Local Driver Configuration
Source: https://github.com/shetabit/payment/blob/master/_autodocs/drivers.md
Configuration for the local driver, suitable for development and testing environments. It specifies a callback URL for payment verification.
```php
'local' => [
'callbackUrl' => 'http://localhost:8000/payment/verify',
]
```
--------------------------------
### Override Driver and Configuration
Source: https://github.com/shetabit/payment/blob/master/_autodocs/configuration.md
Change the active payment driver and override its specific configuration options in a single fluent call.
```php
// Change both driver and its configuration at once
Payment::via('jibit')
->config('apiKey', 'different-key')
->purchase($invoice, ...);
```
--------------------------------
### Catch All Payment Exceptions
Source: https://github.com/shetabit/payment/blob/master/_autodocs/error-handling.md
Demonstrates how to catch all exceptions that inherit from the base PaymentException class provided by the Multipay package. This is useful for centralizing error handling for payment-related operations.
```php
use Shetabit\Multipay\Exceptions\PaymentException;
try {
$receipt = Payment::amount(50000)
->transactionId($transactionId)
->verify();
} catch (PaymentException $e) {
// Catches InvalidPaymentException and any other payment exceptions
Log::error('Payment error: ' . $e->getMessage());
}
```