Skip to main content

Overview

The OCPay PHP SDK provides a modern, type-safe interface for integrating OCPay payments into your PHP applications. Built with PHP 8.1+ features and best practices.

Type Safe

Full PHP 8.1+ type hints and return types

Composer Ready

PSR-4 autoloading and easy installation

Simple API

Clean, intuitive interface

Error Handling

Custom exceptions for different error types

Requirements

  • PHP 8.1 or higher
  • Composer
  • ext-json extension
  • ext-curl extension

Installation

Install via Composer:
composer require oneclickdz/ocpay-php-sdk
Or add to your composer.json:
{
    "require": {
        "oneclickdz/ocpay-php-sdk": "^1.0"
    }
}

Quick Start

1. Initialize SDK

<?php

require 'vendor/autoload.php';

use OneClickDz\OCPay\OCPay;

// Initialize with your API access token
$ocpay = new OCPay('your-api-access-token');
Store your API key in environment variables, never in code
# .env file
ONECLICK_API_KEY=your_api_key_here
// Load from environment
$ocpay = new OCPay(getenv('ONECLICK_API_KEY'));
use OneClickDz\OCPay\DTO\CreateLinkRequest;
use OneClickDz\OCPay\DTO\ProductInfo;

// Create product information
$productInfo = new ProductInfo(
    title: 'Premium Subscription',
    amount: 5000, // Amount in DZD (500 - 500,000)
    description: 'Monthly access to premium features'
);

// Create payment link request
$request = new CreateLinkRequest(
    productInfo: $productInfo,
    feeMode: CreateLinkRequest::FEE_MODE_NO_FEE,
    successMessage: 'Thank you for your purchase!',
    redirectUrl: 'https://yourstore.com/success?order=12345'
);

// Create the payment link
try {
    $response = $ocpay->createLink($request);
    
    // Redirect customer to payment page
    echo "Payment URL: " . $response->paymentUrl . "\n";
    
    // IMPORTANT: Save this reference!
    echo "Payment Reference: " . $response->paymentRef . "\n";
    saveOrderPaymentRef($orderId, $response->paymentRef);
    
} catch (\OneClickDz\OCPay\Exception\ValidationException $e) {
    echo "Validation error: " . $e->getMessage() . "\n";
} catch (\OneClickDz\OCPay\Exception\UnauthorizedException $e) {
    echo "Auth error: " . $e->getMessage() . "\n";
} catch (\OneClickDz\OCPay\Exception\ApiException $e) {
    echo "API error: " . $e->getMessage() . "\n";
}

3. Check Payment Status

// Check payment status using the payment reference
try {
    $status = $ocpay->checkPayment('OCPL-A1B2C3-D4E5');
    
    if ($status->isConfirmed()) {
        // Payment successful - fulfill the order
        echo "Payment confirmed!\n";
        echo "Amount: " . $status->transactionDetails->amount . " DZD\n";
        fulfillOrder($orderId);
        
    } elseif ($status->isFailed()) {
        // Payment failed or expired
        echo "Payment failed: " . $status->message . "\n";
        markOrderFailed($orderId);
        
    } else {
        // Still pending - check again later
        echo "Payment pending...\n";
    }
    
} catch (\OneClickDz\OCPay\Exception\NotFoundException $e) {
    echo "Payment not found\n";
} catch (\OneClickDz\OCPay\Exception\PaymentExpiredException $e) {
    echo "Payment link expired\n";
} catch (\OneClickDz\OCPay\Exception\ApiException $e) {
    echo "API error: " . $e->getMessage() . "\n";
}

Complete E-commerce Example

Here’s a complete flow for an e-commerce checkout:
<?php

require 'vendor/autoload.php';

use OneClickDz\OCPay\OCPay;
use OneClickDz\OCPay\DTO\CreateLinkRequest;
use OneClickDz\OCPay\DTO\ProductInfo;

// Initialize SDK
$ocpay = new OCPay(getenv('ONECLICK_API_KEY'));

// Step 1: Create order in your system
$orderId = createOrder([
    'customer_id' => 123,
    'items' => [
        ['name' => 'Product A', 'price' => 5000],
        ['name' => 'Product B', 'price' => 3000],
    ],
    'total' => 8000,
]);

// Step 2: Create payment link
try {
    $productInfo = new ProductInfo(
        title: "Order #{$orderId}",
        amount: 8000,
        description: "Payment for order #{$orderId}"
    );
    
    $request = new CreateLinkRequest(
        productInfo: $productInfo,
        feeMode: CreateLinkRequest::FEE_MODE_NO_FEE,
        successMessage: "Thank you! Order #{$orderId} confirmed.",
        redirectUrl: "https://yourstore.com/orders/{$orderId}/success"
    );
    
    $response = $ocpay->createLink($request);
    
    // Step 3: Save payment reference
    updateOrder($orderId, [
        'payment_ref' => $response->paymentRef,
        'payment_url' => $response->paymentUrl,
        'status' => 'pending_payment',
    ]);
    
    // Step 4: Redirect customer
    header("Location: " . $response->paymentUrl);
    exit;
    
} catch (ApiException $e) {
    error_log("Payment creation failed: " . $e->getMessage());
    showErrorPage("Failed to create payment. Please try again.");
}

Background Job for Status Polling

Set up a cron job or background worker:
<?php

// check_payments.php - Run every 20 minutes

require 'vendor/autoload.php';

use OneClickDz\OCPay\OCPay;

$ocpay = new OCPay(getenv('ONECLICK_API_KEY'));

// Get all pending orders
$pendingOrders = getPendingOrders();

foreach ($pendingOrders as $order) {
    if (!$order['payment_ref']) {
        continue;
    }
    
    try {
        $status = $ocpay->checkPayment($order['payment_ref']);
        
        if ($status->isConfirmed()) {
            // Mark as paid and fulfill
            updateOrder($order['id'], [
                'status' => 'paid',
                'paid_at' => date('Y-m-d H:i:s'),
            ]);
            fulfillOrder($order['id']);
            
        } elseif ($status->isFailed()) {
            // Mark as failed
            updateOrder($order['id'], [
                'status' => 'payment_failed',
            ]);
        }
        
    } catch (ApiException $e) {
        error_log("Status check failed: " . $e->getMessage());
    }
}
Add to crontab:
*/20 * * * * php /path/to/check_payments.php

API Reference

OCPay Class

Main SDK entry point.

Constructor

public function __construct(
    string $accessToken,
    array $options = []
)
Parameters:
  • $accessToken: Your API access token
  • $options: Optional Guzzle client configuration
    • timeout: Request timeout in seconds (default: 30)

Methods

createLink(CreateLinkRequest $request): CreateLinkResponse Creates a payment link. checkPayment(string $paymentRef): CheckPaymentResponse Checks payment status.

Data Transfer Objects (DTOs)

ProductInfo

new ProductInfo(
    title: string,        // Product name (1-200 chars)
    amount: int,          // Amount in DZD (500 - 500,000)
    description?: string  // Optional (max 1000 chars)
)

CreateLinkRequest

new CreateLinkRequest(
    productInfo: ProductInfo,
    feeMode?: string,        // NO_FEE (default), SPLIT_FEE, CUSTOMER_FEE
    successMessage?: string, // Optional success message
    redirectUrl?: string     // Optional redirect URL
)
Fee Mode Constants:
  • CreateLinkRequest::FEE_MODE_NO_FEE - Merchant pays (default)
  • CreateLinkRequest::FEE_MODE_SPLIT_FEE - 50/50 split
  • CreateLinkRequest::FEE_MODE_CUSTOMER_FEE - Customer pays

CreateLinkResponse

$response->paymentUrl     // URL to redirect customer
$response->paymentRef     // Payment reference (SAVE THIS!)
$response->paymentLink    // Full payment link object

CheckPaymentResponse

$response->status                // PaymentStatus enum
$response->message               // Status message
$response->paymentRef           // Payment reference
$response->transactionDetails   // Transaction details (if confirmed)

// Helper methods
$response->isConfirmed()        // true if payment confirmed
$response->isPending()          // true if still pending
$response->isFailed()           // true if failed

Exception Handling

All exceptions extend OCPayException:
ExceptionHTTP CodeWhen Thrown
ValidationException400Invalid request data
UnauthorizedException403Invalid API key
NotFoundException404Payment not found
PaymentExpiredException410Link expired (>20 min)
ApiExceptionVariousOther API errors
All exceptions provide:
try {
    $response = $ocpay->createLink($request);
} catch (ApiException $e) {
    echo $e->getMessage();       // Error message
    echo $e->getStatusCode();    // HTTP status code
    echo $e->getRequestId();     // Request ID for support
    var_dump($e->getErrorData()); // Full error data
}

Important Notes

Merchant Validation Required

Complete merchant validation at oneclickdz.com before using the API

Amount Limits

  • Minimum: 500 DZD
  • Maximum: 500,000 DZD
  • Must be whole numbers (integers)

Fee Structure

Low Fees: 0% on balance, only 1% withdrawal fee
Links expire 20 minutes after creation if payment not initiated.

Payment Status Flow

  1. PENDING - Payment in progress → Poll again later
  2. CONFIRMED - Payment successful → Fulfill order
  3. FAILED - Payment declined/expired → Mark order failed

Laravel Integration

For Laravel projects, see the complete integration example in the GitHub repository. Includes:
  • Service provider setup
  • Payment service class
  • Controller examples
  • Database migrations
  • Background job for polling
  • Error handling

Testing

Using Sandbox

The API automatically uses sandbox mode for test accounts:
$response = $ocpay->createLink($request);

if ($response->paymentLink->isSandbox) {
    echo "This is a test payment\n";
}

Unit Tests

composer install --dev
vendor/bin/phpunit

Best Practices

Store paymentRef immediately after creating the link. You need it to check payment status.
Set up a background job to check payment status every 20 minutes for pending orders.
Catch and handle all exception types appropriately. Log errors for debugging.
Store API keys in environment variables, never commit them to version control.
Always use HTTPS for redirect URLs and your application endpoints.

Support & Resources

Next Steps

OCPay Best Practices

Learn production-ready tips and security best practices