mollie / mollie-api-php

Mollie API client for PHP
http://www.mollie.com
BSD 2-Clause "Simplified" License
554 stars 191 forks source link

Mollie API client for PHP

mollie-api-php-header

Accepting iDEAL, Apple Pay, Bancontact, SOFORT Banking, Creditcard, SEPA Bank transfer, SEPA Direct debit, PayPal, Belfius Direct Net, KBC/CBC, paysafecard, ING Home'Pay, Giropay, EPS, Przelewy24, Postepay, In3, Klarna (Pay now, Pay later, Slice it, Pay in 3), Giftcard and Voucher online payments without fixed monthly costs or any punishing registration procedures. Just use the Mollie API to receive payments directly on your website or easily refund transactions to your customers.

Build Status Latest Stable Version Total Downloads

Requirements

To use the Mollie API client, the following things are required:

For leveraging Mollie Connect (advanced use cases only), we recommend also installing our OAuth2 client.

Installation

Using Composer

The easiest way to install the Mollie API client is by using Composer. You can require it with the following command:

composer require mollie/mollie-api-php

To work with the most recent API version, ensure that you are using a version of this API client that is equal to or greater than 2.0.0. If you prefer to continue using the v1 API, make sure your client version is below 2.0.0. For guidance on transitioning from v1 to v2, please refer to the migration notes.

Manual Installation

If you're not familiar with using composer we've added a ZIP file to the releases containing the API client and all the packages normally installed by composer. Download the mollie-api-php.zip from the releases page.

Include the vendor/autoload.php as shown in Initialize example.

Usage

Initializing the Mollie API client, and setting your API key.

$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey("test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM");

With the MollieApiClient you can now access any of the following endpoints by selecting them as a property of the client:

API Resource Code Link to Endpoint file
Balances API Balance $mollie->balances BalanceEndpoint
Balance Report $mollie->balanceReports BalanceReportEndpoint
Balance Transaction $mollie->balanceTransactions BalanceTransactionEndpoint
Chargebacks API Chargeback $mollie->chargebacks ChargebackEndpoint
Payment Chargeback $mollie->paymentChargebacks PaymentChargebackEndpoint
Clients API Client $mollie->clients ClientEndpoint
Client Links API Client Link $mollie->clientLinks ClientLinkEndpoint
Customers API Customer $mollie->customers CustomerEndpoint
Customer Payment $mollie->customerPayments CustomerPaymentsEndpoint
Invoices API Invoice $mollie->invoices InvoiceEndpoint
Mandates API Mandate $mollie->mandates MandateEndpoint
Methods API Payment Method $mollie->methods MethodEndpoint
Onboarding API Onboarding $mollie->onboarding OnboardingEndpoint
Orders API Order $mollie->orders OrderEndpoint
Order Line $mollie->orderLines OrderLineEndpoint
Order Payment $mollie->orderPayments OrderPaymentEndpoint
Organizations API Organization $mollie->organizations OrganizationEndpoint
Organization Partner $mollie->organizationPartners OrganizationPartnerEndpoint
Captures API Payment Captures $mollie->organizations PaymentCaptureEndpoint
Payments API Payment $mollie->payments PaymentEndpoint
Payment Route $mollie->paymentRoutes PaymentRouteEndpoint
Payment links API Payment Link $mollie->paymentLinks PaymentLinkEndpoint
Permissions API Permission $mollie->permissions PermissionEndpoint
Profile API Profile $mollie->profiles ProfileEndpoint
Profile Method $mollie->profileMethods ProfileMethodEndpoint
Refund API Refund $mollie->refunds RefundEndpoint
Order Refund $mollie->orderRefunds OrderRefundEndpoint
Payment Refund $mollie->paymentRefunds PaymentRefundEndpoint
Settlements API Settlement $mollie->settlements SettlementsEndpoint
Settlement Capture $mollie->settlementCaptures SettlementCaptureEndpoint
Settlement Chargeback $mollie->settlementChargebacks SettlementChargebackEndpoint
Settlement Payment $mollie->settlementPayments SettlementPaymentEndpoint
Settlement Refund $mollie->settlementRefunds SettlementRefundEndpoint
Shipments API Shipment $mollie->shipments ShipmentEndpoint
Subscriptions API Subscription $mollie->subscriptions SubscriptionEndpoint
Terminal API Terminal $mollie->terminals TerminalEndpoint
Wallets API Wallet $mollie->wallets WalletEndpoint

Find our full documentation online on docs.mollie.com.

Orders

Creating Orders

Create Order reference

$order = $mollie->orders->create([
    "amount" => [
        "value" => "1027.99",
        "currency" => "EUR",
    ],
    "billingAddress" => [
        "streetAndNumber" => "Keizersgracht 313",
        "postalCode" => "1016 EE",
        "city" => "Amsterdam",
        "country" => "nl",
        "givenName" => "Luke",
        "familyName" => "Skywalker",
        "email" => "luke@skywalker.com",
    ],
    "shippingAddress" => [
        "streetAndNumber" => "Keizersgracht 313",
        "postalCode" => "1016 EE",
        "city" => "Amsterdam",
        "country" => "nl",
        "givenName" => "Luke",
        "familyName" => "Skywalker",
        "email" => "luke@skywalker.com",
    ],
    "metadata" => [
        "some" => "data",
    ],
    "consumerDateOfBirth" => "1958-01-31",
    "locale" => "en_US",
    "orderNumber" => "1234",
    "redirectUrl" => "https://your_domain.com/return?some_other_info=foo",
    "webhookUrl" => "https://your_domain.com/webhook",
    "method" => "ideal",
    "lines" => [
        [
            "sku" => "5702016116977",
            "name" => "LEGO 42083 Bugatti Chiron",
            "productUrl" => "https://shop.lego.com/nl-NL/Bugatti-Chiron-42083",
            "imageUrl" => 'https://sh-s7-live-s.legocdn.com/is/image//LEGO/42083_alt1?$main$',
            "quantity" => 2,
            "vatRate" => "21.00",
            "unitPrice" => [
                "currency" => "EUR",
                "value" => "399.00",
            ],
            "totalAmount" => [
                "currency" => "EUR",
                "value" => "698.00",
            ],
            "discountAmount" => [
                "currency" => "EUR",
                "value" => "100.00",
            ],
            "vatAmount" => [
                "currency" => "EUR",
                "value" => "121.14",
            ],
        ],
        // more order line items
    ],
]);

After creation, the order id is available in the $order->id property. You should store this id with your order.

After storing the order id you can send the customer off to complete the order payment using $order->getCheckoutUrl().

header("Location: " . $order->getCheckoutUrl(), true, 303);

This header location should always be a GET, thus we enforce 303 http response code

For an order create example, see Example - New Order.

Updating Orders

Update Order Documentation

$order = $mollie->orders->get("ord_kEn1PlbGa");
$order->billingAddress->organizationName = "Mollie B.V.";
$order->billingAddress->streetAndNumber = "Keizersgracht 126";
$order->billingAddress->city = "Amsterdam";
$order->billingAddress->region = "Noord-Holland";
$order->billingAddress->postalCode = "1234AB";
$order->billingAddress->country = "NL";
$order->billingAddress->title = "Dhr";
$order->billingAddress->givenName = "Piet";
$order->billingAddress->familyName = "Mondriaan";
$order->billingAddress->email = "piet@mondriaan.com";
$order->billingAddress->phone = "+31208202070";
$order->update();

Refunding Orders

Complete
$order = $mollie->orders->get('ord_8wmqcHMN4U');
$refund = $order->refundAll();

echo 'Refund ' . $refund->id . ' was created for order ' . $order->id;
Partially

When executing a partial refund you have to list all order line items that should be refunded.

$order = $mollie->orders->get('ord_8wmqcHMN4U');
$refund = $order->refund([
    'lines' => [
        [
            'id' => 'odl_dgtxyl',
            'quantity' => 1,
        ],
    ],
    "description" => "Required quantity not in stock, refunding one photo book.",
]);

Cancel Orders

Cancel Order Documentation

When canceling an order it is crucial to check if the order is cancelable before executing the cancel action. For more information see the possible order statuses.

$order = $mollie->orders->get("ord_pbjz8x");

if ($order->isCancelable) {
    $canceledOrder = $order->cancel();
    echo "Your order " . $order->id . " has been canceled.";
} else {
    echo "Unable to cancel your order " . $order->id . ".";
}

Order webhook

When the order status changes, the webhookUrl you specified during order creation will be called. You can use the id from the POST parameters to check the status and take appropriate actions. For more details, refer to Example - Webhook.

Payments

Payment Reception Process

Payment Reception Process documentation

To ensure a successful payment reception, you should follow these steps:

  1. Utilize the Mollie API client to initiate a payment. Specify the desired amount, currency, description, and optionally, a payment method. It's crucial to define a unique redirect URL where the customer should be directed after completing the payment.

  2. Immediately upon payment completion, our platform will initiate an asynchronous request to the configured webhook. This enables you to retrieve payment details, ensuring you know precisely when to commence processing the customer's order.

  3. The customer is redirected to the URL from step (1) and should be pleased to find that the order has been paid and is now in the processing stage.

Creating Payments

Create Payment Documentation

$payment = $mollie->payments->create([
    "amount" => [
        "currency" => "EUR",
        "value" => "10.00"
    ],
    "description" => "My first API payment",
    "redirectUrl" => "https://webshop.example.org/order/12345/",
    "webhookUrl"  => "https://webshop.example.org/mollie-webhook/",
]);

After creation, the payment id is available in the $payment->id property. You should store this id with your order.

After storing the payment id you can send the customer to the checkout using $payment->getCheckoutUrl().

header("Location: " . $payment->getCheckoutUrl(), true, 303);

This header location should always be a GET, thus we enforce 303 http response code

For a payment create example, see Example - New Payment.

Multicurrency

Since API v2.0 it is now possible to create non-EUR payments for your customers. A full list of available currencies can be found in our documentation.

$payment = $mollie->payments->create([
    "amount" => [
        "currency" => "USD",
        "value" => "10.00"
    ],
    //...
]);

After creation, the settlementAmount will contain the EUR amount that will be settled on your account.

Create fully integrated iDEAL payments

To fully integrate iDEAL payments on your website, follow these additional steps:

  1. Retrieve the list of issuers (banks) that support iDEAL.
$method = $mollie->methods->get(\Mollie\Api\Types\PaymentMethod::IDEAL, ["include" => "issuers"]);

Use the $method->issuers list to let the customer pick their preferred issuer.

$method->issuers will be a list of objects. Use the property $id of this object in the API call, and the property $name for displaying the issuer to your customer.

  1. Create a payment with the selected issuer:
$payment = $mollie->payments->create([
    "amount" => [
        "currency" => "EUR",
        "value" => "10.00"
    ],
    "description" => "My first API payment",
    "redirectUrl" => "https://webshop.example.org/order/12345/",
    "webhookUrl"  => "https://webshop.example.org/mollie-webhook/",
    "method"      => \Mollie\Api\Types\PaymentMethod::IDEAL,
    "issuer"      => $selectedIssuerId, // e.g. "ideal_INGBNL2A"
]);

_The _links property of the $payment object will contain an object checkout with a href property, which is a URL that points directly to the online banking environment of the selected issuer. A short way of retrieving this URL can be achieved by using the $payment->getCheckoutUrl()._

For a more in-depth example, see Example - iDEAL payment.

Retrieving Payments

Retrieve Payment Documentation

We can use the $payment->id to retrieve a payment and check if the payment isPaid.

$payment = $mollie->payments->get($payment->id);

if ($payment->isPaid())
{
    echo "Payment received.";
}

Or retrieve a collection of payments.

$payments = $mollie->payments->page();

For an extensive example of listing payments with the details and status, see Example - List Payments.

Refunding payments

Refund Payment Documentation

Our API provides support for refunding payments. It's important to note that there is no confirmation step, and all refunds are immediate and final. Refunds are available for all payment methods except for paysafecard and gift cards.

$payment = $mollie->payments->get($payment->id);

// Refund € 2 of this payment
$refund = $payment->refund([
    "amount" => [
        "currency" => "EUR",
        "value" => "2.00"
    ]
]);

Payment webhook

When the payment status changes, the webhookUrl you specified during payment creation will be called. You can use the id from the POST parameters to check the status and take appropriate actions. For more details, refer to Example - Webhook.

For a working example, see Example - Refund payment.

Enabling debug mode

When troubleshooting, it can be highly beneficial to have access to the submitted request within the ApiException. To safeguard against inadvertently exposing sensitive request data in your local application logs, the debugging feature is initially turned off.

To enable debugging and inspect the request:

/** @var $mollie \Mollie\Api\MollieApiClient */
$mollie->enableDebugging();

try {
    $mollie->payments->get('tr_12345678');
} catch (\Mollie\Api\Exceptions\ApiException $exception) {
    $request = $exception->getRequest();
}

If you are recording instances of ApiException, the request details will be included in the logs. It is vital to ensure that no sensitive information is retained within these logs and to perform cleanup after debugging is complete.

To disable debugging again:

/** @var $mollie \Mollie\Api\MollieApiClient */
$mollie->disableDebugging();

Please note that debugging is only available when using the default Guzzle http adapter (Guzzle6And7MollieHttpAdapter).

API documentation

For an in-depth understanding of our API, please explore the Mollie Developer Portal. Our API documentation is available in English.

Contributing to Our API Client

Would you like to contribute to improving our API client? We welcome pull requests. But, if you're interested in contributing to a technology-focused organization, Mollie is actively recruiting developers and system engineers. Discover our current job openings or reach out.

License

BSD (Berkeley Software Distribution) License. Copyright (c) 2013-2018, Mollie B.V.

Support

Contact: www.mollie.com — info@mollie.com — +31 20 820 20 70