354 lines
20 KiB
C++
354 lines
20 KiB
C++
// SPDX-License-Identifier: LGPL-3.0-only
|
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
module;
|
|
|
|
#ifdef NOSTRO_BUNQ_ENABLED
|
|
#include "../lib/json.hpp"
|
|
#include <openssl/types.h>
|
|
#endif
|
|
|
|
export module Nostro:Bunq;
|
|
#ifdef NOSTRO_BUNQ_ENABLED
|
|
|
|
import std;
|
|
import :Account;
|
|
import :Crypto;
|
|
import :Currency;
|
|
import :Transaction;
|
|
import :Utils;
|
|
|
|
namespace Nostro {
|
|
export struct BunqConnector;
|
|
|
|
// Which bunq a connector talks to: api.bunq.com, or the sandbox at public-api.sandbox.bunq.com. Sandbox API
|
|
// keys start with "sandbox_"; OAuth access tokens do not say.
|
|
export enum class BunqEnvironment : std::uint8_t {
|
|
Production,
|
|
Sandbox
|
|
};
|
|
|
|
// A server to send bunq's API and OAuth token calls to instead of bunq's own: a local fake, for tests.
|
|
export struct BunqEndpoint {
|
|
std::string host;
|
|
std::uint16_t port = 443;
|
|
std::string caPem; // a trust anchor beside the system store, for a self-signed certificate
|
|
};
|
|
|
|
// An error response from bunq, with its HTTP status (bunq also uses 466, 490 and 491) and error_description.
|
|
export struct BunqError : std::runtime_error {
|
|
std::uint16_t status;
|
|
BunqError(std::uint16_t status, const std::string& message);
|
|
};
|
|
|
|
// The other side of a payment or a request, as bunq addresses it.
|
|
export struct BunqCounterparty {
|
|
std::string type; // "IBAN", "EMAIL" or "PHONE_NUMBER"
|
|
std::string value; // an IBAN without spaces, an e-mail address, or a phone number in international format
|
|
std::string name; // required by bunq for an IBAN outside bunq
|
|
|
|
// `value` with an '@' is an e-mail address, one starting with '+' a phone number, anything else an IBAN,
|
|
// whose check digits are verified so a typo fails here rather than at the bank.
|
|
static BunqCounterparty Parse(std::string_view value, std::string_view name);
|
|
};
|
|
|
|
// How bunq shows a party in a listing.
|
|
export struct BunqLabel {
|
|
std::string name;
|
|
std::string iban; // empty when bunq gives none (a card merchant, or a party known by e-mail or phone)
|
|
};
|
|
|
|
// A request for money this account sent (a bunq RequestInquiry).
|
|
export struct BunqPaymentRequest {
|
|
std::uint64_t id;
|
|
std::string status; // PENDING, ACCEPTED, REJECTED, REVOKED or EXPIRED
|
|
BunqLabel counterparty;
|
|
Currency currency;
|
|
std::int64_t amount; // what was asked, in the currency's minor unit
|
|
std::optional<std::int64_t> amountPaid; // what was paid, once accepted
|
|
std::string description;
|
|
std::chrono::system_clock::time_point created;
|
|
std::string shareUrl; // a bunq.me link anyone can pay through, when bunq made one
|
|
};
|
|
|
|
// A request for money this account received (a bunq RequestResponse). Incoming SEPA direct debits are these too.
|
|
export struct BunqIncomingRequest {
|
|
std::uint64_t id;
|
|
std::string status; // PENDING, ACCEPTED, REJECTED, REFUND_REQUESTED, REFUNDED or REVOKED
|
|
std::string type; // INTERNAL, DIRECT_DEBIT, DIRECT_DEBIT_B2B, IDEAL or SOFORT
|
|
BunqLabel counterparty;
|
|
Currency currency;
|
|
std::int64_t amount; // what is asked, in the currency's minor unit
|
|
std::string description;
|
|
std::chrono::system_clock::time_point created;
|
|
};
|
|
|
|
// When a scheduled payment runs. bunq keeps these times in UTC.
|
|
export struct BunqSchedule {
|
|
std::chrono::system_clock::time_point start;
|
|
std::optional<std::chrono::system_clock::time_point> end;
|
|
std::string unit = "ONCE"; // ONCE, HOURLY, DAILY, WEEKLY, MONTHLY or YEARLY
|
|
std::uint32_t every = 1; // with WEEKLY, 2 is every other week
|
|
std::string status; // ACTIVE, FINISHED or CANCELLED; ignored when scheduling
|
|
std::optional<std::chrono::system_clock::time_point> next; // the next run, when bunq says; ignored when scheduling
|
|
|
|
// Throws std::invalid_argument for a unit bunq does not know or `every` of 0, as Schedule would.
|
|
void Check() const;
|
|
};
|
|
|
|
// A payment bunq makes on a schedule (a bunq SchedulePayment).
|
|
export struct BunqScheduledPayment {
|
|
std::uint64_t id;
|
|
BunqLabel counterparty;
|
|
Currency currency;
|
|
std::int64_t amount; // each payment, in the currency's minor unit
|
|
std::string description;
|
|
BunqSchedule schedule;
|
|
};
|
|
|
|
// A payment waiting for approval (a bunq DraftPayment): made through OAuth, which may not pay others directly, or
|
|
// for an account that needs a second approval.
|
|
export struct BunqDraftPayment {
|
|
struct Entry {
|
|
BunqLabel counterparty;
|
|
Currency currency;
|
|
std::int64_t amount;
|
|
std::string description;
|
|
};
|
|
std::uint64_t id;
|
|
std::string status; // PENDING, ACCEPTED, REJECTED or CANCELLED
|
|
std::string createdBy;
|
|
std::vector<Entry> entries; // each becomes a payment when the draft is accepted
|
|
std::string updated; // bunq's time of its last change, as bunq wrote it; empty when bunq gave none
|
|
};
|
|
|
|
export struct BunqCard {
|
|
std::uint64_t id;
|
|
std::string kind; // bunq's object: CardDebit, CardCredit, ...
|
|
std::string productType; // MASTERCARD_DEBIT, MAESTRO_DEBIT, ...
|
|
std::string status; // ACTIVE, DEACTIVATED, LOST, STOLEN, CANCELLED, EXPIRED or PIN_TRIES_EXCEEDED
|
|
std::string orderStatus;
|
|
std::string nameOnCard;
|
|
std::string secondLine;
|
|
std::string lastFour; // last four digits of the card number
|
|
std::string expiry; // YYYY-MM-DD
|
|
std::string iban; // the account it pays from
|
|
};
|
|
|
|
export struct BunqAccount : public Account {
|
|
std::uint64_t id;
|
|
std::string type; // bunq's object: MonetaryAccountBank, MonetaryAccountSavings, MonetaryAccountJoint, ...
|
|
BunqConnector* connector;
|
|
|
|
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);
|
|
|
|
// "/user/{user}/monetary-account/{id}", the API path everything below hangs from.
|
|
std::string Path() const;
|
|
// Where this account's transactions are stored (the `connector` argument of Account's transaction calls):
|
|
// the connector's StorageKey and the account id, so two accounts with one name never share a table.
|
|
std::string StorageKey() const;
|
|
|
|
// Amounts are in the currency's minor unit and positive; `to` and `from` are read by BunqCounterparty::Parse.
|
|
// Each returns the id bunq gave the new object.
|
|
std::uint64_t Send(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
|
|
std::uint64_t Draft(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
|
|
std::uint64_t Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const;
|
|
// Asks `from` for money. bunq.me is allowed, so someone without bunq can pay through the returned share URL.
|
|
BunqPaymentRequest Request(std::string_view from, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
|
|
|
|
// Newest first.
|
|
std::vector<BunqPaymentRequest> Requests() const;
|
|
std::vector<BunqIncomingRequest> IncomingRequests() const;
|
|
std::vector<BunqScheduledPayment> ScheduledPayments() const;
|
|
std::vector<BunqDraftPayment> DraftPayments() const;
|
|
// One of each, as bunq has it now: what to show before answering it.
|
|
BunqIncomingRequest IncomingRequest(std::uint64_t id) const;
|
|
BunqDraftPayment DraftPayment(std::uint64_t id) const;
|
|
|
|
void RevokeRequest(std::uint64_t id) const;
|
|
// Answers the request as it was shown: accepting pays shown.amount from this account, whatever the request
|
|
// asks by now.
|
|
void RespondToRequest(const BunqIncomingRequest& shown, bool accept) const;
|
|
void CancelScheduledPayment(std::uint64_t id) const;
|
|
// Answers the draft as it was shown: bunq refuses the answer when the draft changed since (by shown.updated).
|
|
void RespondToDraftPayment(const BunqDraftPayment& shown, bool accept) const;
|
|
};
|
|
|
|
export struct BunqConnector {
|
|
BunqEnvironment environment = BunqEnvironment::Production;
|
|
std::string apiKey; // the API key, or the OAuth access token it was connected with
|
|
std::string installationToken;
|
|
std::string sessionToken;
|
|
std::uint64_t sessionId = 0; // 0 for connectors saved before it was kept: bunq logs out the current session for 0
|
|
Crypto::Key privateKey;
|
|
Crypto::Key serverPublicKey; // verifies every response; fetched on first use for connectors saved before it was kept
|
|
std::string userType; // UserPerson, UserCompany, UserApiKey (connected through OAuth) or UserPaymentServiceProvider
|
|
std::string name;
|
|
std::uint64_t id = 0; // the user id in API paths; for OAuth the UserApiKey's own id
|
|
std::uint64_t ownerId = 0; // the bunq user whose accounts these are: `id`, or for OAuth the user who granted access
|
|
std::vector<BunqAccount> accounts;
|
|
|
|
// One call to the bunq API: `path` is below /v1 ("/user/1/monetary-account"), or a pagination URL. Bodies are
|
|
// signed, responses verified against the server's key, rate limits waited out, and an expired session
|
|
// renewed once. Throws BunqError for an error response. A POST, PUT or DELETE goes over a new connection, so
|
|
// nothing below replays it; when its outcome is unknown (a lost connection, a 5xx) the error says so.
|
|
nlohmann::json Get(std::string_view path);
|
|
nlohmann::json Post(std::string_view path, const nlohmann::json& body);
|
|
nlohmann::json Put(std::string_view path, const nlohmann::json& body);
|
|
nlohmann::json Delete(std::string_view path);
|
|
// Every item of a listing, following its pages, newest first.
|
|
std::vector<nlohmann::json> List(std::string_view path);
|
|
|
|
void RefreshSession();
|
|
// All open accounts, of every kind bunq has. One in a currency Nostro does not know is skipped, with a Note.
|
|
void RefreshAccounts();
|
|
// Fetches each account's payments newer than the last stored one and stores them.
|
|
void GetNewTransactions();
|
|
void GetNewTransactions(BunqAccount& account);
|
|
bool TestConnector();
|
|
// Ends the session at bunq. The API key or OAuth grant stays valid; revoke it in the bunq app.
|
|
void Logout();
|
|
|
|
std::vector<BunqCard> Cards();
|
|
// DEACTIVATED and ACTIVE freeze and unfreeze a card; LOST and STOLEN block it for good. Returns the card as
|
|
// bunq has it afterwards, which can differ from what was asked: a card never activated stays DEACTIVATED.
|
|
BunqCard SetCardStatus(std::uint64_t card, std::string_view status);
|
|
|
|
// The directory of this connector's transaction tables below <cache>/transactions: bunq, the environment
|
|
// and the user id, so two connectors never share a table.
|
|
std::string StorageKey() const;
|
|
// Connected through OAuth: bunq then allows payments between the user's own accounts and draft payments only.
|
|
bool IsOAuth() const;
|
|
|
|
static constexpr std::string connectorId = "bunq";
|
|
// A deque, so an account's `connector` stays valid when another connector is added.
|
|
static std::deque<BunqConnector> connectors;
|
|
|
|
// Registers a new key pair and device for `apiKey` (an API key or OAuth access token) and opens a session.
|
|
// `allowedIps` is a comma-separated list for the device, "*" for any address (a wildcard API key), or empty
|
|
// for the address this call comes from. A connector of the same kind for the same bunq user is replaced (that
|
|
// is how a key is renewed); one of the other kind (API key against OAuth) is refused, as every account would
|
|
// then be listed twice.
|
|
static BunqConnector& Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment);
|
|
// Forgets a connector: deletes its stored transactions and takes it out of `connectors`, keeping the other
|
|
// connectors' accounts pointing at their connector. Does not log out; call Logout first.
|
|
static void Remove(BunqConnector& connector);
|
|
static BunqEnvironment EnvironmentOfKey(std::string_view apiKey);
|
|
|
|
// OAuth: send the user to this URL, where they approve with the bunq app; bunq then redirects to
|
|
// `redirectUri` with `code` and `state` in the query. `redirectUri` must be registered with the OAuth client.
|
|
static std::string OAuthAuthorizationUrl(BunqEnvironment environment, std::string_view clientId, std::string_view redirectUri, std::string_view state);
|
|
// Exchanges the code from that redirect for an access token, which Create takes in place of an API key.
|
|
static std::string OAuthExchangeCode(BunqEnvironment environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
|
|
|
|
// Where API calls for `environment` go: bunq's own host, or wherever RedirectTo sent them.
|
|
static BunqEndpoint Endpoint(BunqEnvironment environment);
|
|
// Sends every API and OAuth token call, whatever the connector's environment, to `endpoint` from now on.
|
|
// For tests against a local server; nostro itself never calls it.
|
|
static void RedirectTo(BunqEndpoint endpoint);
|
|
|
|
using Account = BunqAccount;
|
|
|
|
private:
|
|
enum class Auth : std::uint8_t { None, Installation, Session };
|
|
nlohmann::json Call(std::string_view method, std::string_view path, const nlohmann::json* body, Auth auth, bool renew = true);
|
|
void ReadUser(const nlohmann::json& response);
|
|
void EnsureServerPublicKey();
|
|
bool fetchingServerKey = false;
|
|
};
|
|
|
|
void to_json(nlohmann::json& j, const BunqConnector& connector);
|
|
void from_json(const nlohmann::json& j, BunqConnector& connector);
|
|
|
|
// Shared by the implementation units; not exported.
|
|
namespace BunqJson {
|
|
// The object under `key` in a response's "Response" array.
|
|
nlohmann::json Item(const nlohmann::json& response, std::string_view key);
|
|
// The single object inside an item, such as the MonetaryAccountBank in {"MonetaryAccountBank": {...}}, with its key.
|
|
std::pair<std::string, const nlohmann::json*> Only(const nlohmann::json& item);
|
|
nlohmann::json Amount(std::int64_t amount, Currency currency);
|
|
nlohmann::json Pointer(const BunqCounterparty& counterparty);
|
|
std::pair<Currency, std::int64_t> ReadAmount(const nlohmann::json& amount);
|
|
BunqLabel ReadLabel(const nlohmann::json& label);
|
|
std::string String(const nlohmann::json& object, std::string_view key);
|
|
}
|
|
}
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqConnector> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqConnector& obj, std::format_context& ctx) const {
|
|
return std::formatter<std::string>::format(obj.name, ctx);
|
|
}
|
|
};
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqLabel> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqLabel& obj, std::format_context& ctx) const {
|
|
return std::formatter<std::string>::format(obj.iban.empty() ? obj.name : std::format("{} {}", obj.name, obj.iban), ctx);
|
|
}
|
|
};
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqPaymentRequest> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqPaymentRequest& obj, std::format_context& ctx) const {
|
|
std::string out = std::format("{}\t{}\t{}\t{}\t{}", obj.id, Nostro::FormatLocalTime(obj.created), obj.status, obj.counterparty, Nostro::FormatMoney(obj.amount, obj.currency));
|
|
if(obj.amountPaid && *obj.amountPaid != obj.amount) {
|
|
out += std::format(" (paid {})", Nostro::FormatMoney(*obj.amountPaid, obj.currency));
|
|
}
|
|
out += std::format("\t{}", obj.description);
|
|
if(!obj.shareUrl.empty()) {
|
|
out += std::format("\t{}", obj.shareUrl);
|
|
}
|
|
return std::formatter<std::string>::format(out, ctx);
|
|
}
|
|
};
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqIncomingRequest> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqIncomingRequest& obj, std::format_context& ctx) const {
|
|
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t{}\t{}\t{}\t{}", obj.id, Nostro::FormatLocalTime(obj.created), obj.status, obj.type, obj.counterparty, Nostro::FormatMoney(obj.amount, obj.currency), obj.description), ctx);
|
|
}
|
|
};
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqScheduledPayment> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqScheduledPayment& obj, std::format_context& ctx) const {
|
|
const Nostro::BunqSchedule& schedule = obj.schedule;
|
|
const std::map<std::string_view, std::pair<std::string_view, std::string_view>> units = {
|
|
{"HOURLY", {"hourly", "hours"}}, {"DAILY", {"daily", "days"}}, {"WEEKLY", {"weekly", "weeks"}}, {"MONTHLY", {"monthly", "months"}}, {"YEARLY", {"yearly", "years"}},
|
|
};
|
|
std::string when;
|
|
if(const auto unit = units.find(schedule.unit); unit != units.end()) {
|
|
when = schedule.every == 1 ? std::format("{} from {}", unit->second.first, Nostro::FormatLocalTime(schedule.start)) : std::format("every {} {} from {}", schedule.every, unit->second.second, Nostro::FormatLocalTime(schedule.start));
|
|
} else {
|
|
when = std::format("once on {}", Nostro::FormatLocalTime(schedule.start));
|
|
}
|
|
if(schedule.end) {
|
|
when += std::format(" until {}", Nostro::FormatLocalTime(*schedule.end));
|
|
}
|
|
if(schedule.next && schedule.status == "ACTIVE") {
|
|
when += std::format(", next {}", Nostro::FormatLocalTime(*schedule.next));
|
|
}
|
|
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t{}\t{}\t{}", obj.id, schedule.status, when, obj.counterparty, Nostro::FormatMoney(obj.amount, obj.currency), obj.description), ctx);
|
|
}
|
|
};
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqDraftPayment> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqDraftPayment& obj, std::format_context& ctx) const {
|
|
std::string out = std::format("{}\t{}\t{}", obj.id, obj.status, obj.createdBy);
|
|
for(const Nostro::BunqDraftPayment::Entry& entry : obj.entries) {
|
|
out += std::format("\n\t{}\t{}\t{}", entry.counterparty, Nostro::FormatMoney(entry.amount, entry.currency), entry.description);
|
|
}
|
|
return std::formatter<std::string>::format(out, ctx);
|
|
}
|
|
};
|
|
|
|
template<>
|
|
struct std::formatter<Nostro::BunqCard> : std::formatter<std::string> {
|
|
auto format(const Nostro::BunqCard& obj, std::format_context& ctx) const {
|
|
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t**** {}\t{}\t{}\t{}\texpires {}", obj.id, obj.status, obj.productType, obj.lastFour, obj.nameOnCard, obj.secondLine, obj.iban, obj.expiry), ctx);
|
|
}
|
|
};
|
|
|
|
#endif
|