Omnipay Documentation

repository·master·Indexed 27 days ago

https://github.com/thephpleague/omnipay

A consistent payment processing library for PHP that abstracts differences between various payment gateways. It provides a single API to interact with multiple providers such as PayPal, Stripe, Braintree, and Authorize.Net, allowing developers to switch gateways without rewriting core logic. The library supports core payment flows including authorize, capture, purchase, refund, and token billing, and handles both on-site and off-site redirect responses.

Tokens
3.2K
Snippets
11
Records
15
Agent score
41%

What's inside Omnipay

  1. Quickstart with Omnipay

    master

    Omnipay provides a consistent API for processing payments across different gateways. You can create a gateway instance, configure it with credentials, and initiate a purchase. The response object allows you to handle redirects to offsite gateways, successful payments, or failures.

    use Omnipay\Omnipay;
    
    $gateway = Omnipay::create('Stripe');
    $gateway->setApiKey('abc123');
    
    $formData = array('number' => '4242424242424242', 'expiryMonth' => '6', 'expiryYear' => '2030', 'cvv' => '123');
    $response = $gateway->purchase(array('amount' => '10.00', 'currency' => 'USD', 'card' => $formData))->send();
    
    if ($response->isRedirect()) {
        // redirect to offsite payment gateway
        $response->redirect();
    } elseif ($response->isSuccessful()) {
        // payment was successful: update database
        print_r($response);
    } else {
        // payment failed: display message to customer
        echo $response->getMessage();
    }
  2. Handle Payment Responses

    master

    After calling .send() on a request, you receive a response object implementing ResponseInterface. You must check if the response was successful or if a redirect is required.

    Successful Responses: Use $response->isSuccessful() to verify. You can retrieve the transaction reference via $response->getTransactionReference() and the gateway's message via $response->getMessage(). If the authorization is reusable, $response->getCardReference() may return a value.

    Redirect Responses: If $response->isRedirect() is true, the customer must be moved to an off-site form. You can use $response->redirect() to automatically forward the customer, or manually retrieve the URL via $response->getRedirectUrl() and any necessary POST data via $response->getRedirectData().

    $response = $gateway->purchase(array('amount' => '10.00', 'card' => $card))->send();
    
    if ($response->isSuccessful()) {
        // payment is complete
    } elseif ($response->isRedirect()) {
        $response->redirect(); // automatically forwards the customer
    } else {
        // not successful
    }
  3. Use Token Billing for future payments

    master

    Token billing allows you to store a card with a gateway and charge it later using a cardReference.

    1. Create a card: Use $gateway->createCard($options). If you want to process an initial payment immediately, include 'action' => 'authorize' or 'action' => 'purchase' in the options.
    2. Retrieve reference: Get the reference from the response using $response->getCardReference().
    3. Charge later: Use the reference in the cardReference option instead of the card object.

    Supported methods:

    • createCard($options)
    • updateCard($options) (not all gateways support this)
    • deleteCard($options) (not all gateways support this)
  4. Install Omnipay with a custom HTTP Client

    master

    If you prefer not to use Guzzle, you can require omnipay/common directly along with a specific php-http/client-implementation (such as Buzz).

    composer require league/common:^3 omnipay/paypal php-http/buzz-adapter
  5. Handle Errors and Exceptions

    master

    When processing payments, you should handle both unsuccessful response objects and thrown exceptions.

    • Unsuccessful Responses: If the gateway does not throw an exception but isSuccessful() is false, use $response->getMessage() to display the error to the customer.
    • Exceptions: If an exception is thrown, it typically indicates a code bug (missing required fields) or a communication error with the gateway. Wrap your request in a try-catch block to prevent application crashes.
    try {
        $response = $gateway->purchase(array('amount' => '10.00', 'card' => $card))->send();
        if ($response->isSuccessful()) {
            // mark order as complete
        } elseif ($response->isRedirect()) {
            $response->redirect();
        } else {
            // display error to customer
            exit($response->getMessage());
        }
    } catch (\Exception $e) {
        // internal error, log exception and display a generic message to the customer
        exit('Sorry, there was an error processing your payment. Please try again later.');
    }
  6. Upgrade from v2 to v3

    master
    When upgrading to v3, note that the package name has changed from omnipay/omnipay to league/omnipay. Ensure you require league/omnipay or a separate HTTP adapter. If your specific gateway does not yet support v3, you may need to upgrade it manually or check for an upcoming release.
  7. Enable Test Mode or Developer Mode

    master

    Most gateways use a testMode setting for sandbox environments. Some specific gateways (like Authorize.net) use developerMode. To support multiple gateways safely, check for the existence of the method before calling it.

    if ($is_developer_mode) {
        if (method_exists($gateway, 'setDeveloperMode')) {
            $gateway->setDeveloperMode(TRUE);
        } else {
            $gateway->setTestMode(TRUE);
        }
    }
  8. Initialize a Payment Gateway

    master

    To use a gateway, use the Omnipay::create() method with the gateway's identifier. You can then configure the gateway using its specific settings, such as setUsername() and setPassword().

    use Omnipay\Omnipay;
    
    $gateway = Omnipay::create('PayPal_Express');
    $gateway->setUsername('adrian');
    $gateway->setPassword('12345');
  9. Retrieve Gateway Default Parameters

    master

    If you need to discover the available configuration settings for a specific gateway, call the getDefaultParameters() method. This returns an associative array of the settings the gateway expects.

    $settings = $gateway->getDefaultParameters();
    // example output format:
    array(
        'username' => '', // string variable
        'testMode' => false, // boolean variable
        'landingPage' => array('billing', 'login'), // enum variable
    );
  10. Use the CreditCard object for user input

    master

    The CreditCard object provides a safe way to handle user payment data. It can be initialized with an associative array of untrusted user input via the constructor; any unrecognized fields will be ignored.

    Commonly required fields for on-site gateways include:

    • firstName
    • lastName
    • number
    • expiryMonth
    • expiryYear
    • cvv

    You can validate card numbers using the Luhn algorithm via Helper::validateLuhn($number). If you submit invalid details (e.g., missing required fields or failing the Luhn check), an InvalidCreditCardException will be thrown.

    $formInputData = array(
        'firstName' => 'Bobby',
        'lastName' => 'Tables',
        'number' => '4111111111111111',
    );
    $card = new CreditCard($formInputData);
    
    // Accessing fields
    $number = $card->getNumber();
    $card->setFirstName('Adrian');