2026-11-01 18:35:23 +01:00
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
2026-10-06 15:39:17 +02:00
module ;
# include "../lib/json.hpp"
# include <openssl/types.h>
module Nostro : Bunq_impl ;
import std ;
import : Bunq ;
2026-10-31 20:50:57 +01:00
import : Connector ;
2026-10-06 15:39:17 +02:00
import : Crypto ;
2026-11-01 18:35:23 +01:00
import : Currency ;
import : File ;
import : Transaction ;
2026-10-31 20:50:57 +01:00
import : Utils ;
2026-10-06 15:39:17 +02:00
import Crafter . Network ;
using namespace Nostro ;
using namespace Nostro : : Crypto ;
using namespace nlohmann ;
using namespace Crafter ;
2026-11-01 18:35:23 +01:00
std : : deque < BunqConnector > BunqConnector : : connectors ;
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
namespace {
constexpr std : : string_view userAgent = " Nostro " ;
constexpr std : : string_view maybeCarriedOut = " ; the request may have been carried out, check before trying again " ;
// Where BunqConnector::RedirectTo sends everything.
std : : optional < BunqEndpoint > & Redirected ( ) {
static std : : optional < BunqEndpoint > redirected ;
return redirected ;
}
// A request's authority: the host, with the port when it is not HTTPS's own.
std : : string Authority ( const BunqEndpoint & endpoint ) {
return endpoint . port = = 443 ? endpoint . host : std : : format ( " {}:{} " , endpoint . host , endpoint . port ) ;
}
// One persistent connection per endpoint, dialled on first use.
ClientHTTP1 & ApiClient ( const BunqEndpoint & endpoint ) {
static std : : map < std : : string , std : : unique_ptr < ClientHTTP1 > > clients ;
std : : unique_ptr < ClientHTTP1 > & client = clients [ Authority ( endpoint ) ] ;
if ( ! client ) {
client = std : : make_unique < ClientHTTP1 > ( endpoint . host , endpoint . port , TLSClientCredentials { . caPem = endpoint . caPem } ) ;
}
return * client ;
}
// How often a 429 is waited out, and how long each time. bunq allows 3 GETs, 5 POSTs and 2 PUTs per endpoint in
// any 3 seconds, and one session per 30 seconds: the second entry is session-server's.
struct RateLimit {
std : : uint32_t retries ;
std : : chrono : : seconds wait ;
} ;
constexpr std : : array < RateLimit , 2 > rateLimits = { {
{ 5 , std : : chrono : : seconds ( 3 ) } ,
{ 2 , std : : chrono : : seconds ( 31 ) } ,
} } ;
std : : uint16_t ParseStatus ( std : : string_view status ) {
std : : uint16_t value = 0 ;
std : : from_chars ( status . data ( ) , status . data ( ) + status . size ( ) , value ) ;
return value ;
}
// bunq's {"Error": [{"error_description": ...}]}, or the OAuth server's {"error": ..., "error_description": ...}.
std : : string ErrorMessage ( std : : string_view body ) {
const json doc = json : : parse ( body , nullptr , false ) ;
std : : string message ;
if ( doc . is_object ( ) ) {
if ( const json : : const_iterator errors = doc . find ( " Error " ) ; errors ! = doc . end ( ) & & errors - > is_array ( ) ) {
for ( const json & error : * errors ) {
const std : : string description = BunqJson : : String ( error , " error_description " ) ;
if ( ! description . empty ( ) ) {
message + = message . empty ( ) ? description : std : : format ( " ; {} " , description ) ;
}
}
}
if ( message . empty ( ) ) {
message = BunqJson : : String ( doc , " error_description " ) ;
}
if ( message . empty ( ) ) {
message = BunqJson : : String ( doc , " error " ) ;
2026-10-06 15:39:17 +02:00
}
}
2026-11-01 18:35:23 +01:00
if ( message . empty ( ) ) {
message = body . empty ( ) ? std : : string ( " no details " ) : std : : string ( body . substr ( 0 , 300 ) ) ;
}
return message ;
}
// bunq has no BIC on its own accounts; an IBAN with bank code BUNQ is one of them.
std : : string BicOf ( std : : string_view iban , std : : string bic ) {
if ( bic . empty ( ) & & iban . size ( ) > = 8 & & iban . substr ( 4 , 4 ) = = " BUNQ " ) {
return " BUNQNL2A " ;
}
return bic ;
2026-10-06 15:39:17 +02:00
}
}
2026-11-01 18:35:23 +01:00
BunqError : : BunqError ( std : : uint16_t status , const std : : string & message ) : std : : runtime_error ( message ) , status ( status ) {
}
json BunqJson : : Item ( const json & response , std : : string_view key ) {
for ( const json & item : response . at ( " Response " ) ) {
if ( item . is_object ( ) ) {
if ( const json : : const_iterator value = item . find ( key ) ; value ! = item . end ( ) ) {
return * value ;
}
}
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
throw std : : runtime_error ( std : : format ( " bunq response has no '{}' object " , key ) ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
std : : pair < std : : string , const json * > BunqJson : : Only ( const json & item ) {
if ( ! item . is_object ( ) | | item . size ( ) ! = 1 ) {
return { std : : string ( ) , nullptr } ;
2026-10-31 20:50:57 +01:00
}
2026-11-01 18:35:23 +01:00
const json : : const_iterator only = item . begin ( ) ;
return { only . key ( ) , & only . value ( ) } ;
2026-10-31 20:50:57 +01:00
}
2026-11-01 18:35:23 +01:00
json BunqJson : : Amount ( std : : int64_t amount , Currency currency ) {
return json { { " value " , FormatAmount ( amount , currency ) } , { " currency " , std : : string ( GetCurrencyCode ( currency ) ) } } ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
json BunqJson : : Pointer ( const BunqCounterparty & counterparty ) {
json pointer = { { " type " , counterparty . type } , { " value " , counterparty . value } } ;
if ( ! counterparty . name . empty ( ) ) {
pointer [ " name " ] = counterparty . name ;
}
return pointer ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
std : : pair < Currency , std : : int64_t > BunqJson : : ReadAmount ( const json & amount ) {
const Currency currency = GetCurrency ( amount . at ( " currency " ) . get < std : : string > ( ) ) ;
return { currency , ParseAmount ( amount . at ( " value " ) . get < std : : string > ( ) , currency ) } ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
BunqLabel BunqJson : : ReadLabel ( const json & label ) {
BunqLabel out { String ( label , " display_name " ) , String ( label , " iban " ) } ;
if ( out . name . empty ( ) & & label . is_object ( ) ) {
if ( const json : : const_iterator user = label . find ( " label_user " ) ; user ! = label . end ( ) ) {
out . name = String ( * user , " display_name " ) ;
}
}
return out ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
std : : string BunqJson : : String ( const json & object , std : : string_view key ) {
if ( ! object . is_object ( ) ) {
return std : : string ( ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
const json : : const_iterator value = object . find ( key ) ;
return value ! = object . end ( ) & & value - > is_string ( ) ? value - > get < std : : string > ( ) : std : : string ( ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
json BunqConnector : : Call ( std : : string_view method , std : : string_view path , const json * body , Auth auth , bool renew ) {
// Nothing a session call returns is used unverified: a connector saved before the server key was kept fetches it first.
if ( auth = = Auth : : Session & & ! serverPublicKey & & ! fetchingServerKey ) {
EnsureServerPublicKey ( ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
const bool write = method ! = " GET " ;
const std : : string target = path . starts_with ( " /v1/ " ) ? std : : string ( path ) : std : : format ( " /v1{} " , path ) ;
// The signature covers these exact bytes. Text that is not UTF-8 (a description typed in another encoding) is
// replaced rather than refused.
const std : : string payload = body ? body - > dump ( - 1 , ' ' , false , json : : error_handler_t : : replace ) : std : : string ( ) ;
2026-10-31 20:50:57 +01:00
2026-11-01 18:35:23 +01:00
std : : unordered_map < std : : string , std : : string > headers = {
{ " User-Agent " , std : : string ( userAgent ) } ,
{ " Cache-Control " , " no-cache " } ,
{ " Accept " , " application/json " } ,
} ;
if ( body ) {
headers . emplace ( " Content-Type " , " application/json " ) ;
// Only sessions and payments need a signature, but signing every body costs nothing and covers whatever
// else bunq starts to require one for. The installation call is the one that may not carry it.
if ( auth ! = Auth : : None ) {
headers . emplace ( " X-Bunq-Client-Signature " , SignBody ( privateKey . get ( ) , payload ) ) ;
}
}
2026-10-31 20:50:57 +01:00
2026-11-01 18:35:23 +01:00
bool renewed = false ;
for ( std : : uint32_t attempt = 0 ; ; attempt + + ) {
if ( auth = = Auth : : Installation ) {
headers [ " X-Bunq-Client-Authentication " ] = installationToken ;
} else if ( auth = = Auth : : Session ) {
headers [ " X-Bunq-Client-Authentication " ] = sessionToken ;
}
2026-10-31 20:50:57 +01:00
2026-11-01 18:35:23 +01:00
// ClientHTTP1 sends a request again on a reused connection that fails before any of the response arrives,
// which includes a read timeout: for a payment bunq booked before its answer was lost, that pays twice. It
// never replays on a new connection, so a write gets one.
const BunqEndpoint endpoint = Endpoint ( environment ) ;
ClientHTTP1 & client = ApiClient ( endpoint ) ;
if ( write ) {
client . Disconnect ( ) ;
}
HTTPResponse response ;
try {
response = client . Send ( CreateRequestHTTP ( std : : string ( method ) , target , Authority ( endpoint ) , headers , payload ) ) ;
} catch ( const std : : exception & e ) {
if ( write ) {
throw std : : runtime_error ( std : : format ( " bunq {} {}: {}{} " , method , path , e . what ( ) , maybeCarriedOut ) ) ;
2026-10-31 20:50:57 +01:00
}
2026-11-01 18:35:23 +01:00
throw ;
}
const std : : uint16_t status = ParseStatus ( response . status ) ;
2026-10-31 20:50:57 +01:00
2026-11-01 18:35:23 +01:00
// A 429 is refused before anything happens, so even a payment is safe to send again.
const RateLimit & limit = rateLimits [ target . starts_with ( " /v1/session-server " ) ] ;
if ( status = = 429 & & attempt < limit . retries ) {
std : : this_thread : : sleep_for ( limit . wait ) ;
continue ;
}
2026-10-31 20:50:57 +01:00
2026-11-01 18:35:23 +01:00
if ( status > = 200 & & status < 300 ) {
// An error response can come unsigned; nothing but its message is used. A success is used, so it must verify.
if ( serverPublicKey & & auth ! = Auth : : None ) {
const std : : unordered_map < std : : string , std : : string > : : const_iterator signature = response . headers . find ( " x-bunq-server-signature " ) ;
if ( signature = = response . headers . end ( ) | | ! VerifyBody ( serverPublicKey . get ( ) , response . body , signature - > second ) ) {
// The check comes after the fact: a payment may have been made all the same, and sending it again
// could pay twice.
throw std : : runtime_error ( std : : format ( " bunq {} {}: the response is not signed by bunq's server key{} " , method , path , write ? maybeCarriedOut : " " ) ) ;
2026-10-31 20:50:57 +01:00
}
2026-11-01 18:35:23 +01:00
}
try {
return response . body . empty ( ) ? json : : object ( ) : json : : parse ( response . body ) ;
} catch ( const json : : exception & e ) {
throw std : : runtime_error ( std : : format ( " bunq {} {}: unreadable response: {}{} " , method , path , e . what ( ) , write ? maybeCarriedOut : " " ) ) ;
2026-10-31 20:50:57 +01:00
}
}
2026-11-01 18:35:23 +01:00
const std : : string message = ErrorMessage ( response . body ) ;
// An expired or ended session is a 401, or a 403 "Insufficient authentication.": open a new one, once.
if ( auth = = Auth : : Session & & renew & & ! renewed & & ( status = = 401 | | ( status = = 403 & & message . contains ( " authentication " ) ) ) ) {
renewed = true ;
RefreshSession ( ) ;
Connector : : SaveConnectors ( ) ;
continue ;
}
// A 5xx says nothing about whether a write went through.
throw BunqError ( status , std : : format ( " bunq {} {}: {} ({}) { } " , method, path, message, status, write && status >= 500 ? maybeCarriedOut : " " ));
2026-10-31 20:50:57 +01:00
}
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
json BunqConnector : : Get ( std : : string_view path ) {
return Call ( " GET " , path , nullptr , Auth : : Session ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
json BunqConnector : : Post ( std : : string_view path , const json & body ) {
return Call ( " POST " , path , & body , Auth : : Session ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
json BunqConnector : : Put ( std : : string_view path , const json & body ) {
return Call ( " PUT " , path , & body , Auth : : Session ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
json BunqConnector : : Delete ( std : : string_view path ) {
return Call ( " DELETE " , path , nullptr , Auth : : Session ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
std : : vector < json > BunqConnector : : List ( std : : string_view path ) {
std : : vector < json > items ;
std : : string next = std : : format ( " {}{}count=200 " , path , path . contains ( ' ? ' ) ? ' & ' : ' ? ' ) ;
while ( ! next . empty ( ) ) {
json page = Get ( next ) ;
for ( json & item : page . at ( " Response " ) ) {
items . push_back ( std : : move ( item ) ) ;
}
next . clear ( ) ;
if ( const json : : const_iterator pagination = page . find ( " Pagination " ) ; pagination ! = page . end ( ) ) {
if ( const json : : const_iterator older = pagination - > find ( " older_url " ) ; older ! = pagination - > end ( ) & & older - > is_string ( ) ) {
next = older - > get < std : : string > ( ) ;
}
}
}
return items ;
}
void BunqConnector : : ReadUser ( const json & response ) {
const auto displayName = [ ] ( const json & user ) {
constexpr std : : array < std : : string_view , 4 > keys = { " display_name " , " name " , " legal_name " , " public_nick_name " } ;
for ( const std : : string_view key : keys ) {
std : : string value = BunqJson : : String ( user , key ) ;
if ( ! value . empty ( ) ) {
return value ;
}
}
return std : : string ( ) ;
} ;
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
for ( const json & item : response . at ( " Response " ) ) {
const auto [ type , user ] = BunqJson : : Only ( item ) ;
if ( ! user ) {
continue ;
}
if ( type = = " UserPerson " | | type = = " UserCompany " | | type = = " UserPaymentServiceProvider " ) {
userType = type ;
id = user - > at ( " id " ) . get < std : : uint64_t > ( ) ;
ownerId = id ;
name = displayName ( * user ) ;
return ;
}
if ( type = = " UserApiKey " ) {
// An OAuth connection: its own user id goes in paths; the name and owner are the bunq user who granted access.
userType = type ;
id = user - > at ( " id " ) . get < std : : uint64_t > ( ) ;
const auto [ grantedType , granted ] = BunqJson : : Only ( user - > at ( " granted_by_user " ) ) ;
name = granted ? displayName ( * granted ) : std : : string ( ) ;
ownerId = granted ? granted - > at ( " id " ) . get < std : : uint64_t > ( ) : id ;
return ;
}
}
throw std : : runtime_error ( " bunq session names no user " ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
void BunqConnector : : RefreshSession ( ) {
const json body = { { " secret " , apiKey } } ;
const json response = Call ( " POST " , " /session-server " , & body , Auth : : Installation ) ;
sessionToken = BunqJson : : Item ( response , " Token " ) . at ( " token " ) . get < std : : string > ( ) ;
sessionId = BunqJson : : Item ( response , " Id " ) . at ( " id " ) . get < std : : uint64_t > ( ) ;
ReadUser ( response ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
void BunqConnector : : EnsureServerPublicKey ( ) {
// Connectors saved before the key was kept: fetch it once. These two calls cannot be verified yet; TLS still
// authenticates the host.
fetchingServerKey = true ;
struct Reset {
bool & flag ;
~ Reset ( ) { flag = false ; }
} reset { fetchingServerKey } ;
const std : : uint64_t installation = BunqJson : : Item ( Get ( " /installation " ) , " Id " ) . at ( " id " ) . get < std : : uint64_t > ( ) ;
const json key = Get ( std : : format ( " /installation/{}/server-public-key " , installation ) ) ;
serverPublicKey = OwnKey ( LoadPublicKeyFromPem ( BunqJson : : Item ( key , " ServerPublicKey " ) . at ( " server_public_key " ) . get < std : : string > ( ) ) ) ;
Connector : : SaveConnectors ( ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
BunqConnector & BunqConnector : : Create ( std : : string & & apiKey , std : : string_view allowedIps , BunqEnvironment environment ) {
BunqConnector connector ;
connector . environment = environment ;
2026-10-06 15:39:17 +02:00
connector . apiKey = std : : move ( apiKey ) ;
2026-11-01 18:35:23 +01:00
const auto [ key , publicKey ] = CreateKey ( ) ;
connector . privateKey = OwnKey ( key ) ;
const json installation = { { " client_public_key " , publicKey } } ;
const json installed = connector . Call ( " POST " , " /installation " , & installation , Auth : : None ) ;
connector . installationToken = BunqJson : : Item ( installed , " Token " ) . at ( " token " ) . get < std : : string > ( ) ;
connector . serverPublicKey = OwnKey ( LoadPublicKeyFromPem ( BunqJson : : Item ( installed , " ServerPublicKey " ) . at ( " server_public_key " ) . get < std : : string > ( ) ) ) ;
json device = { { " description " , " Nostro " } , { " secret " , connector . apiKey } } ;
if ( ! allowedIps . empty ( ) ) {
json ips = json : : array ( ) ;
for ( const auto part : std : : views : : split ( allowedIps , ' , ' ) ) {
std : : string_view ip ( part . begin ( ) , part . end ( ) ) ;
while ( ip . starts_with ( ' ' ) ) {
ip . remove_prefix ( 1 ) ;
}
while ( ip . ends_with ( ' ' ) ) {
ip . remove_suffix ( 1 ) ;
}
if ( ! ip . empty ( ) ) {
ips . push_back ( std : : string ( ip ) ) ;
}
}
device [ " permitted_ips " ] = std : : move ( ips ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
connector . Call ( " POST " , " /device-server " , & device , Auth : : Installation ) ;
connector . RefreshSession ( ) ;
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
// One connector per bunq user: the same accounts under two connectors would make every one of them ambiguous.
// Adding the user again the same way (a renewed API key, a new OAuth grant) replaces the old connector.
const std : : deque < BunqConnector > : : iterator existing = std : : ranges : : find_if ( connectors , [ & connector ] ( const BunqConnector & other ) {
return other . environment = = connector . environment & & other . ownerId = = connector . ownerId ;
} ) ;
if ( existing ! = connectors . end ( ) ) {
if ( existing - > IsOAuth ( ) ! = connector . IsOAuth ( ) ) {
try {
connector . Logout ( ) ;
} catch ( const std : : exception & ) {
// The new session expires by itself.
}
throw std : : runtime_error ( std : : format ( " {} is already connected {}: remove that connector first " , connector . name , existing - > IsOAuth ( ) ? " through OAuth " : " with an API key " ) ) ;
}
try {
existing - > Logout ( ) ;
} catch ( const std : : exception & ) {
// A key that no longer works has no session to end.
}
}
BunqConnector & added = existing ! = connectors . end ( ) ? ( * existing = std : : move ( connector ) ) : connectors . emplace_back ( std : : move ( connector ) ) ;
added . RefreshAccounts ( ) ;
return added ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
void BunqConnector : : Remove ( BunqConnector & connector ) {
const std : : deque < BunqConnector > : : iterator it = std : : ranges : : find_if ( connectors , [ & connector ] ( const BunqConnector & other ) { return & other = = & connector ; } ) ;
if ( it = = connectors . end ( ) ) {
throw std : : invalid_argument ( " that connector is not in BunqConnector::connectors " ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
Account : : ForgetTransactions ( connector . StorageKey ( ) ) ;
connectors . erase ( it ) ;
// Erasing from the middle of a deque moves the connectors around it: point their accounts at where they are now.
for ( BunqConnector & remaining : connectors ) {
for ( BunqAccount & account : remaining . accounts ) {
account . connector = & remaining ;
}
}
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
BunqEnvironment BunqConnector : : EnvironmentOfKey ( std : : string_view apiKey ) {
return apiKey . starts_with ( " sandbox_ " ) ? BunqEnvironment : : Sandbox : BunqEnvironment : : Production ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
std : : string BunqConnector : : OAuthAuthorizationUrl ( BunqEnvironment environment , std : : string_view clientId , std : : string_view redirectUri , std : : string_view state ) {
return std : : format ( " https://{}/auth?response_type=code&client_id={}&redirect_uri={}&state={} " , environment = = BunqEnvironment : : Production ? " oauth.bunq.com " : " oauth.sandbox.bunq.com " , UrlEncode ( clientId ) , UrlEncode ( redirectUri ) , UrlEncode ( state ) ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
BunqEndpoint BunqConnector : : Endpoint ( BunqEnvironment environment ) {
return Redirected ( ) . value_or ( BunqEndpoint { . host = environment = = BunqEnvironment : : Production ? " api.bunq.com " : " public-api.sandbox.bunq.com " , . port = 443 , . caPem = std : : string ( ) } ) ;
}
void BunqConnector : : RedirectTo ( BunqEndpoint endpoint ) {
Redirected ( ) = std : : move ( endpoint ) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
std : : string BunqConnector : : OAuthExchangeCode ( BunqEnvironment environment , std : : string_view clientId , std : : string_view clientSecret , std : : string_view redirectUri , std : : string_view code ) {
// The token endpoint has a host of its own, which a redirect replaces like the API's.
const BunqEndpoint endpoint = Redirected ( ) . value_or ( BunqEndpoint { . host = environment = = BunqEnvironment : : Production ? " api.oauth.bunq.com " : " api-oauth.sandbox.bunq.com " , . port = 443 , . caPem = std : : string ( ) } ) ;
ClientHTTP1 client ( endpoint . host , endpoint . port , TLSClientCredentials { . caPem = endpoint . caPem } ) ;
const std : : string host = Authority ( endpoint ) ;
// The token endpoint reads its parameters from the query string only: sent as a form body they are reported missing.
const std : : string target = std : : format ( " /v1/token?grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&client_secret={} " , UrlEncode ( code ) , UrlEncode ( redirectUri ) , UrlEncode ( clientId ) , UrlEncode ( clientSecret ) ) ;
const HTTPResponse response = client . Send ( CreateRequestHTTP ( " POST " , target , host , { { " User-Agent " , std : : string ( userAgent ) } , { " Accept " , " application/json " } } ) ) ;
const std : : uint16_t status = ParseStatus ( response . status ) ;
const json doc = json : : parse ( response . body , nullptr , false ) ;
const std : : string token = BunqJson : : String ( doc , " access_token " ) ;
if ( status = = 200 & & ! token . empty ( ) ) {
return token ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
throw BunqError ( status , std : : format ( " bunq OAuth token exchange: {} ({}) " , ErrorMessage(response.body), status)) ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
void BunqConnector : : RefreshAccounts ( ) {
std : : vector < BunqAccount > refreshed ;
for ( const json & item : List ( std : : format ( " /user/{}/monetary-account " , id ) ) ) {
const auto [ type , account ] = BunqJson : : Only ( item ) ;
if ( ! account | | ! type . starts_with ( " MonetaryAccount " ) ) {
continue ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
// A closed account stays listed. A blocked one is still the user's, with its balance.
const std : : string status = BunqJson : : String ( * account , " status " ) ;
if ( status ! = " ACTIVE " & & status ! = " BLOCKED " ) {
2026-10-06 15:39:17 +02:00
continue ;
}
2026-11-01 18:35:23 +01:00
std : : string description = BunqJson : : String ( * account , " description " ) ;
Currency currency ;
try {
currency = GetCurrency ( BunqJson : : String ( * account , " currency " ) ) ;
} catch ( const std : : runtime_error & e ) {
Note ( std : : format ( " skipping bunq account '{}': {} " , description , e . what ( ) ) ) ;
2026-10-06 15:39:17 +02:00
continue ;
}
2026-11-01 18:35:23 +01:00
std : : string iban ;
if ( const json : : const_iterator aliases = account - > find ( " alias " ) ; aliases ! = account - > end ( ) & & aliases - > is_array ( ) ) {
for ( const json & alias : * aliases ) {
if ( BunqJson : : String ( alias , " type " ) = = " IBAN " ) {
iban = BunqJson : : String ( alias , " value " ) ;
}
2026-10-06 15:39:17 +02:00
}
}
2026-11-01 18:35:23 +01:00
std : : int64_t balance = 0 ;
if ( const json : : const_iterator value = account - > find ( " balance " ) ; value ! = account - > end ( ) & & value - > is_object ( ) ) {
balance = BunqJson : : ReadAmount ( * value ) . second ;
}
std : : string bic = BicOf ( iban , std : : string ( ) ) ;
refreshed . emplace_back ( std : : move ( description ) , std : : move ( bic ) , std : : move ( iban ) , currency , balance , account - > at ( " id " ) . get < std : : uint64_t > ( ) , std : : string ( type ) , this ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
accounts = std : : move ( refreshed ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
void BunqConnector : : GetNewTransactions ( ) {
for ( BunqAccount & account : accounts ) {
GetNewTransactions ( account ) ;
}
}
void BunqConnector : : GetNewTransactions ( BunqAccount & account ) {
const std : : string key = account . StorageKey ( ) ;
const std : : chrono : : system_clock : : time_point last = account . GetLastTransactionTime ( key ) ;
std : : vector < Transaction > fetched ;
std : : string next = std : : format ( " {}/payment?count=200 " , account . Path ( ) ) ;
while ( ! next . empty ( ) ) {
const json page = Get ( next ) ;
next . clear ( ) ;
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
bool reachedStored = false ;
for ( const json & item : page . at ( " Response " ) ) {
const json : : const_iterator payment = item . find ( " Payment " ) ;
if ( payment = = item . end ( ) ) {
continue ;
}
// Listed newest first. One at the last stored timestamp may still be new: SaveTransactions tells by id.
const std : : chrono : : system_clock : : time_point created = ParseTimestamp ( payment - > at ( " created " ) . get < std : : string > ( ) ) ;
if ( created < last ) {
reachedStored = true ;
break ;
}
const json & counterparty = payment - > at ( " counterparty_alias " ) ;
const auto [ currency , amount ] = BunqJson : : ReadAmount ( payment - > at ( " amount " ) ) ;
std : : string iban = BunqJson : : String ( counterparty , " iban " ) ;
std : : string bic = BicOf ( iban , BunqJson : : String ( counterparty , " swift_bic " ) ) ;
fetched . push_back ( Transaction {
. name = BunqJson : : ReadLabel ( counterparty ) . name ,
. bic = std : : move ( bic ) ,
. iban = std : : move ( iban ) ,
. description = BunqJson : : String ( * payment , " description " ) ,
. currency = currency ,
. amount = amount ,
. timePoint = created ,
. id = std : : to_string ( payment - > at ( " id " ) . get < std : : uint64_t > ( ) ) ,
. kind = std : : format ( " {}/{} " , BunqJson : : String ( * payment , " type " ) , BunqJson : : String ( * payment , " sub_type " ) ) ,
} ) ;
}
if ( ! reachedStored ) {
if ( const json : : const_iterator pagination = page . find ( " Pagination " ) ; pagination ! = page . end ( ) ) {
if ( const json : : const_iterator older = pagination - > find ( " older_url " ) ; older ! = pagination - > end ( ) & & older - > is_string ( ) ) {
next = older - > get < std : : string > ( ) ;
}
}
}
}
account . SaveTransactions ( key , std : : move ( fetched ) ) ;
}
bool BunqConnector : : TestConnector ( ) {
try {
Get ( std : : format ( " /user/{} " , id ) ) ;
2026-10-06 15:39:17 +02:00
return true ;
2026-11-01 18:35:23 +01:00
} catch ( const std : : exception & ) {
return false ;
}
}
void BunqConnector : : Logout ( ) {
try {
// Not renewed: opening a session to close it would leave the new one open.
Call ( " DELETE " , std : : format ( " /session/{} " , sessionId ) , nullptr , Auth : : Session , false ) ;
} catch ( const BunqError & e ) {
// A session that already ended is logged out.
if ( e . status ! = 401 & & e . status ! = 403 ) {
throw ;
2026-10-06 15:39:17 +02:00
}
}
2026-11-01 18:35:23 +01:00
sessionToken . clear ( ) ;
2026-10-06 15:39:17 +02:00
}
2026-11-01 18:35:23 +01:00
namespace {
BunqCard ReadCard ( std : : string_view kind , const json & card ) {
BunqCard out {
. id = card . at ( " id " ) . get < std : : uint64_t > ( ) ,
. kind = std : : string ( kind ) ,
. productType = BunqJson : : String ( card , " product_type " ) ,
. status = BunqJson : : String ( card , " status " ) ,
. orderStatus = BunqJson : : String ( card , " order_status " ) ,
. nameOnCard = BunqJson : : String ( card , " name_on_card " ) ,
. secondLine = BunqJson : : String ( card , " second_line " ) ,
. lastFour = std : : string ( ) ,
. expiry = BunqJson : : String ( card , " expiry_date " ) ,
. iban = std : : string ( ) ,
} ;
if ( const json : : const_iterator numbers = card . find ( " primary_account_numbers " ) ; numbers ! = card . end ( ) & & numbers - > is_array ( ) & & ! numbers - > empty ( ) ) {
out . lastFour = BunqJson : : String ( numbers - > front ( ) , " four_digit " ) ;
}
if ( const json : : const_iterator current = card . find ( " label_monetary_account_current " ) ; current ! = card . end ( ) ) {
out . iban = BunqJson : : String ( * current , " iban " ) ;
}
return out ;
}
}
std : : vector < BunqCard > BunqConnector : : Cards ( ) {
std : : vector < BunqCard > cards ;
for ( const json & item : List ( std : : format ( " /user/{}/card " , id ) ) ) {
const auto [ kind , card ] = BunqJson : : Only ( item ) ;
if ( card ) {
cards . push_back ( ReadCard ( kind , * card ) ) ;
}
}
return cards ;
}
BunqCard BunqConnector : : SetCardStatus ( std : : uint64_t card , std : : string_view status ) {
// bunq answers with the card as it is now, which is not always as asked: a card that was never activated stays
// DEACTIVATED, without an error.
const json response = Put ( std : : format ( " /user/{}/card/{} " , id , card ) , json { { " status " , std : : string ( status ) } } ) ;
for ( const json & item : response . at ( " Response " ) ) {
const auto [ kind , updated ] = BunqJson : : Only ( item ) ;
if ( updated & & kind . starts_with ( " Card " ) ) {
return ReadCard ( kind , * updated ) ;
}
}
throw std : : runtime_error ( " bunq did not return the card it updated " ) ;
}
std : : string BunqConnector : : StorageKey ( ) const {
return std : : format ( " {}/{}/{} " , connectorId , environment = = BunqEnvironment : : Production ? " production " : " sandbox " , id ) ;
}
bool BunqConnector : : IsOAuth ( ) const {
return userType = = " UserApiKey " ;
}
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
BunqAccount : : BunqAccount ( std : : string & & name , std : : string & & bic , std : : string & & iban , Currency currency , std : : int64_t balance , std : : uint64_t id , std : : string & & type , BunqConnector * connector ) : Account ( std : : move ( name ) , std : : move ( bic ) , std : : move ( iban ) , currency , balance ) , id ( id ) , type ( std : : move ( type ) ) , connector ( connector ) {
2026-10-06 15:39:17 +02:00
2026-11-01 18:35:23 +01:00
}
std : : string BunqAccount : : Path ( ) const {
return std : : format ( " /user/{}/monetary-account/{} " , connector - > id , id ) ;
}
std : : string BunqAccount : : StorageKey ( ) const {
return std : : format ( " {}/{} " , connector - > StorageKey ( ) , id ) ;
}
void Nostro : : to_json ( json & j , const BunqConnector & connector ) {
2026-10-06 15:39:17 +02:00
j = json {
2026-11-01 18:35:23 +01:00
{ " environment " , connector . environment = = BunqEnvironment : : Production ? " production " : " sandbox " } ,
2026-10-06 15:39:17 +02:00
{ " apiKey " , connector . apiKey } ,
2026-11-01 18:35:23 +01:00
{ " installationToken " , connector . installationToken } ,
{ " sessionToken " , connector . sessionToken } ,
{ " sessionId " , connector . sessionId } ,
{ " privateKey " , PrivateKeyToPem ( connector . privateKey . get ( ) ) } ,
{ " userType " , connector . userType } ,
2026-10-06 15:39:17 +02:00
{ " name " , connector . name } ,
{ " id " , connector . id } ,
2026-11-01 18:35:23 +01:00
{ " ownerId " , connector . ownerId } ,
2026-10-06 15:39:17 +02:00
} ;
2026-11-01 18:35:23 +01:00
if ( connector . serverPublicKey ) {
j [ " serverPublicKey " ] = PublicKeyToPem ( connector . serverPublicKey . get ( ) ) ;
}
2026-10-06 15:39:17 +02:00
}
void Nostro : : from_json ( const json & j , BunqConnector & connector ) {
2026-11-01 18:35:23 +01:00
// Connectors saved before the environment was kept were all made against the sandbox, then the only host.
connector . environment = j . value ( " environment " , std : : string ( " sandbox " ) ) = = " production " ? BunqEnvironment : : Production : BunqEnvironment : : Sandbox ;
2026-10-06 15:39:17 +02:00
j . at ( " apiKey " ) . get_to ( connector . apiKey ) ;
2026-11-01 18:35:23 +01:00
j . at ( " installationToken " ) . get_to ( connector . installationToken ) ;
j . at ( " sessionToken " ) . get_to ( connector . sessionToken ) ;
connector . sessionId = j . value ( " sessionId " , std : : uint64_t { 0 } ) ;
connector . privateKey = OwnKey ( LoadKeyFromPem ( j . at ( " privateKey " ) . get < std : : string > ( ) ) ) ;
if ( const json : : const_iterator key = j . find ( " serverPublicKey " ) ; key ! = j . end ( ) & & key - > is_string ( ) ) {
connector . serverPublicKey = OwnKey ( LoadPublicKeyFromPem ( key - > get < std : : string > ( ) ) ) ;
}
connector . userType = j . value ( " userType " , std : : string ( ) ) ;
2026-10-06 15:39:17 +02:00
j . at ( " name " ) . get_to ( connector . name ) ;
j . at ( " id " ) . get_to ( connector . id ) ;
2026-11-01 18:35:23 +01:00
// Connectors saved before the owner was kept all used API keys, whose user is the owner.
connector . ownerId = j . value ( " ownerId " , connector . id ) ;
}