Nostro/implementations/Nostro-Bunq-Payments.cpp
2026-11-01 18:35:23 +01:00

333 lines
14 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
module Nostro:BunqPayments_impl;
import std;
import :Bunq;
import :Currency;
import :Utils;
using namespace Nostro;
using namespace nlohmann;
namespace {
// ISO 13616: with the first four characters moved to the end and letters read as 10 to 35, the number is 1 mod 97.
bool ValidIban(std::string_view iban) {
if(iban.size() < 15 || iban.size() > 34 || !std::isalpha(static_cast<std::uint8_t>(iban[0])) || !std::isalpha(static_cast<std::uint8_t>(iban[1])) || !std::isdigit(static_cast<std::uint8_t>(iban[2])) || !std::isdigit(static_cast<std::uint8_t>(iban[3]))) {
return false;
}
std::uint32_t remainder = 0;
const std::string rearranged = std::format("{}{}", iban.substr(4), iban.substr(0, 4));
for(const char c : rearranged) {
if(c >= '0' && c <= '9') {
remainder = (remainder * 10 + static_cast<std::uint32_t>(c - '0')) % 97;
} else if(c >= 'A' && c <= 'Z') {
remainder = (remainder * 100 + static_cast<std::uint32_t>(c - 'A' + 10)) % 97;
} else {
return false;
}
}
return remainder == 1;
}
void RequirePositive(std::int64_t amount) {
if(amount <= 0) {
throw std::invalid_argument("the amount must be more than zero");
}
}
std::uint64_t CreatedId(const json& response) {
return BunqJson::Item(response, "Id").at("id").get<std::uint64_t>();
}
// The objects of one type in a listing, skipping anything else bunq puts in it. Some listings name their objects
// differently from the spec (scheduled payments come as ScheduledPayment, not SchedulePayment): every name in
// `types` is taken.
template<typename T, typename Read>
std::vector<T> ReadAll(const std::vector<json>& items, std::initializer_list<std::string_view> types, Read&& read) {
std::vector<T> out;
for(const json& item : items) {
for(const std::string_view type : types) {
if(const json::const_iterator object = item.find(type); object != item.end()) {
out.push_back(read(*object));
break;
}
}
}
return out;
}
std::chrono::system_clock::time_point Timestamp(const json& object, std::string_view key) {
const std::string text = BunqJson::String(object, key);
return text.empty() ? std::chrono::system_clock::time_point() : ParseTimestamp(text);
}
BunqPaymentRequest ReadRequest(const json& inquiry) {
const auto [currency, amount] = BunqJson::ReadAmount(inquiry.at("amount_inquired"));
BunqPaymentRequest out{
.id = inquiry.at("id").get<std::uint64_t>(),
.status = BunqJson::String(inquiry, "status"),
.counterparty = BunqJson::ReadLabel(inquiry.at("counterparty_alias")),
.currency = currency,
.amount = amount,
.amountPaid = std::nullopt,
.description = BunqJson::String(inquiry, "description"),
.created = Timestamp(inquiry, "created"),
.shareUrl = BunqJson::String(inquiry, "bunqme_share_url"),
};
if(const json::const_iterator paid = inquiry.find("amount_responded"); paid != inquiry.end() && paid->is_object()) {
out.amountPaid = BunqJson::ReadAmount(*paid).second;
}
return out;
}
BunqIncomingRequest ReadIncoming(const json& response) {
const auto [currency, amount] = BunqJson::ReadAmount(response.at("amount_inquired"));
return BunqIncomingRequest{
.id = response.at("id").get<std::uint64_t>(),
.status = BunqJson::String(response, "status"),
.type = BunqJson::String(response, "type"),
.counterparty = BunqJson::ReadLabel(response.at("counterparty_alias")),
.currency = currency,
.amount = amount,
.description = BunqJson::String(response, "description"),
.created = Timestamp(response, "created"),
};
}
BunqScheduledPayment ReadScheduled(const json& scheduled) {
const json& payment = scheduled.at("payment");
const json& schedule = scheduled.at("schedule");
const auto [currency, amount] = BunqJson::ReadAmount(payment.at("amount"));
BunqSchedule when{
.start = Timestamp(schedule, "time_start"),
.end = std::nullopt,
.unit = BunqJson::String(schedule, "recurrence_unit"),
.every = schedule.value("recurrence_size", std::uint32_t{1}),
.status = BunqJson::String(scheduled, "status"),
.next = std::nullopt,
};
if(!BunqJson::String(schedule, "time_end").empty()) {
when.end = Timestamp(schedule, "time_end");
}
if(!BunqJson::String(schedule, "time_next").empty()) {
when.next = Timestamp(schedule, "time_next");
}
if(when.status.empty()) {
when.status = BunqJson::String(schedule, "status");
}
return BunqScheduledPayment{
.id = scheduled.at("id").get<std::uint64_t>(),
.counterparty = BunqJson::ReadLabel(payment.at("counterparty_alias")),
.currency = currency,
// Each run sends this much; bunq lists it as positive or negative depending on the endpoint.
.amount = amount < 0 ? -amount : amount,
.description = BunqJson::String(payment, "description"),
.schedule = std::move(when),
};
}
BunqDraftPayment ReadDraft(const json& draft) {
BunqDraftPayment out{
.id = draft.at("id").get<std::uint64_t>(),
.status = BunqJson::String(draft, "status"),
.createdBy = std::string(),
.entries = {},
.updated = BunqJson::String(draft, "updated"),
};
if(const json::const_iterator creator = draft.find("user_alias_created"); creator != draft.end()) {
out.createdBy = BunqJson::String(*creator, "display_name");
}
if(const json::const_iterator entries = draft.find("entries"); entries != draft.end() && entries->is_array()) {
for(const json& entry : *entries) {
const auto [currency, amount] = BunqJson::ReadAmount(entry.at("amount"));
out.entries.push_back(BunqDraftPayment::Entry{
.counterparty = BunqJson::ReadLabel(entry.at("counterparty_alias")),
.currency = currency,
.amount = amount < 0 ? -amount : amount,
.description = BunqJson::String(entry, "description"),
});
}
}
return out;
}
// What a payment, draft entry and scheduled payment share.
json PaymentBody(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) {
RequirePositive(amount);
return json{
{"amount", BunqJson::Amount(amount, currency)},
{"counterparty_alias", BunqJson::Pointer(BunqCounterparty::Parse(to, name))},
{"description", std::string(description)},
};
}
}
BunqCounterparty BunqCounterparty::Parse(std::string_view value, std::string_view name) {
while(value.starts_with(' ')) {
value.remove_prefix(1);
}
while(value.ends_with(' ')) {
value.remove_suffix(1);
}
if(value.contains('@')) {
return BunqCounterparty{"EMAIL", std::string(value), std::string(name)};
}
if(value.starts_with('+')) {
std::string phone = "+";
for(const char c : value.substr(1)) {
if(c >= '0' && c <= '9') {
phone += c;
} else if(c != ' ' && c != '-' && c != '(' && c != ')') {
throw std::invalid_argument(std::format("'{}' is not a phone number", value));
}
}
if(phone.size() < 8) {
throw std::invalid_argument(std::format("'{}' is not a phone number", value));
}
return BunqCounterparty{"PHONE_NUMBER", std::move(phone), std::string(name)};
}
std::string iban;
for(const char c : value) {
if(c != ' ') {
iban += static_cast<char>(std::toupper(static_cast<std::uint8_t>(c)));
}
}
if(!ValidIban(iban)) {
throw std::invalid_argument(std::format("'{}' is not a valid IBAN, e-mail address or phone number (+31...)", value));
}
return BunqCounterparty{"IBAN", std::move(iban), std::string(name)};
}
std::uint64_t BunqAccount::Send(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
return CreatedId(connector->Post(std::format("{}/payment", Path()), PaymentBody(to, name, amount, currency, description)));
}
std::uint64_t BunqAccount::Draft(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
const json body = {
{"entries", json::array({PaymentBody(to, name, amount, currency, description)})},
{"number_of_required_accepts", 1},
};
return CreatedId(connector->Post(std::format("{}/draft-payment", Path()), body));
}
void BunqSchedule::Check() const {
constexpr std::array<std::string_view, 6> units = {"ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};
if(!std::ranges::contains(units, unit)) {
throw std::invalid_argument(std::format("'{}' is not a schedule: once, hourly, daily, weekly, monthly or yearly", unit));
}
if(every == 0) {
throw std::invalid_argument("a schedule repeats at least every 1 unit");
}
}
std::uint64_t BunqAccount::Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const {
schedule.Check();
json when = {
{"time_start", FormatTimestamp(schedule.start)},
{"recurrence_unit", schedule.unit},
{"recurrence_size", schedule.every},
};
if(schedule.end) {
when["time_end"] = FormatTimestamp(*schedule.end);
}
const json body = {
{"payment", PaymentBody(to, name, amount, currency, description)},
{"schedule", std::move(when)},
};
return CreatedId(connector->Post(std::format("{}/schedule-payment", Path()), body));
}
BunqPaymentRequest BunqAccount::Request(std::string_view from, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
RequirePositive(amount);
const json body = {
{"amount_inquired", BunqJson::Amount(amount, currency)},
{"counterparty_alias", BunqJson::Pointer(BunqCounterparty::Parse(from, name))},
{"description", std::string(description)},
{"allow_bunqme", true},
};
const std::uint64_t id = CreatedId(connector->Post(std::format("{}/request-inquiry", Path()), body));
// The share URL is only on the object, not in the creation's response. The request exists whatever happens to
// this read: failing here would look like a failed request, and asking again would ask twice.
try {
return ReadRequest(BunqJson::Item(connector->Get(std::format("{}/request-inquiry/{}", Path(), id)), "RequestInquiry"));
} catch(const std::exception& e) {
Note(std::format("request {} was made, but reading it back failed: {}", id, e.what()));
const BunqCounterparty counterparty = BunqCounterparty::Parse(from, name);
return BunqPaymentRequest{
.id = id,
.status = "PENDING",
.counterparty = BunqLabel{counterparty.name, counterparty.type == "IBAN" ? counterparty.value : std::string()},
.currency = currency,
.amount = amount,
.amountPaid = std::nullopt,
.description = std::string(description),
.created = std::chrono::system_clock::now(),
.shareUrl = std::string(),
};
}
}
std::vector<BunqPaymentRequest> BunqAccount::Requests() const {
return ReadAll<BunqPaymentRequest>(connector->List(std::format("{}/request-inquiry", Path())), {"RequestInquiry"}, ReadRequest);
}
std::vector<BunqIncomingRequest> BunqAccount::IncomingRequests() const {
return ReadAll<BunqIncomingRequest>(connector->List(std::format("{}/request-response", Path())), {"RequestResponse"}, ReadIncoming);
}
std::vector<BunqScheduledPayment> BunqAccount::ScheduledPayments() const {
return ReadAll<BunqScheduledPayment>(connector->List(std::format("{}/schedule-payment", Path())), {"ScheduledPayment", "SchedulePayment"}, ReadScheduled);
}
std::vector<BunqDraftPayment> BunqAccount::DraftPayments() const {
return ReadAll<BunqDraftPayment>(connector->List(std::format("{}/draft-payment", Path())), {"DraftPayment"}, ReadDraft);
}
BunqIncomingRequest BunqAccount::IncomingRequest(std::uint64_t id) const {
return ReadIncoming(BunqJson::Item(connector->Get(std::format("{}/request-response/{}", Path(), id)), "RequestResponse"));
}
BunqDraftPayment BunqAccount::DraftPayment(std::uint64_t id) const {
return ReadDraft(BunqJson::Item(connector->Get(std::format("{}/draft-payment/{}", Path(), id)), "DraftPayment"));
}
void BunqAccount::RevokeRequest(std::uint64_t id) const {
connector->Put(std::format("{}/request-inquiry/{}", Path(), id), json{{"status", "REVOKED"}});
}
void BunqAccount::RespondToRequest(const BunqIncomingRequest& shown, bool accept) const {
const std::string path = std::format("{}/request-response/{}", Path(), shown.id);
if(!accept) {
connector->Put(path, json{{"status", "REJECTED"}});
return;
}
// Accepting names the amount paid: the amount that was shown, not what the request asks by the time this runs,
// which the asker can change in between.
connector->Put(path, json{{"amount_responded", BunqJson::Amount(shown.amount, shown.currency)}, {"status", "ACCEPTED"}});
}
void BunqAccount::CancelScheduledPayment(std::uint64_t id) const {
connector->Delete(std::format("{}/schedule-payment/{}", Path(), id));
}
void BunqAccount::RespondToDraftPayment(const BunqDraftPayment& shown, bool accept) const {
// bunq refuses a response to a draft that changed since it was read, by its updated timestamp: the one of the
// draft that was shown, so a change made after that is refused rather than accepted unseen.
json body = {{"status", accept ? "ACCEPTED" : "REJECTED"}};
if(!shown.updated.empty()) {
body["previous_updated_timestamp"] = shown.updated;
}
connector->Put(std::format("{}/draft-payment/{}", Path(), shown.id), body);
}