bunq API Documentation
SDK'sPostman Collection
  • Getting Started
    • Welcome to the bunq API documentation
    • Tools
      • Software Development Kits (SDKs)
        • PHP
          • Usage
          • Tests
          • Exceptions
        • Java
          • Usage
          • Tests
          • Exceptions
        • Python
          • Usage
          • Tests
          • Exceptions
        • C#
          • Usage
          • Tests
          • Exceptions
      • Postman
      • Android Emulator
      • Developers Portal
  • Basics
    • bunq API Objects
      • User
      • Monetary Account
      • Payment
      • RequestInquiry
      • Card
      • Attachment and Note Attachment
    • API Context, Device Installation and Session
    • Authentication
      • API Keys
      • OAuth
    • Pagination
    • Errors
    • Rate Limits
    • Response body formatting
    • Moving to production
    • Headers
  • NOT SO BASICS
    • Signing
      • Python Code Example
        • Full main.py
        • Full bunq_lib.py
        • Full signing.py
      • PHP Code Example
    • Callbacks (Webhooks)
  • PSD2
    • Are you a Third Party Provider (TPP)? Start here!
      • Register as a TPP
      • Change your avatar
    • Account Information Service Provider (AISP)
    • Payment Initiation Service Provider (PISP)
    • Card-Based Payment Instrument Issuer (CBPII)
  • Support
    • FAQ
    • bunq status page
    • Terms and Conditions
  • TUTORIALS
    • Your first payment
      • Introduction
      • Creating a sandbox user and getting an API key
      • Creating the API Context
        • Creating the Installation
        • Device Registration
        • Start a Session
      • Setting up a sandbox user
        • Retrieving my user details
        • Getting sandbox money on the user account
        • Sandbox version of the bunq app
      • First Payments
    • Receiving payments on your website using bunq.me
    • How to manage your cards
      • Introduction
      • Ordering a card
      • Setting the card Limit and changing the PIN code
  • API Reference
    • Start here
    • Additional Transaction Information Category
    • Additional Transaction Information Category User Defined
    • Attachment
    • Attachment Public
    • Avatar
    • Billing Contract Subscription
    • bunqme
      • bunqme Tab
      • bunqme Fundraiser Profile
      • bunqme Tab Response
      • bunqme Fundraiser Result
    • Callback URL OAuth
    • Cards
      • Card
      • Card-Batch
      • Card Credit
      • Card Debit
      • Card Name
      • Card Replace
  • Confirmation Of Funds
  • Content and Exports
  • Currency Cloud
    • Currency cloud Benificiairy
    • Payment Quote
  • Currency Conversion
    • Convert
    • Quotes
  • Customer Statements
  • Devices
  • Draft Payment
  • Event
  • Exports
    • Export Annual Overview
    • Export RIB
    • Export Statement Card
  • Generated CVC2
  • Ideal Merchant Transaction
  • Insights
  • Installation
  • Invoice
  • Invoice Export
  • Legal Name
  • Limit
  • Mastercard Action
  • Monetary Account
    • Monetary Account Bank
    • Monetary Account Card
    • Monetary Account External
    • Monetary Account External Savings
    • Monetary Account Joint
    • Monetary Account Savings
    • Monetary Account Savings External
  • Name
  • Note Text & Attachment
    • Adyen Card Transaction
    • Switch Service Payment
    • bunqme fundraiser result
    • Draft Payment
    • Ideal Merchant Transaction
    • Mastercard Action
    • Open Banking Merchant
    • Payment Batch
    • Payment Delayed
    • Payment
    • Request Inquiry Batch
    • Request Response
    • Schedule Payment
    • Schedule Request
    • Sofort
    • Whitelist Result
  • Notification Filter
    • Notification Filter Email
    • Notification Filter Failure
    • Notification Filter Push
    • Notification Filter URL
  • OAuth
  • Payment
    • Payment
    • Payment Auto Allocate
    • Payment Batch
  • Payment Auto Allocation
  • Payment Service Provider
    • Payment Service Provider Credential
    • Payment Service Provider Draft Payment
    • Payment Service Provider Issuer Transaction
  • Request
    • Request Inquiry
    • Request Inquiry Batch
    • Request Response
  • Sandbox Users
  • Schedule
    • Schedule Instance
    • Schedule Payment
    • Schedule Payment Batch
  • Server Error
  • Server Public Key
  • Session
  • [deprecated] Share Invite Monetary Account Inquiry
  • Share Invite Monetary Account Response
  • Sofort Merchant Transaction
  • Statement
  • Switch Service Payment
  • Token QR Request Sofort
  • Transferwise
    • Transferwise Currency
    • Transferwise Quote
    • Transferwise Recipient
    • Transferwise Recipient Requirement
    • Transferwise Transfer
    • Transferwise Transfer Requirement
    • Transferwise User
  • Tree Progress
  • User
    • User Person
    • User Company
    • User Payment Service Provider
  • Whitelist SSD
    • Whitelist SSD One Off
    • Whitelist SSD Recurring
  • Content
Powered by GitBook
On this page
  • Creating an API context
  • Basic Operations
  • User Context Helper Methods

Was this helpful?

  1. Getting Started
  2. Tools
  3. Software Development Kits (SDKs)
  4. PHP

Usage

Creating an API context

In order to start making calls with the bunq API, you must first register your API key and device, and create a session. In the SDKs, we group these actions and call it "creating an API context". There are two ways to do it. One is through our interactive script, and the other is programmatically from your code.

src/Util/InstallationUtil.php

Creating an API context using bunq-install interactive script

After installing bunq SDK into your project, run the command below from your project root folder:

$ vendor/bin/bunq-install

And then follow the steps the script offers.

Creating an API context programmatically

The context can be created by executing the following code snippet:

use bunq\Context\ApiContext;
use bunq\Util\BunqEnumApiEnvironmentType;
use bunq\Util\InstallationUtil;

// Automatically install and save the API context
InstallationUtil::automaticInstall(
    BunqEnumApiEnvironmentType::SANDBOX(), // Use PRODUCTION() for production
    '/path/to/save/context.conf'
);

Load the API Context:

use bunq\Context\BunqContext;

BunqContext::loadApiContext(
    ApiContext::restore('/path/to/saved/context.conf')
);

Please note: initializing your application is a heavy task and it is recommended to do it only once per device.

PSD2

It is possible to create an ApiContext as PSD2 Service Provider. Although this might seem a complex task, we wrote some helper implementations to get you started. You need to create a certificate and private key to get you started. Our sandbox environment currently accepts all certificates, if these criteria are met:

  • Up to 64 characters

  • PISP and/or AISP used in the end.

Make sure you have your unique eIDAS certificate number and certificates ready when you want to perform these tasks on our production environment.

Creating a PSD2 context is very easy:

$apiContext = ApiContext::createForPsd2(
    BunqEnumApiEnvironmentType::SANDBOX(), // Could be PRODUCTION as well.
    SecurityUtil::getCertificateFromFile($pathToCertificate),
    SecurityUtil::getPrivateKeyFromFile($pathToKey),
    [
        SecurityUtil::getCertificateFromFile($pathToCertificateInChain), // Could be one file containing chain, or multiple certificate files in array.
    ],
    $description
)

Proxy

You can use a proxy with the bunq PHP SDK. This option must be a string. This proxy will be used for all requests done with the context for which it was provided. You will be prompted to provide a proxy URL when using the interactive installation script.

$proxyUrl = 'socks5://localhost:1080'; // The proxy for all requests, null to disable

$apiContext = ApiContext::create(
    ...
    $proxyUrl
);

Safety considerations

The file storing the context details (i.e. bunq.conf) is a key to your account. Anyone having access to it is able to perform any Public API actions with your account. Therefore, we recommend choosing a truly safe place to store it.

If you rather save the context in a database, you can use the fromJson() and toJson() methods.

Making API calls

There is a class for each endpoint. Each class has functions for each supported action. These actions can be create, get, update, delete and listing.

Before you can start making calls, you must ensure that you have create an ApiContext and loaded in into BunqContext as shown in the examples above.

The SDK will take care of your user Id, as this id will never change per ApiContext. The SDK also uses your first active monetary account as primary monetary account. This is almost always the same as your billing account. This means that when you do not explicitly pass a Monetary Account ID, the SDK will use the Monetary Account ID of your billing account.

Basic Operations

Monetary Accounts

Create a monetary account:

use bunq\Model\Generated\Endpoint\MonetaryAccountBankApiObject;

$accountId = MonetaryAccountBankApiObject::create(
    'EUR',                     // Currency
    'My account description'   // Description
)->getValue();

Get account details:

$monetaryAccount = MonetaryAccountBankApiObject::get($accountId)->getValue();

Close a monetary account:

MonetaryAccountBankApiObject::update(    
    $accountId,    
    null,      // New description (null = no change)    
    null,      // Avatar (null = no change)    
    null,      // Status (null = no change)    
    'CANCELLED',  // Status    
    'REDEMPTION_VOLUNTARY',  // Sub-status    
    'OTHER',   // Reason    
    'Closing this test account'  // Reason description
);

Payments

Make a payment:

use bunq\Model\Generated\Endpoint\PaymentApiObject;
use bunq\Model\Generated\Object\AmountObject;
use bunq\Model\Generated\Object\PointerObject;

// Create payment to another user
$payment = PaymentApiObject::create(
    new AmountObject('0.01', 'EUR'),  // Amount and currency    
    new PointerObject('EMAIL', 'recipient@example.com'),  // Recipient    
    'Payment description'  // Description
);

Make a payment to another monetary account:

// Get the IBAN pointer of the recipient account
$recipientAccountAlias = $monetaryAccount->getAlias()[0]; // Get the first alias
$paymentId = PaymentApiObject::create(
    new AmountObject('0.01', 'EUR'),    
    $recipientAccountAlias,    
    'Payment description'
);

Batch Payments

use bunq\Model\Generated\Endpoint\PaymentBatchApiObject;

// Create an array of payments
$payments = [];for ($i = 0; $i < 10; $i++) {
    $payment = new PaymentApiObject(
            new AmountObject('0.01', 'EUR'),
            new PointerObject('EMAIL', 'recipient@example.com'),        
            'Batch payment #' . $i    
    );    
    $payments[] = $payment;
}

// Create the batch payment
$batchId = PaymentBatchApiObject::create($payments)->getValue();

Payment Requests

Create a payment request:

use bunq\Model\Generated\Endpoint\RequestInquiryApiObject;

$requestId = RequestInquiryApiObject::create(
    new AmountObject('0.01', 'EUR'),    
    new PointerObject('EMAIL', 'recipient@example.com'),    
    'Request description',    
    false  // Don't allow bunqme
)->getValue();

Accept a payment request:

use bunq\Model\Generated\Endpoint\RequestResponseApiObject;

// List responses to find the ID
$responses = RequestResponseApiObject::listing($monetaryAccountId)->getValue();
$requestResponseId = $responses[0]->getId();

// Accept the request
RequestResponseApiObject::update(
    $requestResponseId,
    $monetaryAccountId,    
    null,    
    'ACCEPTED'  // Status
);

bunq.me

Create a bunqme tab:

use bunq\Model\Generated\Endpoint\BunqMeTabApiObject;
use bunq\Model\Generated\Endpoint\BunqMeTabEntryApiObject;

$tabId = BunqMeTabApiObject::create(
    new BunqMeTabEntryApiObject(
            new AmountObject('0.01', 'EUR'),        
            'Tab description'    
    )
)->getValue();

// Get tab details
$tab = BunqMeTabApiObject::get($tabId);

Attachments

Create a public attachment:

use bunq\Http\ApiClient;
use bunq\Model\Generated\Endpoint\AttachmentPublicApiObject;

// Read the file content
$fileContents = file_get_contents('/path/to/file.png');

// Create the attachment
$attachmentUuid = AttachmentPublicApiObject::create(
    $fileContents,
    [
            ApiClient::HEADER_CONTENT_TYPE => 'image/png',        
            ApiClient::HEADER_ATTACHMENT_DESCRIPTION => 'Attachment description'    
    ]
)->getValue();

Get attachment content:

use bunq\Model\Generated\Endpoint\AttachmentPublicContentApiObject;

$fileContents = AttachmentPublicContentApiObject::listing($attachmentUuid)->getValue();

Avatar

Create an avatar:

use bunq\Model\Generated\Endpoint\AvatarApiObject;

// First create a public attachment
$attachmentUuid = AttachmentPublicApiObject::create(
    $fileContents,    
    [
            ApiClient::HEADER_CONTENT_TYPE => 'image/png',        
            ApiClient::HEADER_ATTACHMENT_DESCRIPTION => 'Avatar image'    
    ]
)->getValue();

// Create the avatar using the attachment
$avatarUuid = AvatarApiObject::create($attachmentUuid)->getValue();

Cards

Get allowed card names:

use bunq\Model\Generated\Endpoint\CardNameApiObject;

$cardNamesAllowed = CardNameApiObject::listing()->getValue();
$possibleNames = $cardNamesAllowed[0]->getPossibleCardNameArray();

Order a debit card:

use bunq\Model\Generated\Endpoint\CardDebitApiObject;
use bunq\Model\Generated\Object\CardPinAssignmentObject;

$cardDebit = CardDebitApiObject::create(
    'My Card',                   // Card description    
    $possibleNames[0],           // Name on card    
    'MASTERCARD',                // Card type    
    'MASTERCARD_DEBIT',          // Product type    
    $userAlias->getName(),       // Second line on card    
    $userAlias,                  // User alias    
    [                           // PIN assignments
            new CardPinAssignmentObject(
                        'PRIMARY',           // PIN assignment type            
                        'MANUAL',            // Routing type            
                        '1234',              // PIN code            
                        $primaryAccountId    // Account ID        
            ),    
    ]
)->getValue();

Notifications (webhooks)

Create notification filters for a monetary account:

use bunq\Model\Generated\Endpoint\NotificationFilterUrlMonetaryAccountInternal;
use bunq\Model\Generated\Object\NotificationFilterUrlObject;

$filter = new NotificationFilterUrlObject(
    'MUTATION',                    // Category    
    'https://example.com/callback'  // Callback URL
);

$filters = NotificationFilterUrlMonetaryAccountInternal::createWithListResponse(
    $monetaryAccountId,    
    [$filter]
)->getValue();

Create notification filters for a user:

use bunq\Model\Generated\Endpoint\NotificationFilterUrlUserInternal;

$filter = new NotificationFilterUrlObject(
    'MUTATION',    
    'https://example.com/callback'
);

$filters = NotificationFilterUrlUserInternal::createWithListResponse(
    [$filter]
)->getValue();

Create push notification filters:

use bunq\Model\Generated\Endpoint\NotificationFilterPushUserInternal;
use bunq\Model\Generated\Object\NotificationFilterPushObject;

$filter = new NotificationFilterPushObject('MUTATION');
$filters = NotificationFilterPushUserInternal::createWithListResponse(
    [$filter]
)->getValue();

OAuth

Create OAuth authorization URI:

use bunq\Model\Core\BunqEnumOauthResponseType;
use bunq\Model\Core\OauthAuthorizationUri;
use bunq\Model\Generated\Endpoint\OauthClientApiObject;

$authUri = OauthAuthorizationUri::create(
    BunqEnumOauthResponseType::CODE(),    
    'https://redirect.example.com',    
    new OauthClientApiObject('client_status'),    
    'state_parameter'
)->getAuthorizationUriString();

Session Management

Delete a session:

use bunq\Model\Generated\Endpoint\SessionApiObject;

SessionApiObject::delete(0);  // 0 refers to the current session

Reset a session:

BunqContext::getApiContext()->resetSession();
BunqContext::getApiContext()->save('/path/to/context.conf');

User Context Helper Methods

// Get the primary monetary account
$primaryAccount = BunqContext::getUserContext()->getPrimaryMonetaryAccount();

// Get the user alias
$userAlias = null;
if (BunqContext::getUserContext()->isOnlyUserPersonSet()) {
    $userAlias = BunqContext::getUserContext()->getUserPerson()->getAlias()[0];
} elseif (BunqContext::getUserContext()->isOnlyUserCompanySet()) {
    $userAlias = BunqContext::getUserContext()->getUserCompany()->getAlias()[0];
} elseif (BunqContext::getUserContext()->isOnlyUserApiKeySet()) {
    $userAlias = BunqContext::getUserContext()
            ->getUserApiKey()        
            ->getRequestedByUser()        
            ->getReferencedObject()        
            ->getAlias()[0];
}

// Refresh user context
BunqContext::getUserContext()->refreshUserContext();

Reading objects

To use the read method you must pass the identifier of the object to read (ID or UUID) except for the endpoints User, UserPerson, UserCompany and MonetaryAccount. The SDK will use the default IDs when none are passed. For all other endpoints you must pass the identifier.

This type of calls always returns a model.

BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

$userCompany = UserCompany::get();

printf($userCompany->getPublicNickName());

Updating objects

BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

MonetaryAccountBank::update(
    $monetaryAccount->getId(),
    $description
);

Deleting objects

BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

CustomerStatementExport::delete($customerStatementExportId);

Listing objects

BunqContext::loadApiContext($apiContext); // if it has not been loaded yet. 

$monetaryAccountList = MonetaryAccount::listing();

foreach ($monetaryAccountList as $monetaryAccount) {
    printf($monetaryAccount->getMonetaryAccountBank->getDescription() . PHP_EOL);
}

PreviousPHPNextTests

Last updated 26 days ago

Was this helpful?

This context can be saved the same way as a normal ApiContext. After creating this context, create an OAuth client to get your users to grant you access. For a more detailed example, check the repository.

tinker_php