### Setting up the Omnipay Example Application Source: https://omnipay.thephpleague.com/simple-example Follow these steps to clone and set up the Omnipay example application. This involves cloning the repository, navigating into the directory, installing dependencies with Composer, and running the application using PHP's built-in web server. ```bash # Clone project git clone https://github.com/thephpleague/omnipay-example.git omnipay-example # Go to project directory cd omnipay-example # Install dependencies composer install # Run using the built-in PHP web server php -S localhost:8000 ``` -------------------------------- ### Install Omnipay and PayPal Gateway Source: https://omnipay.thephpleague.com/installation Use this command to install the core Omnipay library and the PayPal gateway. This is the standard installation for most users. ```bash composer require league/omnipay:^3 omnipay/paypal ``` -------------------------------- ### Install Omnipay with Custom HTTP Client Source: https://omnipay.thephpleague.com/installation Install Omnipay with the common package and a specific PHP-HTTP client adapter if you prefer not to use the default Guzzle client. This example uses the Buzz adapter. ```bash composer require omnipay/common:^3 omnipay/paypal php-http/buzz-adapter ``` -------------------------------- ### Install All Omnipay Gateways Source: https://omnipay.thephpleague.com/changelog Use this metapackage in composer.json to install all officially supported Omnipay gateways. ```json { "require": { "omnipay/omnipay": "~2.0" } } ``` -------------------------------- ### Authorize Payment and Set Details Later Source: https://omnipay.thephpleague.com/api/authorizing This example shows how to initiate an authorize request and then set the card and amount using setter methods. This is an alternative to passing all options in the initial array. ```php $request = $gateway->authorize(['returnUrl' => 'https://www.example.com/return']); $request->setCard($card); $request->setAmount('10.00'); ``` -------------------------------- ### Install Individual Omnipay Gateway Source: https://omnipay.thephpleague.com/changelog Migrate to an individual gateway by updating composer.json to reference the specific gateway package. 'omnipay/common' is included automatically. ```json { "require": { "omnipay/paypal": "~2.0" } } ``` -------------------------------- ### Get Default Gateway Parameters Source: https://omnipay.thephpleague.com/gateways/configuring Retrieve the default configuration parameters for a gateway using getDefaultParameters(). This helps understand available settings and their types. ```php $settings = $gateway->getDefaultParameters(); // default settings array format: array( 'username' => '', // string variable 'testMode' => false, // boolean variable 'landingPage' => array('billing', 'login'), // enum variable, first item should be treated as default ); ``` -------------------------------- ### Handling Redirect Responses Source: https://omnipay.thephpleague.com/api/responses Determine if a payment response requires a redirect and initiate the redirect process. This example shows checking for success, redirect, or failure, and then either redirecting the customer or handling the failure. ```php $response = $gateway->purchase(['amount' => '10.00', 'card' => $card])->send(); if ($response->isSuccessful()) { // payment is complete } elseif ($response->isRedirect()) { $response->redirect(); // this will automatically forward the customer } else { // not successful } ``` -------------------------------- ### Successful Response Methods Source: https://omnipay.thephpleague.com/api/responses Check the status of a payment, retrieve a transaction reference, and get a message from the gateway. Most gateways provide additional methods for gateway-specific fields. ```php $response = $gateway->purchase(['amount' => '10.00', 'card' => $card])->send(); $response->isSuccessful(); // is the response successful? $response->isRedirect(); // is the response a redirect? $response->getTransactionReference(); // a reference generated by the payment gateway $response->getMessage(); // a message generated by the payment gateway ``` -------------------------------- ### Retrieving Redirect Details Source: https://omnipay.thephpleague.com/api/responses Get the URL and any necessary POST data for off-site redirects. This allows for custom display of redirect pages or handling redirects within AJAX calls. ```php $url = $response->getRedirectUrl(); // for a form redirect, you can also call the following method: $data = $response->getRedirectData(); // associative array of fields which must be posted to the redirectUrl ``` -------------------------------- ### Initialize a Gateway Source: https://omnipay.thephpleague.com/gateways/configuring Use Omnipay::create() to instantiate a gateway and set individual parameters like username and password. ```php use Omnipay\Omnipay; $gateway = Omnipay::create('PayPal_Express'); $gateway->setUsername('adrian'); $gateway->setPassword('12345'); ``` -------------------------------- ### Initialize Gateway with Multiple Parameters Source: https://omnipay.thephpleague.com/gateways/configuring Initialize a gateway by passing an array of parameters to the initialize() method. This merges provided settings with defaults. ```php $gateway->initialize([ 'username' => 'adrian', 'password' => '12345', ]); ``` -------------------------------- ### Create Gateway Using Omnipay Class Source: https://omnipay.thephpleague.com/changelog Use the Omnipay class for static gateway creation if you prefer simplicity. This internally uses GatewayFactory. ```php // at the top of your PHP file use Omnipay\Omnipay; // further down when you need to create the gateway $gateway = Omnipay::create('PayPal_Express'); ``` -------------------------------- ### Initialize CreditCard with Form Data Source: https://omnipay.thephpleague.com/api/cards Initialize a CreditCard object with an array of form data. Unrecognized fields will be ignored. ```php $formInputData = array( 'firstName' => 'Bobby', 'lastName' => 'Tables', 'number' => '4111111111111111', ); $card = new CreditCard($formInputData); ``` -------------------------------- ### Instantiate GatewayFactory Source: https://omnipay.thephpleague.com/changelog Create an instance of GatewayFactory to use dependency injection for creating gateways. The static GatewayFactory::create() method is no longer supported. ```php $factory = new GatewayFactory(); $gateway = $factory->create('PayPal_Express'); ``` -------------------------------- ### Complete Purchase Source: https://omnipay.thephpleague.com/api/charging Handles the return from off-site gateways after a purchase. ```APIDOC ## completePurchase($options) ### Description Handle return from off-site gateways after purchase. ### Parameters #### Request Body - **options** (array) - Required - An array of options for completing the purchase. The exact same arguments should be provided as when the initial `purchase` call was made (some gateways will need to verify for example the actual amount paid equals the amount requested). The only parameter you can omit is `card`. ``` -------------------------------- ### PHPUnit 5 vs PHPUnit 6 Exception Handling Source: https://omnipay.thephpleague.com/changelog Illustrates the change in exception assertion syntax from PHPUnit 5 to PHPUnit 6, moving from setExpectedException to expectException and expectExceptionMessage. ```php // PHPUnit 5: $this->setExpectedException($class, $message); ``` ```php // PHPUnit 6: $this->expectException($class); $this->expectExceptionMessage($message); ``` -------------------------------- ### V3 JSON Request Handling Source: https://omnipay.thephpleague.com/changelog Demonstrates how to make a JSON request using Omnipay v3's HTTPlug client. It includes setting appropriate headers and decoding the JSON response. ```php // Example JSON request: $response = $this->httpClient->request('POST', $this->endpoint, [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', ], json_encode($data)); $result = json_decode($response->getBody()->getContents(), true); ``` -------------------------------- ### Complete Authorization Source: https://omnipay.thephpleague.com/api/authorizing Handle the return from off-site gateways after an authorization has been initiated. On-site gateways may not need to implement this. ```APIDOC ## completeAuthorize($options) ### Description Handle return from off-site gateways after authorization. On-site gateways do not need to implement this method and will throw `BadMethodCallException` if called. ### Method `completeAuthorize` ### Parameters #### Options Array (`$options`) - **card** (CreditCard) - Optional - The customer's credit card details. Can be omitted for this call. - **token** (string) - Optional - A token representing the customer's payment method. - **amount** (string) - Required - The amount to authorize (e.g., '10.00' for $10.00). - **currency** (string) - Optional - The currency of the amount. - **description** (string) - Optional - A description of the transaction. - **transactionId** (string) - Optional - A unique identifier for the transaction. - **clientIp** (string) - Optional - The IP address of the client making the request. - **returnUrl** (string) - Optional - The URL to redirect the user to after authorization. - **cancelUrl** (string) - Optional - The URL to redirect the user to if they cancel the authorization. *Note: The exact same arguments should be provided as when the initial `authorize` call was made, with the exception of the `card` parameter which can be omitted.* ``` -------------------------------- ### Purchase using Card Reference Source: https://omnipay.thephpleague.com/api/token-billing Use a stored card reference to create a purchase. Ensure the card reference is valid and supported by the gateway. ```php $gateway->purchase(['amount' => '10.00', 'cardReference' => 'abc']); ``` -------------------------------- ### V2 vs V3 XML Request Handling Source: https://omnipay.thephpleague.com/changelog Compares the XML request handling between Omnipay v2 and v3. V3 requires explicit use of HTTPlug client methods and PSR-7 response handling. ```php // V2 XML: $response = $this->httpClient->post($this->endpoint, null, $data)->send(); $result = $httpResponse->xml(); ``` ```php // V3 XML: $response = $this->httpClient->request('POST', $this->endpoint, [], http_build_query($data)); $result = simplexml_load_string($httpResponse->getBody()->getContents()); ``` -------------------------------- ### Successful Response Handling Source: https://omnipay.thephpleague.com/api/responses Demonstrates how to check if a payment was successful and retrieve transaction details. ```APIDOC ## Successful Response For a successful responses, a reference will normally be generated, which can be used to capture or refund the transaction at a later date. The following methods are always available: ```php $response = $gateway->purchase(['amount' => '10.00', 'card' => $card])->send(); $response->isSuccessful(); // is the response successful? $response->isRedirect(); // is the response a redirect? $response->getTransactionReference(); // a reference generated by the payment gateway $response->getMessage(); // a message generated by the payment gateway ``` In addition, most gateways will override the response object, and provide access to any extra fields returned by the gateway. ``` -------------------------------- ### Purchase Source: https://omnipay.thephpleague.com/api/charging Authorizes and immediately captures an amount on the customer's card. ```APIDOC ## purchase($options) ### Description Authorize and immediately capture an amount on the customer's card. ### Parameters #### Request Body - **options** (array) - Required - An array of options for the purchase. ``` -------------------------------- ### Basic Payment Purchase with Omnipay Source: https://omnipay.thephpleague.com/simple-example Use this snippet to perform a basic purchase using a payment gateway. Ensure the gateway is configured with the correct API key and card details are provided in the correct format. ```php use Omnipay\Omnipay; // Setup payment gateway $gateway = Omnipay::create('Stripe'); $gateway->setApiKey('abc123'); // Example form data $formData = [ 'number' => '4242424242424242', 'expiryMonth' => '6', 'expiryYear' => '2016', 'cvv' => '123' ]; // Send purchase request $response = $gateway->purchase( [ 'amount' => '10.00', 'currency' => 'USD', 'card' => $formData ] )->send(); // Process response if ($response->isSuccessful()) { // Payment was successful print_r($response); } elseif ($response->isRedirect()) { // Redirect to offsite payment gateway $response->redirect(); } else { // Payment failed echo $response->getMessage(); } ``` -------------------------------- ### Redirect Response Handling Source: https://omnipay.thephpleague.com/api/responses Explains how to handle responses that require redirecting the customer to an off-site payment form. ```APIDOC ## Redirect Response The redirect response is further broken down by whether the customer’s browser must redirect using GET (RedirectResponse object), or POST (FormRedirectResponse). These could potentially be combined into a single response class, with a `getRedirectMethod()`. After processing a payment, the cart should check whether the response requires a redirect, and if so, redirect accordingly: ```php $response = $gateway->purchase(['amount' => '10.00', 'card' => $card])->send(); if ($response->isSuccessful()) { // payment is complete } elseif ($response->isRedirect()) { $response->redirect(); // this will automatically forward the customer } else { // not successful } ``` The customer isn’t automatically forwarded on, because often the cart or developer will want to customize the redirect method (or if payment processing is happening inside an AJAX call they will want to return JS to the browser instead). To display your own redirect page, simply call `getRedirectUrl()` on the response, then display it accordingly: ```php $url = $response->getRedirectUrl(); // for a form redirect, you can also call the following method: $data = $response->getRedirectData(); // associative array of fields which must be posted to the redirectUrl ``` ``` -------------------------------- ### Authorize Payment with Card Details Source: https://omnipay.thephpleague.com/api/authorizing Use this snippet to authorize a payment amount using a CreditCard object and other relevant options. Ensure all required parameters like amount, card, and returnUrl are provided. ```php $card = new CreditCard($formData); $request = $gateway->authorize([ 'amount' => '10.00', // this represents $10.00 'card' => $card, 'returnUrl' => 'https://www.example.com/return', ]); ``` -------------------------------- ### Authorize Payment Source: https://omnipay.thephpleague.com/api/authorizing Authorize an amount on the customer's card. This is the primary method for initiating an authorization. ```APIDOC ## authorize($options) ### Description Authorize an amount on the customer's card. ### Method `authorize` ### Parameters #### Options Array (`$options`) - **card** (CreditCard) - Required - The customer's credit card details. - **token** (string) - Optional - A token representing the customer's payment method. - **amount** (string) - Required - The amount to authorize (e.g., '10.00' for $10.00). - **currency** (string) - Optional - The currency of the amount. - **description** (string) - Optional - A description of the transaction. - **transactionId** (string) - Optional - A unique identifier for the transaction. - **clientIp** (string) - Optional - The IP address of the client making the request. - **returnUrl** (string) - Optional - The URL to redirect the user to after authorization. - **cancelUrl** (string) - Optional - The URL to redirect the user to if they cancel the authorization. ### Request Example ```php $card = new CreditCard($formData); $request = $gateway->authorize([ 'amount' => '10.00', 'card' => $card, 'returnUrl' => 'https://www.example.com/return', ]); ``` ### Request Example (using setters) ```php $request = $gateway->authorize(['returnUrl' => 'https://www.example.com/return']); $request->setCard($card); $request->setAmount('10.00'); ``` ``` -------------------------------- ### Handle Gateway and Communication Errors Source: https://omnipay.thephpleague.com/api/error-handling Wrap payment requests in a try-catch block to handle both gateway-specific errors and communication failures. Check the response for success, redirection, or displayable error messages. ```php try { $response = $gateway->purchase(['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.'); } ``` -------------------------------- ### Token Billing Methods Source: https://omnipay.thephpleague.com/api/token-billing These methods allow you to manage stored credit card tokens with your payment gateway. Note that not all gateways support all methods. ```APIDOC ## Token Billing Token billing allows you to store a credit card with your gateway, and charge it at a later date. Token billing is not supported by all gateways. For supported gateways, the following methods are available: ### `createCard($options)` - **Description**: Creates a token for a credit card, allowing it to be charged later. - **Returns**: A response object which includes a `cardReference`, which can be used for future transactions. ### `updateCard($options)` - **Description**: Updates a stored credit card token. Not all gateways support this method. ### `deleteCard($options)` - **Description**: Removes a stored credit card token. Not all gateways support this method. ### Using a Card Reference for Charges Once you have a `cardReference`, you can use it instead of the `card` parameter when creating a charge: ```php $gateway->purchase([ 'amount' => '10.00', 'cardReference' => 'abc' ]); ``` ``` -------------------------------- ### Access and Set CreditCard Fields Source: https://omnipay.thephpleague.com/api/cards Access CreditCard fields using getter methods and modify them using setter methods. ```php $number = $card->getNumber(); $card->setFirstName('Adrian'); ``` -------------------------------- ### Add Line-Item Data to Request Source: https://omnipay.thephpleague.com/changelog Set line item details for a request, currently supported by the PayPal gateway. Each item can include name, quantity, and price. ```php $request->setItems(array( array('name' => 'Food', 'quantity' => 1, 'price' => '40.00'), array('name' => 'Drinks', 'quantity' => 2, 'price' => '6.00'), )); ``` -------------------------------- ### Validate Card Number with Luhn Algorithm Source: https://omnipay.thephpleague.com/api/cards Verify a card number using the Luhn algorithm before submitting it to a gateway. ```php Helper::validateLuhn($number); ``` -------------------------------- ### Refund Transaction Source: https://omnipay.thephpleague.com/api/refunds The `refund` method is implemented by gateways to process a refund for an already completed transaction. If a gateway does not support refunds, it will raise a `BadMethodCallException`. ```APIDOC ## refund($options) ### Description Refund an already processed transaction. ### Method This is a method call within the Omnipay library, not an HTTP endpoint. ### Parameters #### Parameters - **options** (array) - Required - An associative array of options for the refund. The specific keys required will depend on the gateway implementation. ### Request Example ```php // Assuming $gateway is an initialized Omnipay gateway instance $result = $gateway->refund(array( 'transactionId' => '12345', 'amount' => '10.00', 'currency' => 'USD', 'reason' => 'Item returned by customer', ))->send(); ``` ### Response #### Success Response The success response will vary depending on the gateway, but typically indicates whether the refund was successful. #### Response Example ```php // Example success response structure (may vary by gateway) // $result->isSuccessful() would return true // $result->getTransactionReference() might return a refund transaction ID ``` ### Error Handling If a gateway does not support refunds, it will throw an `BadMethodCallException`. ``` -------------------------------- ### Capture Authorized Amount Source: https://omnipay.thephpleague.com/api/authorizing Capture an amount that has been previously authorized. ```APIDOC ## capture($options) ### Description Capture an amount you have previously authorized. ### Method `capture` ### Parameters #### Options Array (`$options`) - **card** (CreditCard) - Required - The customer's credit card details. - **token** (string) - Optional - A token representing the customer's payment method. - **amount** (string) - Required - The amount to capture (e.g., '10.00' for $10.00). - **currency** (string) - Optional - The currency of the amount. - **description** (string) - Optional - A description of the transaction. - **transactionId** (string) - Optional - A unique identifier for the transaction. - **clientIp** (string) - Optional - The IP address of the client making the request. - **returnUrl** (string) - Optional - The URL to redirect the user to after authorization. - **cancelUrl** (string) - Optional - The URL to redirect the user to if they cancel the authorization. ``` -------------------------------- ### Modify Request Data Before Sending Source: https://omnipay.thephpleague.com/changelog Use the sendData() method to modify request data, allowing for custom parameters before the request is sent to the gateway. This is an alternative to the standard send() method. ```php // standard method - send default data $response = $request->send(); // new method - get and send custom data $data = $request->getData(); $data['customParameter'] = true; $response = $request->sendData($data); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.