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
  • Core Functionalities
  • Tips for Using the SDK

Was this helpful?

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

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". The context can be created by using the following code snippet:

ApiContext apiContext = ApiContext.create(
    ApiEnvironmentType.SANDBOX,
    sandboxUser.getApiKey(),
    "Your Device Description"
);
apiContext.save("bunq-config.conf");

BunqContext.loadApiContext(apiContext); //load the API context to use in your app

Please note: initialising 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 = ApiContext.createForPsd2(
    ENVIRONMENT_TYPE,
    SecurityUtils.getCertificateFromFile(PATH_TO_CERTIFICATE),
    SecurityUtils.getPrivateKeyFromFile(PATH_TO_PRIVATE_KEY),
    new Certificate[]{
            SecurityUtils.getCertificateFromFile(PATH_TO_CERTIFICATE_CHAIN)
    },
    DESCRIPTION
)

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.

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 list.

When making calls, The userId and monetaryAccountId needed to make calls will be determined by the SDK it. When no monetaryAccountId has been passed, the SDK will use the first active monetary account it can find. This is normally the monetary account used for billing.

Before you make a call, make sure that you have loaded ApiContext in to the BunqContext.

Core Functionalities

Managing Monetary Accounts

Create a new monetary account:

// Create a new EUR bank account with a description
Integer accountId = MonetaryAccountBankApiObject.create(
    "EUR",                    // Currency code    
    "Account Description"     // Description for the account
).getValue();                 // Returns the new account ID

Close a monetary account:

// Close an existing monetary account
MonetaryAccountBankApiObject.update(
    accountId,                // ID of the account to close    
    null,                     // No change to currency    
    null,                     // No change to description    
    null,                     // No change to daily limit    
    "CANCELLED",              // New status for the account    
    "REDEMPTION_VOLUNTARY",   // Sub-status explaining the closure reason    
    "OTHER",                  // Reason category    
    "Reason description"      // Detailed explanation
);

Payments

Make a payment to another user:

// Create the amount object with value and currency
AmountObject amount = new AmountObject("0.01", "EUR");  // Amount in EUR

// Create pointer object to specify the recipient
PointerObject recipient = new PointerObject(
    "EMAIL",                  // Type of identifier (EMAIL, PHONE_NUMBER, IBAN)    
    "recipient@example.com"   // The actual identifier value
);

// Execute the payment
PaymentApiObject.create(
    amount,                   // The amount to transfer    
    recipient,                // Who to pay    
    "Payment description"     // Description shown on the transaction
);

Batch payments:

// Create a list to hold multiple payments
List<PaymentApiObject> payments = new ArrayList<>();

// Add payments to the list
payments.add(new PaymentApiObject(
    new AmountObject("0.01", "EUR"),  // Amount for this payment    
    recipient,                         // Recipient for this payment    
    "Payment description"              // Description for this payment
));

// Execute all payments as a batch
PaymentBatchApiObject.create(payments);  // More efficient than individual calls

Payment Requests

Create a payment request:

// Request money from another user
RequestInquiryApiObject.create(
    new AmountObject("0.01", "EUR"),  // Amount to request    
    recipient,                         // Who to request from    
    "Request description",             // Description of request    
    false,                             // Allow bunqme - false means regular request    
    monetaryAccountId                  // ID of account to receive the money
);

Accept a payment request:

// Create parameters to filter for pending requests
Map<String, String> params = new HashMap<>();
params.put("status", "PENDING");  // Only get PENDING requests

// Retrieve pending requests
List<RequestResponseApiObject> requests = RequestResponseApiObject.list(
    monetaryAccountId,        // Account ID to check for requests    
    params                    // Filter parameters
).getValue();

// Accept the first pending request
RequestResponseApiObject.update(
    requests.get(0).getId(),  // ID of the request to update    
    monetaryAccountId,        // Account ID that received the request    
    null,                     // No counter-amount needed    
    "ACCEPTED"                // New status - ACCEPTED or REJECTED
);

Card Management

Get possible card names:

// Get all available card names
List<CardNameApiObject> cardNames = CardNameApiObject.list().getValue();

// Get the array of possible names for the first card type
List possibleNames = cardNames.get(0).getPossibleCardNameArray();

Order a new card:

// Generate a random string for the second line on the card
String secondLine = generateRandomSecondLine();  // Custom method to generate text
String nameOnCard = "YOUR NAME";  // Name to be printed on the card

// Order a new debit card
CardDebitApiObject.create(
    secondLine,               // Text for second line on card    
    nameOnCard,               // Name to appear on card    
    "MASTERCARD",             // Card type    
    "MASTERCARD_DEBIT"        // Product type
);

File Attachments

Upload a public attachment:

// Create headers for the attachment
HashMap<String, String> headers = new HashMap<>();
BunqHeader.CONTENT_TYPE.addTo(headers, "image/png");  // Specify file type
BunqHeader.ATTACHMENT_DESCRIPTION.addTo(headers, "Description");  // Add description

// Read file into byte array
byte[] fileContents = FileUtils.readFileToByteArray(new File("path/to/file.png"));

// Upload the attachment and get its UUID
String uuid = AttachmentPublicApiObject.create(headers, fileContents).getValue();

Retrieve an attachment:

// Download attachment content using its UUID
byte[] fileContents = AttachmentPublicContentApiObject.list(uuid).getValue();

Avatar Management

Create an avatar:

// First upload an image as a public attachment
String attachmentUuid = uploadAttachment();  // Custom method to upload attachment

// Then create an avatar with the attachment
String avatarUuid = AvatarApiObject.create(attachmentUuid).getValue();  // Returns avatar UUID

Session Management

Delete the current session:

// Delete current session (0 is a dummy session ID, as the actual ID isn't needed)
SessionApiObject.delete(0).getValue();  // Will invalidate current session

Reset a session:

// Reset the session in your API context
apiContext.resetSession();  // Creates a new session
apiContext.save("bunq-config.conf");  // Save changes to configuration file

Notification Filters (Webhooks)

Create a URL notification filter for a monetary account:

// Create a filter for payment mutations (changes) with a callback URL
NotificationFilterUrlObject filter = new NotificationFilterUrlObject(
    "MUTATION",                      // Event category to trigger on    
    "https://your-callback-url.com"  // URL to receive webhooks
);

// Add filter to a list (API expects a list)
List<NotificationFilterUrlObject> filters = new ArrayList<>();
filters.add(filter);

// Set up the notification filter for a specific account
NotificationFilterUrlMonetaryAccountInternal.createWithListResponse(
    monetaryAccountId,  // Account to monitor    
    filters            // List of filters to apply
);

Create a push notification filter for a user:

// Create a filter for push notifications about payment mutations
NotificationFilterPushObject filter = new NotificationFilterPushObject("MUTATION");

// Add filter to a list (API expects a list)
List<NotificationFilterPushObject> filters = new ArrayList<>();
filters.add(filter);

// Set up the push notification filter for the current user
NotificationFilterPushUserInternal.createWithListResponse(filters);

OAuth Authorization

Create an OAuth authorization URI:

// Generate an OAuth URL for authorization
String uri = OauthAuthorizationUri.create(
    OauthResponseType.CODE,     // Request an authorization code    
    "your-redirect-uri",        // Where to redirect after authorization    
    new OauthClientApiObject("status"),  // Client information    
    "state"                     // Security state parameter
).getAuthorizationUri();        // Get the complete URI

Creating objects

With the create method you can create new models. This method normally returns the id of the created model.

Payment.create(
	new Amount(amount, CURRENCY_EURO),
	new Pointer(POINTER_TYPE_EMAIL, recipient),
	description
);

Reading objects

Reading objects can be done via the get or list method.

These type of calls always returns the model or binary data.

Payment.list(
 	monetaryAccountBank.getId(),
    pagination.getUrlParamsCountOnly()
)

Updating objects

Updating objects through the API goes the same way as creating objects, except that also the object to update identifier (ID or UUID) is needed.

The update method will also normally return the Id of the updated model.

 MonetaryAccountBank.update(Integer.parseInt(accountId), name);

Deleting objects

Deleting object can be done via the delete method. This method also requires the object identifier which could be an Id or uuid.

This method normally returns an empty response.

CustomerStatementExport.delete(customerStatementId);

Tips for Using the SDK

  1. Always ensure your API context is properly loaded before making API calls

  2. Request spending money in the sandbox environment when needed:

    // Check if account has less than 10 units of currency
    if (Float.parseFloat(monetaryAccountBank.getBalance().getValue()) < 10) {
        // Request money from the sandbox sugar daddy account    
        RequestInquiryApiObject.create(
                new AmountObject("500", "EUR"),        
                new PointerObject("EMAIL", "sugardaddy@bunq.com"),        
                "Request description",        
                false    
        );
    }
  3. Save your API context after making changes to it

  4. Remember to refresh your context periodically for long-running applications:

    // Refresh the user context to get latest information
    BunqContext.getUserContext().refreshContext();
PreviousJavaNextTests

Last updated 17 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_java