.. This file is part of GNU TALER. Copyright (C) 2014-2024 Taler Systems SA TALER is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation; either version 2.1, or (at your option) any later version. TALER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with TALER; see the file COPYING. If not, see @author Marcello Stanisci @author Florian Dold @author Christian Grothoff @author Priscilla Huang .. _merchant-api: ============================ Merchant Backend RESTful API ============================ .. contents:: Table of Contents :local: ----------------------- Base URLs and Instances ----------------------- A single merchant backend installation can host multiple merchant instances. This is useful when multiple businesses want to share the same payment infrastructure. Merchant backends have one special ``default`` instance. This ``default`` instance is used when no explicit instance is specified. Note that using ``/instances/default/$ANYTHING`` is deprecated and will result in a permanent redirect (HTTP status 308) to ``$ANYTHING``. a Despite its name, this instance must be created after the installation. In case *no* default instance is found - or its credentials got lost -, the administrator can use the default instance's rights by resorting on the ``--auth`` command line option, or by restarting the service by providing an environment variable called ``TALER_MERCHANT_TOKEN``. Each instance (default and others) has a base URL. The resources under this base URL are divided into to categories: * Public endpoints that are exposed to the Internet * Private endpoints (under ``/private/*``) that are only supposed to be exposed to the merchant internally, and must not be exposed on the Internet. * Management endpoints (under ``/management/*``) are also private and dedicated to CRUD operation over instances and reset authentication settings over all instances. Only accessible with the default instance authentication token Examples: .. code-block:: none Base URL of the merchant (default instance) at merchant-backend.example.com: https://merchant-backend.example.com/ A private endpoint (default instance): https://merchant-backend.example.com/private/orders A public endpoint (default instance and order id "ABCD"): https://merchant-backend.example.com/orders/ABCD A private endpoint ("myinst" instance): https://merchant-backend.example.com/instances/myinst/private/orders A public endpoint ("myinst" instance and order id "ABCD"): https://merchant-backend.example.com/instances/myinst/orders/ABCD A private endpoint (explicit "default" instance): https://merchant-backend.example.com/private/orders A public endpoint (explicit "default" instance): https://merchant-backend.example.com/orders Endpoints to manage other instances (ONLY for implicit "default" instance): https://merchant-backend.example.com/management/instances https://merchant-backend.example.com/management/instances/$ID Endpoints to manage own instance: https://merchant-backend.example.com/private https://merchant-backend.example.com/private/auth https://merchant-backend.example.com/instances/$ID/private https://merchant-backend.example.com/instances/$ID/private/auth Unavailabe endpoints (will return 404): https://merchant-backend.example.com/instances/myinst/private/instances -------------- Authentication -------------- Each merchant instance has separate authentication settings for the private API resources of that instance. Currently, the API supports two main authentication methods: * ``external``: With this method, no checks are done by the merchant backend. Instead, a reverse proxy / API gateway must do all authentication/authorization checks. * ``token``: With this method, the client must provide a ``Authorization: Bearer $TOKEN`` header, where ``$TOKEN`` is a secret authentication token configured for the instance which must begin with the RFC 8959 prefix. Additionally, clients can send a **login token** which they may obtain from the ``/private/token`` endpoint. Such a login token is valid only for a limited period of time and can be used by clients to avoid storing the long-term login secrets from an authentication method. ----------------- Configuration API ----------------- The configuration API exposes basic information about a merchant backend, such as the implemented version of the protocol and the currency used. .. http:get:: /config Return the protocol version and currency supported by this merchant backend. This specification corresponds to ``current`` protocol being version **v14**. **Response:** :http:statuscode:`200 OK`: The body is a `VersionResponse`. .. ts:def:: VersionResponse interface VersionResponse { // libtool-style representation of the Merchant protocol version, see // https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning // The format is "current:revision:age". version: string; // Name of the protocol. name: "taler-merchant"; // URN of the implementation (needed to interpret 'revision' in version). // @since **v8**, may become mandatory in the future. implementation?: string; // Default (!) currency supported by this backend. // This is the currency that the backend should // suggest by default to the user when entering // amounts. See ``currencies`` for a list of // supported currencies and how to render them. currency: string; // How services should render currencies supported // by this backend. Maps // currency codes (e.g. "EUR" or "KUDOS") to // the respective currency specification. // All currencies in this map are supported by // the backend. Note that the actual currency // specifications are a *hint* for applications // that would like *advice* on how to render amounts. // Applications *may* ignore the currency specification // if they know how to render currencies that they are // used with. currencies: { currency : CurrencySpecification}; // Array of exchanges trusted by the merchant. // Since protocol **v6**. exchanges: ExchangeConfigInfo[]; } .. ts:def:: ExchangeConfigInfo interface ExchangeConfigInfo { // Base URL of the exchange REST API. base_url: string; // Currency for which the merchant is configured // to trust the exchange. // May not be the one the exchange actually uses, // but is the only one we would trust this exchange for. currency: string; // Offline master public key of the exchange. The // ``/keys`` data must be signed with this public // key for us to trust it. master_pub: EddsaPublicKey; } ---------- Wallet API ---------- This section describes (public) endpoints that wallets must be able to interact with directly (without HTTP-based authentication). These endpoints are used to process payments (claiming an order, paying for the order, checking payment/refund status and aborting payments), and to process refunds (checking refund status, obtaining the refund). Claiming an order ----------------- The first step of processing any Taler payment consists of the (authorized) wallet claiming the order for itself. In this process, the wallet provides a wallet-generated nonce that is added into the contract terms. This step prevents two different wallets from paying for the same contract, which would be bad especially if the merchant only has finite stocks. A claim token can be used to ensure that the wallet claiming an order is actually authorized to do so. This is useful in cases where order IDs are predictable and malicious actors may try to claim orders (say in a case where stocks are limited). .. http:post:: [/instances/$INSTANCE]/orders/$ORDER_ID/claim Wallet claims ownership (via nonce) over an order. By claiming an order, the wallet obtains the full contract terms, and thereby implicitly also the hash of the contract terms it needs for the other ``public`` APIs to authenticate itself as the wallet that is indeed eligible to inspect this particular order's status. **Request:** The request must be a `ClaimRequest`. .. ts:def:: ClaimRequest interface ClaimRequest { // Nonce to identify the wallet that claimed the order. nonce: string; // Token that authorizes the wallet to claim the order. // *Optional* as the merchant may not have required it // (``create_token`` set to ``false`` in `PostOrderRequest`). token?: ClaimToken; } **Response:** :http:statuscode:`200 OK`: The client has successfully claimed the order. The response contains the :ref:`contract terms `. :http:statuscode:`404 Not found`: The backend is unaware of the instance or order. :http:statuscode:`409 Conflict`: Someone else has already claimed the same order ID with a different nonce. .. ts:def:: ClaimResponse interface ClaimResponse { // Contract terms of the claimed order contract_terms: ContractTerms; // Signature by the merchant over the contract terms. sig: EddsaSignature; } Making the payment ------------------ .. http:post:: [/instances/$INSTANCE]/orders/$ORDER_ID/pay Pay for an order by giving a deposit permission for coins. Typically used by the customer's wallet. Note that this request does not include the usual ``h_contract`` argument to authenticate the wallet, as the hash of the contract is implied by the signatures of the coins. Furthermore, this API doesn't really return useful information about the order. **Request:** The request must be a `pay request `. **Response:** :http:statuscode:`200 OK`: The exchange accepted all of the coins. The body is a `payment response `. The ``frontend`` should now fulfill the contract. Note that it is possible that refunds have been granted. :http:statuscode:`400 Bad request`: Either the client request is malformed or some specific processing error happened that may be the fault of the client as detailed in the JSON body of the response. This includes the case where the payment is insufficient (sum is below the required total amount, for example because the wallet calculated the fees wrong). :http:statuscode:`402 Payment required`: There used to be a sufficient payment, but due to refunds the amount effectively paid is no longer sufficient. (If the amount is generally insufficient, we return "400 Bad Request", only if this is because of refunds we return 402.) :http:statuscode:`403 Forbidden`: One of the coin signatures was not valid. :http:statuscode:`404 Not found`: The merchant backend could not find the order or the instance and thus cannot process the payment. :http:statuscode:`408 Request timeout`: The backend took too long to process the request. Likely the merchant's connection to the exchange timed out. Try again. :http:statuscode:`409 Conflict`: The exchange rejected the payment because a coin was already spent (or used in a different way for the same purchase previously), or the merchant rejected the payment because the order was already fully paid (and then return signatures with refunds). If a coin was already spent (this includes re-using the same coin after a refund), the response will include the ``exchange_url`` for which the payment failed, in addition to the response from the exchange to the ``/batch-deposit`` request. :http:statuscode:`410 Gone`: The offer has expired and is no longer available. :http:statuscode:`412 Precondition failed`: The given exchange is not acceptable for this merchant, as it is not in the list of accepted exchanges and not audited by an approved auditor. TODO: Status code may be changed to 409 in the future as 412 is technically wrong. :http:statuscode:`502 Bad gateway`: The merchant's interaction with the exchange failed in some way. The client might want to try again later. This includes failures such as the denomination key of a coin not being known to the exchange as far as the merchant can tell. :http:statuscode:`504 Gateway timeout`: The merchant's interaction with the exchange took too long. The client might want to try again later. The backend will return verbatim the error codes received from the exchange's :ref:`deposit ` API. If the wallet made a mistake, like by double-spending for example, the frontend should pass the reply verbatim to the browser/wallet. If the payment was successful, the frontend MAY use this to trigger some business logic. .. ts:def:: PaymentResponse interface PaymentResponse { // Signature on ``TALER_PaymentResponsePS`` with the public // key of the merchant instance. sig: EddsaSignature; // Text to be shown to the point-of-sale staff as a proof of // payment. pos_confirmation?: string; } .. ts:def:: PayRequest interface PayRequest { // The coins used to make the payment. coins: CoinPaySig[]; // Index of the selected choice within the ``choices`` array of // the contract terms. // @since protocol **vSUBSCRIBE** choice_index?: Integer; // Input tokens required by choice indicated by ``choice_index``. // @since protocol **vSUBSCRIBE** tokens: TokenUseSig[]; // Array of output tokens to be (blindly) signed by the merchant. // Output tokens specified in choice indicated by ``choice_index``. // @since protocol **vSUBSCRIBE** tokens_evs: TokenEnvelope[]; // Custom inputs from the wallet for the contract. wallet_data?: Object; // The session for which the payment is made (or replayed). // Only set for session-based payments. session_id?: string; } .. ts:def:: CoinPaySig export interface CoinPaySig { // Signature by the coin. coin_sig: EddsaSignature; // Public key of the coin being spent. coin_pub: EddsaPublicKey; // Signature made by the denomination public key. ub_sig: UnblindedSignature; // The hash of the denomination public key associated with this coin. h_denom: HashCode; // The amount that is subtracted from this coin with this payment. contribution: Amount; // URL of the exchange this coin was withdrawn from. exchange_url: string; // Signature affirming the posession of the // respective private key proving that the payer // is old enough. Only provided if the paid contract // has an age restriction and the coin is // age-restricted. minimum_age_sig?: EddsaSignature; // Age commitment vector of the coin. // Only provided if the paid contract // has an age restriction and the coin is // age-restricted. age_commitment?: Edx25519PublicKey[]; // Hash over the agge commitment vector of the coin. // Only provided if the paid contract // does NOT have an age restriction and the coin is // age-restricted. h_age_commitment?: AgeCommitmentHash; } .. ts:def:: TokenUseSig interface TokenUseSig { // Signature on ``TALER_DepositRequestPS`` with the public key of the // token being provisioned to the merchant. token_sig: EddsaSignature; // Public key of the token being provisioned to the merchant. token_pub: EddsaPublicKey; // Unblinded signature made by the token family public key of the merchant. ub_sig: UnblindedSignature; // The hash of the token family public key associated with this token. h_denom: HashCode; } .. ts:def:: TokenEnvelope // This type depends on the cipher used to sign token families. This is // configured by the merchant and defined for each token family in the // contract terms. type TokenEnvelope = RSATokenEnvelope | CSTokenEnvelope; .. ts:def:: RSATokenEnvelope interface RSATokenEnvelope { // RSA is used for the blind signature. cipher: "RSA"; // Blinded signature of the token's `public EdDSA key `. rsa_blinded_pub: BlindedRsaSignature; } .. ts:def:: CSTokenEnvelope interface CSTokenEnvelope { // Blind Clause-Schnorr signature scheme is used for the blind signature. // See https://taler.net/papers/cs-thesis.pdf for details. cipher: "CS"; // Public nonce cs_nonce: string; // Crockford `Base32` encoded // Two Curve25519 scalars, each representing a blinded challenge cs_blinded_c0: string; // Crockford `Base32` encoded cs_blinded_c1: string; // Crockford `Base32` encoded } Querying payment status ----------------------- .. http:get:: [/instances/$INSTANCE]/orders/$ORDER_ID Query the payment status of an order. This endpoint is for the wallet. When the wallet goes to this URL and it is unpaid, it will be prompted for payment. This endpoint typically also supports requests with the "Accept" header requesting "text/html". In this case, an HTML response suitable for triggering the interaction with the wallet is returned, with ``timeout_ms`` ignored (treated as zero). If the backend installation does not include the required HTML templates, a 406 status code is returned. In the case that the request was made with a claim token (even the wrong one) and the order was claimed and paid, the server will redirect the client to the fulfillment URL. This redirection will happen with a 302 status code if the "Accept" header specified "text/html", and with a 202 status code otherwise. **Request:** :query h_contract=HASH: *Optional*. Hash of the order's contract terms (this is used to authenticate the wallet/customer in case $ORDER_ID is guessable). Required once an order was claimed. :query token=TOKEN: *Optional*. Authorizes the request via the claim token that was returned in the `PostOrderResponse`. Used with unclaimed orders only. Whether token authorization is required is determined by the merchant when the frontend creates the order. :query session_id=STRING: *Optional*. Session ID that the payment must be bound to. If not specified, the payment is not session-bound. :query timeout_ms=NUMBER: *Optional.* If specified, the merchant backend will wait up to ``timeout_ms`` milliseconds for completion of the payment before sending the HTTP response. A client must never rely on this behavior, as the merchant backend may return a response immediately. :query await_refund_obtained=BOOLEAN: *Optional*. If set to "yes", poll for the order's pending refunds to be picked up. ``timeout_ms`` specifies how long we will wait for the refund. :query refund=AMOUNT: *Optional*. Indicates that we are polling for a refund above the given AMOUNT. ``timeout_ms`` will specify how long we will wait for the refund. :query allow_refunded_for_repurchase: *Optional*. Since protocol **v9** refunded orders are only returned under "already_paid_order_id" if this flag is set explicitly to "YES". **Response:** :http:statuscode:`200 OK`: The response is a `StatusPaidResponse`. :http:statuscode:`202 Accepted`: The response is a `StatusGotoResponse`. Only returned if the content type requested was not HTML. The target site may allow the client to setup a fresh order (as this one has been taken) or may trigger repurchase detection. :http:statuscode:`302 Found`: The client should go to the indicated location (via HTTP "Location:" header). Only returned if the content type requested was HTML. The target site may allow the client to setup a fresh order (as this one has been taken) or may trigger repurchase detection. :http:statuscode:`402 Payment required`: The response is a `StatusUnpaidResponse`. :http:statuscode:`403 Forbidden`: The ``h_contract`` (or the ``token`` for unclaimed orders) does not match the order and we have no fulfillment URL in the contract. :http:statuscode:`404 Not found`: The merchant backend is unaware of the order. :http:statuscode:`406 Not acceptable`: The merchant backend could not load the template required to generate a reply in the desired format. (Likely HTML templates were not properly installed.) .. ts:def:: StatusPaidResponse interface StatusPaid { // Was the payment refunded (even partially, via refund or abort)? refunded: boolean; // Is any amount of the refund still waiting to be picked up (even partially)? refund_pending: boolean; // Amount that was refunded in total. refund_amount: Amount; // Amount that already taken by the wallet. refund_taken: Amount; } .. ts:def:: StatusGotoResponse interface StatusGotoResponse { // The client should go to the reorder URL, there a fresh // order might be created as this one is taken by another // customer or wallet (or repurchase detection logic may // apply). public_reorder_url: string; } .. ts:def:: StatusUnpaidResponse interface StatusUnpaidResponse { // URI that the wallet must process to complete the payment. taler_pay_uri: string; // Status URL, can be used as a redirect target for the browser // to show the order QR code / trigger the wallet. fulfillment_url?: string; // Alternative order ID which was paid for already in the same session. // Only given if the same product was purchased before in the same session. already_paid_order_id?: string; } Demonstrating payment --------------------- In case a wallet has already paid for an order, this is a fast way of proving to the merchant that the order was already paid. The alternative would be to replay the original payment, but simply providing the merchant's signature saves bandwidth and computation time. Demonstrating payment is useful in case a digital good was made available only to clients with a particular session ID: if that session ID expired or if the user is using a different client, demonstrating payment will allow the user to regain access to the digital good without having to pay for it again. .. http:post:: [/instances/$INSTANCE]/orders/$ORDER_ID/paid Prove that the client previously paid for an order by providing the merchant's signature from the `payment response `. Typically used by the customer's wallet if it receives a request for payment for an order that it already paid. This is more compact than re-transmitting the full payment details. Note that this request does include the usual ``h_contract`` argument to authenticate the wallet and to allow the merchant to verify the signature before checking with its own database. **Request:** The request must be a `paid request `. **Response:** :http:statuscode:`200 Ok`: The merchant accepted the signature. The ``frontend`` should now fulfill the contract. Note that it is possible that refunds have been granted. Response is of type `PaidRefundStatusResponse`. :http:statuscode:`400 Bad request`: Either the client request is malformed or some specific processing error happened that may be the fault of the client as detailed in the JSON body of the response. :http:statuscode:`403 Forbidden`: The signature was not valid. :http:statuscode:`404 Not found`: The merchant backend could not find the order or the instance and thus cannot process the request. **Details**: .. ts:def:: PaidRefundStatusResponse interface PaidRefundStatusResponse { // Text to be shown to the point-of-sale staff as a proof of // payment (present only if re-usable OTP algorithm is used). pos_confirmation?: string; // True if the order has been subjected to // refunds. False if it was simply paid. refunded: boolean; } .. ts:def:: PaidRequest interface PaidRequest { // Signature on ``TALER_PaymentResponsePS`` with the public // key of the merchant instance. sig: EddsaSignature; // Hash of the order's contract terms (this is used to authenticate the // wallet/customer and to enable signature verification without // database access). h_contract: HashCode; // Hash over custom inputs from the wallet for the contract. wallet_data_hash?: HashCode; // Session id for which the payment is proven. session_id: string; } Aborting incomplete payments ---------------------------- In rare cases (such as a wallet restoring from an outdated backup) it is possible that a wallet fails to complete a payment because it runs out of e-cash in the middle of the process. The abort API allows the wallet to abort the payment for such an incomplete payment and to regain control over the coins that were spent so far. Aborts are not permitted for payments that have completed. In contrast to refunds, aborts do not require approval by the merchant because aborts always are for incomplete payments for an order and never for established contracts. .. _order-abort: .. http:post:: [/instances/$INSTANCE]/orders/$ORDER_ID/abort Abort paying for an order and obtain a refund for coins that were already deposited as part of a failed payment. **Request:** The request must be an `abort request `. We force the wallet to specify the affected coins as it may only request for a subset of the coins (i.e. because the wallet knows that some were double-spent causing the failure). Also we need to know the coins because there may be two wallets "competing" over the same order and one wants to abort while the other still proceeds with the payment. Here we need to again know which subset of the deposits to abort. **Response:** :http:statuscode:`200 OK`: The merchant accepted the request, and passed it on to the exchange. The body is a a `abort response `. Note that the exchange MAY still have encountered errors in processing. Those will then be part of the body. Wallets MUST carefully consider errors for each of the coins as returned by the exchange. :http:statuscode:`400 Bad request`: Either the client request is malformed or some specific processing error happened that may be the fault of the client as detailed in the JSON body of the response. :http:statuscode:`403 Forbidden`: The ``h_contract`` does not match the $ORDER_ID. :http:statuscode:`404 Not found`: The merchant backend could not find the order or the instance and thus cannot process the abort request. :http:statuscode:`408 Request timeout`: The merchant backend took too long getting a response from the exchange. The wallet SHOULD retry soon. :http:statuscode:`412 Precondition failed`: Aborting the payment is not allowed, as the original payment did succeed. It is possible that a different wallet succeeded with the payment. This wallet should thus try to refresh all of the coins involved in the payment. :http:statuscode:`502 Bad gateway`: The merchant's interaction with the exchange failed in some way. The error from the exchange is included. :http:statuscode:`504 Gateway timeout`: The merchant's interaction with the exchange took too long. The client might want to try again later. The backend will return an `abort response `, which includes verbatim the error codes received from the exchange's :ref:`refund ` API. The frontend should pass the replies verbatim to the browser/wallet. .. ts:def:: AbortRequest interface AbortRequest { // Hash of the order's contract terms (this is used to authenticate the // wallet/customer in case $ORDER_ID is guessable). h_contract: HashCode; // List of coins the wallet would like to see refunds for. // (Should be limited to the coins for which the original // payment succeeded, as far as the wallet knows.) coins: AbortingCoin[]; } .. ts:def:: AbortingCoin interface AbortingCoin { // Public key of a coin for which the wallet is requesting an abort-related refund. coin_pub: EddsaPublicKey; // The amount to be refunded (matches the original contribution) contribution: Amount; // URL of the exchange this coin was withdrawn from. exchange_url: string; } .. ts:def:: AbortResponse interface AbortResponse { // List of refund responses about the coins that the wallet // requested an abort for. In the same order as the ``coins`` // from the original request. // The ``rtransaction_id`` is implied to be 0. refunds: MerchantAbortPayRefundStatus[]; } .. ts:def:: MerchantAbortPayRefundStatus type MerchantAbortPayRefundStatus = | MerchantAbortPayRefundSuccessStatus | MerchantAbortPayRefundFailureStatus; .. ts:def:: MerchantAbortPayRefundFailureStatus // Details about why a refund failed. interface MerchantAbortPayRefundFailureStatus { // Used as tag for the sum type RefundStatus sum type. type: "failure"; // HTTP status of the exchange request, must NOT be 200. exchange_status: Integer; // Taler error code from the exchange reply, if available. exchange_code?: Integer; // If available, HTTP reply from the exchange. exchange_reply?: Object; } .. ts:def:: MerchantAbortPayRefundSuccessStatus // Additional details needed to verify the refund confirmation signature // (``h_contract_terms`` and ``merchant_pub``) are already known // to the wallet and thus not included. interface MerchantAbortPayRefundSuccessStatus { // Used as tag for the sum type MerchantCoinRefundStatus sum type. type: "success"; // HTTP status of the exchange request, 200 (integer) required for refund confirmations. exchange_status: 200; // The EdDSA :ref:`signature` (binary-only) with purpose // `TALER_SIGNATURE_EXCHANGE_CONFIRM_REFUND` using a current signing key of the // exchange affirming the successful refund. exchange_sig: EddsaSignature; // Public EdDSA key of the exchange that was used to generate the signature. // Should match one of the exchange's signing keys from ``/keys``. It is given // explicitly as the client might otherwise be confused by clock skew as to // which signing key was used. exchange_pub: EddsaPublicKey; } Obtaining refunds ----------------- Refunds allow merchants to fully or partially restitute e-cash to a wallet, for example because the merchant determined that it could not actually fulfill the contract. Refunds must be approved by the merchant's business logic. .. http:post:: [/instances/$INSTANCE]/orders/$ORDER_ID/refund Obtain refunds for an order. After talking to the exchange, the refunds will no longer be pending if processed successfully. **Request:** The request body is a `WalletRefundRequest` object. **Response:** :http:statuscode:`200 OK`: The response is a `WalletRefundResponse`. :http:statuscode:`204 No content`: There are no refunds for the order. :http:statuscode:`403 Forbidden`: The ``h_contract`` does not match the order. :http:statuscode:`404 Not found`: The merchant backend is unaware of the order. .. ts:def:: WalletRefundRequest interface WalletRefundRequest { // Hash of the order's contract terms (this is used to authenticate the // wallet/customer). h_contract: HashCode; } .. ts:def:: WalletRefundResponse interface WalletRefundResponse { // Amount that was refunded in total. refund_amount: Amount; // Successful refunds for this payment, empty array for none. refunds: MerchantCoinRefundStatus[]; // Public key of the merchant. merchant_pub: EddsaPublicKey; } .. ts:def:: MerchantCoinRefundStatus type MerchantCoinRefundStatus = | MerchantCoinRefundSuccessStatus | MerchantCoinRefundFailureStatus; .. ts:def:: MerchantCoinRefundFailureStatus // Details about why a refund failed. interface MerchantCoinRefundFailureStatus { // Used as tag for the sum type RefundStatus sum type. type: "failure"; // HTTP status of the exchange request, must NOT be 200. exchange_status: Integer; // Taler error code from the exchange reply, if available. exchange_code?: Integer; // If available, HTTP reply from the exchange. exchange_reply?: Object; // Refund transaction ID. rtransaction_id: Integer; // Public key of a coin that was refunded. coin_pub: EddsaPublicKey; // Amount that was refunded, including refund fee charged by the exchange // to the customer. refund_amount: Amount; // Timestamp when the merchant approved the refund. // Useful for grouping refunds. execution_time: Timestamp; } .. ts:def:: MerchantCoinRefundSuccessStatus // Additional details needed to verify the refund confirmation signature // (``h_contract_terms`` and ``merchant_pub``) are already known // to the wallet and thus not included. interface MerchantCoinRefundSuccessStatus { // Used as tag for the sum type MerchantCoinRefundStatus sum type. type: "success"; // HTTP status of the exchange request, 200 (integer) required for refund confirmations. exchange_status: 200; // The EdDSA :ref:`signature` (binary-only) with purpose // `TALER_SIGNATURE_EXCHANGE_CONFIRM_REFUND` using a current signing key of the // exchange affirming the successful refund. exchange_sig: EddsaSignature; // Public EdDSA key of the exchange that was used to generate the signature. // Should match one of the exchange's signing keys from /keys. It is given // explicitly as the client might otherwise be confused by clock skew as to // which signing key was used. exchange_pub: EddsaPublicKey; // Refund transaction ID. rtransaction_id: Integer; // Public key of a coin that was refunded. coin_pub: EddsaPublicKey; // Amount that was refunded, including refund fee charged by the exchange // to the customer. refund_amount: Amount; // Timestamp when the merchant approved the refund. // Useful for grouping refunds. execution_time: Timestamp; } ------------------- Instance management ------------------- Instances allow one merchant backend to be shared by multiple merchants. Every backend must have at least one instance, typically the "default" instance setup before it can be used to manage inventory or process payments. Setting up instances -------------------- .. http:post:: /management/instances This request will be used to create a new merchant instance in the backend. It is only available for the implicit ``default`` instance. **Request:** The request must be a `InstanceConfigurationMessage`. **Response:** :http:statuscode:`204 No content`: The backend has successfully created the instance. :http:statuscode:`409 Conflict`: This instance already exists, but with other configuration options. Use "PATCH" to update an instance configuration. Alternatively, the currency provided in the configuration does not match the currency supported by this backend. Another possible conflict would be if a deleted but not purged instance is known under this ID to the backend. .. ts:def:: InstanceConfigurationMessage interface InstanceConfigurationMessage { // Name of the merchant instance to create (will become $INSTANCE). // Must match the regex ``^[A-Za-z0-9][A-Za-z0-9_.@-]+$``. id: string; // Merchant name corresponding to this instance. name: string; // Type of the user (business or individual). // Defaults to 'business'. Should become mandatory field // in the future, left as optional for API compatibility for now. user_type?: string; // Merchant email for customer contact. email?: string; // Merchant public website. website?: string; // Merchant logo. logo?: ImageDataUrl; // Authentication settings for this instance auth: InstanceAuthConfigurationMessage; // The merchant's physical address (to be put into contracts). address: Location; // The jurisdiction under which the merchant conducts its business // (to be put into contracts). jurisdiction: Location; // Use STEFAN curves to determine default fees? // If false, no fees are allowed by default. // Can always be overridden by the frontend on a per-order basis. use_stefan: boolean; // If the frontend does NOT specify an execution date, how long should // we tell the exchange to wait to aggregate transactions before // executing the wire transfer? This delay is added to the current // time when we generate the advisory execution time for the exchange. default_wire_transfer_delay: RelativeTime; // If the frontend does NOT specify a payment deadline, how long should // offers we make be valid by default? default_pay_delay: RelativeTime; } .. http:post:: /management/instances/$INSTANCE/auth .. http:post:: [/instances/$INSTANCE]/private/auth Update the authentication settings for an instance. POST operations against an instance are authenticated by checking that an authorization is provided that matches either the credential required by the instance being modified OR the ``default`` instance, depending on the access path used. **Request** the request must be an `InstanceAuthConfigurationMessage`. :http:statuscode:`204 No content`: The backend has successfully created the instance. :http:statuscode:`404 Not found`: This instance is unknown and thus cannot be reconfigured. .. ts:def:: InstanceAuthConfigurationMessage interface InstanceAuthConfigurationMessage { // Type of authentication. // "external": The mechant backend does not do // any authentication checks. Instead an API // gateway must do the authentication. // "token": The merchant checks an auth token. // See "token" for details. method: "external" | "token"; // For method "token", this field is mandatory. // The token MUST begin with the string "secret-token:". // After the auth token has been set (with method "token"), // the value must be provided in a "Authorization: Bearer $token" // header. token?: string; } .. http:post:: [/instances/$INSTANCE]/private/token **Request:** The request must be a `LoginTokenRequest`. **Response:** :http:statuscode:`200 Ok`: The backend is returning the access token in a `LoginTokenSuccessResponse`. **Details:** .. ts:def:: LoginTokenRequest interface LoginTokenRequest { // Scope of the token (which kinds of operations it will allow) scope: "readonly" | "write"; // Server may impose its own upper bound // on the token validity duration duration?: RelativeTime; // Can this token be refreshed? // Defaults to false. refreshable?: boolean; } .. ts:def:: LoginTokenSuccessResponse interface LoginTokenSuccessResponse { // The login token that can be used to access resources // that are in scope for some time. Must be prefixed // with "Bearer " when used in the "Authorization" HTTP header. // Will already begin with the RFC 8959 prefix. token: string; // Scope of the token (which kinds of operations it will allow) scope: "readonly" | "write"; // Server may impose its own upper bound // on the token validity duration expiration: Timestamp; // Can this token be refreshed? refreshable: boolean; } .. http:delete:: [/instances/$INSTANCE]/private/token **Response:** :http:statuscode:`204 No content`: The access token used to authorize this request was revoked. .. http:patch:: /management/instances/$INSTANCE .. http:patch:: [/instances/$INSTANCE]/private Update the configuration of a merchant instance. PATCH operations against an instance are authenticated by checking that an authorization is provided that matches either the credential required by the instance being modified OR the ``default`` instance, depending on the access path used. **Request** The request must be a `InstanceReconfigurationMessage`. Removing an existing ``payto_uri`` deactivates the account (it will no longer be used for future contracts). **Response:** :http:statuscode:`204 No content`: The backend has successfully created the instance. :http:statuscode:`404 Not found`: This instance is unknown and thus cannot be reconfigured. .. ts:def:: InstanceReconfigurationMessage interface InstanceReconfigurationMessage { // Merchant name corresponding to this instance. name: string; // Type of the user (business or individual). // Defaults to 'business'. Should become mandatory field // in the future, left as optional for API compatibility for now. user_type?: string; // Merchant email for customer contact. email?: string; // Merchant public website. website?: string; // Merchant logo. logo?: ImageDataUrl; // The merchant's physical address (to be put into contracts). address: Location; // The jurisdiction under which the merchant conducts its business // (to be put into contracts). jurisdiction: Location; // Use STEFAN curves to determine default fees? // If false, no fees are allowed by default. // Can always be overridden by the frontend on a per-order basis. use_stefan: boolean; // If the frontend does NOT specify an execution date, how long should // we tell the exchange to wait to aggregate transactions before // executing the wire transfer? This delay is added to the current // time when we generate the advisory execution time for the exchange. default_wire_transfer_delay: RelativeTime; // If the frontend does NOT specify a payment deadline, how long should // offers we make be valid by default? default_pay_delay: RelativeTime; } Inspecting instances -------------------- .. _instances: .. http:get:: /management/instances This is used to return the list of all the merchant instances. It is only available for the implicit ``default`` instance. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the list of instances stored. Returns a `InstancesResponse`. .. ts:def:: InstancesResponse interface InstancesResponse { // List of instances that are present in the backend (see `Instance`). instances: Instance[]; } The `Instance` object describes the instance registered with the backend. It does not include the full details, only those that usually concern the frontend. It has the following structure: .. ts:def:: Instance interface Instance { // Merchant name corresponding to this instance. name: string; // Type of the user ("business" or "individual"). user_type: string; // Merchant public website. website?: string; // Merchant logo. logo?: ImageDataUrl; // Merchant instance this response is about ($INSTANCE). id: string; // Public key of the merchant/instance, in Crockford Base32 encoding. merchant_pub: EddsaPublicKey; // List of the payment targets supported by this instance. Clients can // specify the desired payment target in /order requests. Note that // front-ends do not have to support wallets selecting payment targets. payment_targets: string[]; // Has this instance been deleted (but not purged)? deleted: boolean; } .. http:get:: /management/instances/$INSTANCE .. http:get:: [/instances/$INSTANCE]/private This is used to query a specific merchant instance. GET operations against an instance are authenticated by checking that an authorization is provided that matches either the credential required by the instance being modified OR the ``default`` instance, depending on the access path used. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the list of instances stored. Returns a `QueryInstancesResponse`. .. ts:def:: QueryInstancesResponse interface QueryInstancesResponse { // Merchant name corresponding to this instance. name: string; // Type of the user ("business" or "individual"). user_type: string; // Merchant email for customer contact. email?: string; // Merchant public website. website?: string; // Merchant logo. logo?: ImageDataUrl; // Public key of the merchant/instance, in Crockford Base32 encoding. merchant_pub: EddsaPublicKey; // The merchant's physical address (to be put into contracts). address: Location; // The jurisdiction under which the merchant conducts its business // (to be put into contracts). jurisdiction: Location; // Use STEFAN curves to determine default fees? // If false, no fees are allowed by default. // Can always be overridden by the frontend on a per-order basis. use_stefan: boolean; // If the frontend does NOT specify an execution date, how long should // we tell the exchange to wait to aggregate transactions before // executing the wire transfer? This delay is added to the current // time when we generate the advisory execution time for the exchange. default_wire_transfer_delay: RelativeTime; // If the frontend does NOT specify a payment deadline, how long should // offers we make be valid by default? default_pay_delay: RelativeTime; // Authentication configuration. // Does not contain the token when token auth is configured. auth: { method: "external" | "token"; }; } Deleting instances ------------------ .. http:delete:: /management/instances/$INSTANCE .. http:delete:: [/instances/$INSTANCE]/private This request will be used to delete (permanently disable) or purge merchant instance in the backend. Purging will delete all offers and payments associated with the instance, while disabling (the default) only deletes the private key and makes the instance unusable for new orders or payments. For deletion, the authentication credentials must match the instance that is being deleted or the ``default`` instance, depending on the access path used. **Request:** :query purge: *Optional*. If set to YES, the instance will be fully deleted. Otherwise only the private key would be deleted. **Response** :http:statuscode:`204 No content`: The backend has successfully removed the instance. The body is empty. :http:statuscode:`401 Unauthorized`: The request is unauthorized. Note that for already deleted instances, the request must be authorized using the ``default`` instance. :http:statuscode:`404 Not found`: The instance is unknown to the backend. :http:statuscode:`409 Conflict`: The instance cannot be deleted because it has pending offers, or the instance cannot be purged because it has successfully processed payments that have not passed the ``TAX_RECORD_EXPIRATION`` time. The latter case only applies if ``purge`` was set. KYC status checks ----------------- .. note:: This is a draft API that is not yet implemented. .. http:GET:: /management/instances/$INSTANCE/kyc .. http:GET:: /instances/$INSTANCE/private/kyc Check KYC status of a particular payment target. Prompts the exchange to inquire with the bank as to the KYC status of the respective account and returns the result. **Request:** :query h_wire=H_WIRE: *Optional*. If specified, the KYC check should return the KYC status only for this wire account. Otherwise, for all wire accounts. :query exchange_url=URL: *Optional*. If specified, the KYC check should return the KYC status only for the given exchange. Otherwise, for all exchanges we interacted with. :query timeout_ms=NUMBER: *Optional.* If specified, the merchant will wait up to ``timeout_ms`` milliseconds for the exchanges to confirm completion of the KYC process(es). **Response:** If different exchanges cause different errors when processing the request, the largest HTTP status code that is applicable is returned. :http:statuscode:`202 Accepted`: The user should be redirected to the provided locations to perform the required KYC checks to open an account. Afterwards, the request should be repeated. The response will be an `AccountKycRedirects` object. :http:statuscode:`204 No content`: All KYC operations queried have succeeded. This may change in the future, but there is no need to check again soon. It is suggested to check again at a frequency of hours or days. :http:statuscode:`502 Bad gateway`: We failed to obtain a response from an exchange (about the KYC status). The response will be an `AccountKycRedirects` object. :http:statuscode:`503 Service unavailable`: We do not know our KYC status as the exchange has not yet returned the necessary details. This is not an actual failure: this is expected to happen if for example a deposit was not yet aggregated by the exchange and thus the exchange has not yet initiated the KYC process. The client should simply try again later. It is suggested to check again at a frequency of minutes to hours. :http:statuscode:`504 Gateway Timeout`: The merchant did not receive a confirmation from an exchange within the specified time period. Used when long-polling for the result. **Details:** .. ts:def:: AccountKycRedirects interface AccountKycRedirects { // Array of pending KYCs. pending_kycs: MerchantAccountKycRedirect[]; // Array of exchanges with no reply. timeout_kycs: ExchangeKycTimeout[]; } .. ts:def:: MerchantAccountKycRedirect interface MerchantAccountKycRedirect { // URL that the user should open in a browser to // proceed with the KYC process (as returned // by the exchange's ``/kyc-check/`` endpoint). // Optional, missing if the account is blocked // due to AML and not due to KYC. kyc_url?: string; // AML status of the account. aml_status: Integer; // Base URL of the exchange this is about. exchange_url: string; // Our bank wire account this is about. payto_uri: string; } .. ts:def:: ExchangeKycTimeout interface ExchangeKycTimeout { // Base URL of the exchange this is about. exchange_url: string; // Numeric `error code ` indicating errors the exchange // returned, or TALER_EC_INVALID for none. exchange_code: number; // HTTP status code returned by the exchange when we asked for // information about the KYC status. // 0 if there was no response at all. exchange_http_status: number; } ------------- Bank Accounts ------------- One or more bank accounts must be associated with an instance so that the instance can receive payments. Payments may be made into any of the active bank accounts of an instance. .. http:post:: [/instances/$INSTANCE]/private/accounts This is used to add an account to an instance. **Request:** The request must have an `AccountAddDetails` body. **Response:** :http:statuscode:`200 Ok`: Adding the account was successful, we return the salt selected by the backend and the resulting wire hash in an `AccountAddResponse`. :http:statuscode:`404 Not found`: The merchant instance is unknown or it is not in our data. :http:statuscode:`409 Conflict`: The provided information is inconsistent with the current state of the instance. Usually this means we already have this account, but with conflicting credit facade information. Inactive accounts can be reactivated using this method even if the credit facade information differs from the previous state. .. ts:def:: AccountAddDetails interface AccountAddDetails { // payto:// URI of the account. payto_uri: string; // URL from where the merchant can download information // about incoming wire transfers to this account. credit_facade_url?: string; // Credentials to use when accessing the credit facade. // Never returned on a GET (as this may be somewhat // sensitive data). Can be set in POST // or PATCH requests to update (or delete) credentials. // To really delete credentials, set them to the type: "none". credit_facade_credentials?: FacadeCredentials; } .. ts:def:: FacadeCredentials type FacadeCredentials = | NoFacadeCredentials | BasicAuthFacadeCredentials; .. ts:def:: NoFacadeCredentials interface NoFacadeCredentials { type: "none"; }; .. ts:def:: BasicAuthFacadeCredentials interface BasicAuthFacadeCredentials { type: "basic"; // Username to use to authenticate username: string; // Password to use to authenticate password: string; }; .. ts:def:: AccountAddResponse interface AccountAddResponse { // Hash over the wire details (including over the salt). h_wire: HashCode; // Salt used to compute h_wire. salt: HashCode; } .. http:patch:: [/instances/$INSTANCE]/private/accounts/$H_WIRE This is used to update a bank account. **Request:** The request must be a `AccountPatchDetails`. **Response:** :http:statuscode:`204 No content`: The template has successfully modified. :http:statuscode:`404 Not found`: The template(ID) is unknown to the backend. .. ts:def:: AccountPatchDetails interface AccountPatchDetails { // URL from where the merchant can download information // about incoming wire transfers to this account. credit_facade_url?: string; // Credentials to use when accessing the credit facade. // Never returned on a GET (as this may be somewhat // sensitive data). Can be set in POST // or PATCH requests to update (or delete) credentials. // To really delete credentials, set them to the type: "none". // If the argument is omitted, the old credentials // are simply preserved. credit_facade_credentials?: FacadeCredentials; } .. http:get:: [/instances/$INSTANCE]/private/accounts This is used to return the list of all the bank accounts of an instance. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned all the accounts. Returns a `AccountsSummaryResponse`. :http:statuscode:`404 Not found`: The backend has does not know about the instance. .. ts:def:: AccountsSummaryResponse interface AccountsSummaryResponse { // List of accounts that are known for the instance. accounts: BankAccountEntry[]; } .. ts:def:: BankAccountEntry interface BankAccountEntry { // payto:// URI of the account. payto_uri: string; // Hash over the wire details (including over the salt). h_wire: HashCode; // Salt used to compute h_wire. salt: HashCode; // URL from where the merchant can download information // about incoming wire transfers to this account. credit_facade_url?: string; // true if this account is active, // false if it is historic. active: boolean; } .. http:get:: [/instances/$INSTANCE]/private/accounts/$H_WIRE This is used to obtain detailed information about a specific bank account. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the detailed information about a specific bank account. Returns a `BankAccountEntry`. :http:statuscode:`404 Not found`: The bank account or instance is unknown to the backend. .. http:delete:: [/instances/$INSTANCE]/private/accounts/$H_WIRE **Response:** :http:statuscode:`204 No content`: The backend has successfully deactivated the account. :http:statuscode:`404 Not found`: The backend does not know the instance or the account. -------------------- Inventory management -------------------- .. _inventory: Inventory management is an *optional* backend feature that can be used to manage limited stocks of products and to auto-complete product descriptions in contracts (such that the frontends have to do less work). You can use the Taler merchant backend to process payments *without* using its inventory management. Adding products to the inventory -------------------------------- .. http:post:: [/instances/$INSTANCE]/private/products This is used to add a product to the inventory. **Request:** The request must be a `ProductAddDetail`. **Response:** :http:statuscode:`204 No content`: The backend has successfully expanded the inventory. :http:statuscode:`409 Conflict`: The backend already knows a product with this product ID, but with different details. .. ts:def:: ProductAddDetail interface ProductAddDetail { // Product ID to use. product_id: string; // Human-readable product description. description: string; // Map from IETF BCP 47 language tags to localized descriptions. description_i18n?: { [lang_tag: string]: string }; // Unit in which the product is measured (liters, kilograms, packages, etc.). unit: string; // The price for one ``unit`` of the product. Zero is used // to imply that this product is not sold separately, or // that the price is not fixed, and must be supplied by the // front-end. If non-zero, this price MUST include applicable // taxes. price: Amount; // An optional base64-encoded product image. image?: ImageDataUrl; // A list of taxes paid by the merchant for one unit of this product. taxes?: Tax[]; // Number of units of the product in stock in sum in total, // including all existing sales ever. Given in product-specific // units. // A value of -1 indicates "infinite" (i.e. for "electronic" books). total_stock: Integer; // Identifies where the product is in stock. address?: Location; // Identifies when we expect the next restocking to happen. next_restock?: Timestamp; // Minimum age buyer must have (in years). Default is 0. minimum_age?: Integer; } .. http:patch:: [/instances/$INSTANCE]/private/products/$PRODUCT_ID This is used to update product details in the inventory. Note that the ``total_stock`` and ``total_lost`` numbers MUST be greater or equal than previous values (this design ensures idempotency). In case stocks were lost but not sold, increment the ``total_lost`` number. All fields in the request are optional, those that are not given are simply preserved (not modified). Note that the ``description_i18n`` and ``taxes`` can only be modified in bulk: if it is given, all translations must be provided, not only those that changed. ``never`` should be used for the ``next_restock`` timestamp to indicate no intention/possibility of restocking, while a time of zero is used to indicate "unknown". **Request:** The request must be a `ProductPatchDetail`. **Response:** :http:statuscode:`204 No content`: The backend has successfully expanded the inventory. :http:statuscode:`404 Not found`: The product (ID) is unknown to the backend. :http:statuscode:`409 Conflict`: The provided information is inconsistent with the current state of the inventory. .. ts:def:: ProductPatchDetail interface ProductPatchDetail { // Human-readable product description. description: string; // Map from IETF BCP 47 language tags to localized descriptions. description_i18n?: { [lang_tag: string]: string }; // Unit in which the product is measured (liters, kilograms, packages, etc.). unit: string; // The price for one ``unit`` of the product. Zero is used // to imply that this product is not sold separately, or // that the price is not fixed, and must be supplied by the // front-end. If non-zero, this price MUST include applicable // taxes. price: Amount; // An optional base64-encoded product image. image?: ImageDataUrl; // A list of taxes paid by the merchant for one unit of this product. taxes?: Tax[]; // Number of units of the product in stock in sum in total, // including all existing sales ever. Given in product-specific // units. // A value of -1 indicates "infinite" (i.e. for "electronic" books). total_stock: Integer; // Number of units of the product that were lost (spoiled, stolen, etc.). total_lost?: Integer; // Identifies where the product is in stock. address?: Location; // Identifies when we expect the next restocking to happen. next_restock?: Timestamp; // Minimum age buyer must have (in years). Default is 0. minimum_age?: Integer; } Inspecting inventory -------------------- .. http:get:: [/instances/$INSTANCE]/private/products This is used to return the list of all items in the inventory. **Request:** :query limit: *Optional*. At most return the given number of results. Negative for descending by row ID, positive for ascending by row ID. Default is ``20``. Since protocol **v12**. :query offset: *Optional*. Starting ``product_serial_id`` for an iteration. Since protocol **v12**. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the inventory. Returns a `InventorySummaryResponse`. :http:statuscode:`404 Not found`: The backend has does not know about the instance. .. ts:def:: InventorySummaryResponse interface InventorySummaryResponse { // List of products that are present in the inventory. products: InventoryEntry[]; } The `InventoryEntry` object describes an item in the inventory. It has the following structure: .. ts:def:: InventoryEntry interface InventoryEntry { // Product identifier, as found in the product. product_id: string; // ``product_serial_id`` of the product in the database. product_serial: Integer; } .. http:get:: [/instances/$INSTANCE]/private/products/$PRODUCT_ID This is used to obtain detailed information about a product in the inventory. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the inventory. Returns a `ProductDetail`. :http:statuscode:`404 Not found`: The product (ID) is unknown to the backend. .. ts:def:: ProductDetail interface ProductDetail { // Human-readable product description. description: string; // Map from IETF BCP 47 language tags to localized descriptions. description_i18n: { [lang_tag: string]: string }; // Unit in which the product is measured (liters, kilograms, packages, etc.). unit: string; // The price for one ``unit`` of the product. Zero is used // to imply that this product is not sold separately, or // that the price is not fixed, and must be supplied by the // front-end. If non-zero, this price MUST include applicable // taxes. price: Amount; // An optional base64-encoded product image. image: ImageDataUrl; // A list of taxes paid by the merchant for one unit of this product. taxes: Tax[]; // Number of units of the product in stock in sum in total, // including all existing sales ever. Given in product-specific // units. // A value of -1 indicates "infinite" (i.e. for "electronic" books). total_stock: Integer; // Number of units of the product that have already been sold. total_sold: Integer; // Number of units of the product that were lost (spoiled, stolen, etc.). total_lost: Integer; // Identifies where the product is in stock. address: Location; // Identifies when we expect the next restocking to happen. next_restock?: Timestamp; // Minimum age buyer must have (in years). minimum_age?: Integer; } Reserving inventory ------------------- .. http:post:: [/instances/$INSTANCE]/private/products/$PRODUCT_ID/lock This is used to lock a certain quantity of the product for a limited duration while the customer assembles a complete order. Note that frontends do not have to "unlock", they may rely on the timeout as given in the ``duration`` field. Re-posting a lock with a different ``duration`` or ``quantity`` updates the existing lock for the same UUID and does not result in a conflict. Unlocking by using a ``quantity`` of zero is optional but recommended if customers remove products from the shopping cart. Note that actually POSTing to ``/orders`` with set ``inventory_products`` and using ``lock_uuids`` will **transition** the lock to the newly created order (which may have a different ``duration`` and ``quantity`` than what was requested in the lock operation). If an order is for fewer items than originally locked, the difference is automatically unlocked. **Request:** The request must be a `LockRequest`. **Response:** :http:statuscode:`204 No content`: The backend has successfully locked (or unlocked) the requested ``quantity``. :http:statuscode:`404 Not found`: The backend has does not know this product. :http:statuscode:`410 Gone`: The backend does not have enough of product in stock. .. ts:def:: LockRequest interface LockRequest { // UUID that identifies the frontend performing the lock // Must be unique for the lifetime of the lock. lock_uuid: string; // How long does the frontend intend to hold the lock? duration: RelativeTime; // How many units should be locked? quantity: Integer; } .. note:: The ``GNUNET_CRYPTO_random_timeflake()`` C API can be used to generate such timeflakes for clients written in C. Removing products from inventory -------------------------------- .. http:delete:: [/instances/$INSTANCE]/private/products/$PRODUCT_ID Delete information about a product. Fails if the product is locked by anyone. **Response:** :http:statuscode:`204 No content`: The backend has successfully deleted the product. :http:statuscode:`404 Not found`: The backend does not know the instance or the product. :http:statuscode:`409 Conflict`: The backend refuses to delete the product because it is locked. ------------------ Payment processing ------------------ To process Taler payments, a merchant must first set up an order with the merchant backend. The order is then claimed by a wallet, and paid by the wallet. The merchant can check the payment status of the order. Once the order is paid, the merchant may (for a limited time) grant refunds on the order. Creating orders --------------- .. _post-order: .. http:post:: [/instances/$INSTANCE]/private/orders Create a new order that a customer can pay for. This request is **not** idempotent unless an ``order_id`` is explicitly specified. However, while repeating without an ``order_id`` will create another order, that is generally pretty harmless (as long as only one of the orders is returned to the wallet). .. note:: This endpoint does not return a URL to redirect your user to confirm the payment. In order to get this URL use :http:get:`[/instances/$INSTANCE]/orders/$ORDER_ID`. The API is structured this way since the payment redirect URL is not unique for every order, there might be varying parameters such as the session id. **Request:** The request must be a `PostOrderRequest`. **Response:** :http:statuscode:`200 OK`: The backend has successfully created the proposal. The response is a :ts:type:`PostOrderResponse`. :http:statuscode:`404 Not found`: Possible reasons are: (1) The order given used products from the inventory, but those were not found in the inventory. (2) The merchant instance is unknown (including possibly the instance being not configured for new orders). (3) The wire method specified is not supported by the backend. (4) An OTP device ID was specified and is unknown. Details in the error code. NOTE: currently the client has no good way to find out which product is not in the inventory, we MAY want to specify that in the reply. :http:statuscode:`409 Conflict`: A different proposal already exists under the specified order ID, or the requested currency is not supported by this backend. Details in the error code. :http:statuscode:`410 Gone`: The order given used products from the inventory that are out of stock. The response is a :ts:type:`OutOfStockResponse`. .. ts:def:: PostOrderRequest interface PostOrderRequest { // The order must at least contain the minimal // order detail, but can override all. order: Order; // If set, the backend will then set the refund deadline to the current // time plus the specified delay. If it's not set, refunds will not be // possible. refund_delay?: RelativeTime; // Specifies the payment target preferred by the client. Can be used // to select among the various (active) wire methods supported by the instance. payment_target?: string; // The session for which the payment is made (or replayed). // Only set for session-based payments. // Since protocol **v6**. session_id?: string; // Specifies that some products are to be included in the // order from the inventory. For these inventory management // is performed (so the products must be in stock) and // details are completed from the product data of the backend. inventory_products?: MinimalInventoryProduct[]; // Specifies a lock identifier that was used to // lock a product in the inventory. Only useful if // ``inventory_products`` is set. Used in case a frontend // reserved quantities of the individual products while // the shopping cart was being built. Multiple UUIDs can // be used in case different UUIDs were used for different // products (i.e. in case the user started with multiple // shopping sessions that were combined during checkout). lock_uuids?: string[]; // Should a token for claiming the order be generated? // False can make sense if the ORDER_ID is sufficiently // high entropy to prevent adversarial claims (like it is // if the backend auto-generates one). Default is 'true'. // Note: This is NOT related to tokens used for subscriptins or refunds. create_token?: boolean; // OTP device ID to associate with the order. // This parameter is optional. otp_id?: string; } The `Order` object represents the starting point for new `ContractTerms`. After validating and sanatizing all inputs, the merchant backend will add additional information to the order and create a new `ContractTerms` object that will be stored in the database. .. ts:def:: Order interface Order { // Total price for the transaction. // The exchange will subtract deposit fees from that amount // before transferring it to the merchant. amount: Amount; // Human-readable description of the whole purchase. summary: string; // Map from IETF BCP 47 language tags to localized summaries. summary_i18n?: { [lang_tag: string]: string }; // Unique, free-form identifier for the order. // Must be unique within a merchant instance. // For merchants that do not store proposals in their DB // before the customer paid for them, the ``order_id`` can be used // by the frontend to restore a proposal from the information // encoded in it (such as a short product identifier and timestamp). order_id?: string; // List of contract choices that the customer can select from. // @since protocol **vSUBSCRIBE** choices?: OrderChoice[]; // URL where the same contract could be ordered again (if // available). Returned also at the public order endpoint // for people other than the actual buyer (hence public, // in case order IDs are guessable). public_reorder_url?: string; // See documentation of ``fulfillment_url`` field in `ContractTerms`. // Either fulfillment_url or fulfillment_message must be specified. // When creating an order, the fulfillment URL can // contain ``${ORDER_ID}`` which will be substituted with the // order ID of the newly created order. fulfillment_url?: string; // See documentation of ``fulfillment_message`` in `ContractTerms`. // Either ``fulfillment_url`` or ``fulfillment_message`` must be specified. fulfillment_message?: string; // Map from IETF BCP 47 language tags to localized fulfillment // messages. fulfillment_message_i18n?: { [lang_tag: string]: string }; // Maximum total deposit fee accepted by the merchant for this contract. // Overrides defaults of the merchant instance. max_fee?: Amount; // List of products that are part of the purchase. products?: Product[]; // Time when this contract was generated. If null, defaults to current // time of merchant backend. timestamp?: Timestamp; // After this deadline has passed, no refunds will be accepted. // Overrides deadline calculated from ``refund_delay`` in // ``PostOrderRequest``. refund_deadline?: Timestamp; // After this deadline, the merchant won't accept payments for the contract. // Overrides deadline calculated from default pay delay configured in // merchant backend. pay_deadline?: Timestamp; // Transfer deadline for the exchange. Must be in the deposit permissions // of coins used to pay for this order. // Overrides deadline calculated from default wire transfer delay // configured in merchant backend. Must be after refund deadline. wire_transfer_deadline?: Timestamp; // Base URL of the (public!) merchant backend API. // Must be an absolute URL that ends with a slash. // Defaults to the base URL this request was made to. merchant_base_url?: string; // Delivery location for (all!) products. delivery_location?: Location; // Time indicating when the order should be delivered. // May be overwritten by individual products. // Must be in the future. delivery_date?: Timestamp; // See documentation of ``auto_refund`` in ``ContractTerms``. // Specifies for how long the wallet should try to get an // automatic refund for the purchase. auto_refund?: RelativeTime; // Extra data that is only interpreted by the merchant frontend. // Useful when the merchant needs to store extra information on a // contract without storing it separately in their database. // Must really be an Object (not a string, integer, float or array). extra?: Object; } The `OrderChoice` object describes a possible choice within an order. The choice is done by the wallet and consists of in- and outputs. In the example of buying an article, the merchant could present the customer with the choice to use a valid subscription token or pay using a gift voucher. Available since protocol **vSUBSCRIBE**. .. ts:def:: OrderChoice interface OrderChoice { // Inputs that must be provided by the customer, if this choice is selected. inputs: OrderInput[]; // Outputs provided by the merchant, if this choice is selected. outputs: OrderOutput[]; } .. ts:def:: OrderInput // For now, only token inputs are supported. type OrderInput = OrderInputToken; .. ts:def:: OrderInputToken interface OrderInputToken { // Token input. type: "token"; // Token family slug as configured in the merchant backend. Slug is unique // across all configured tokens of a merchant. token_family_slug: string; // Start of the validity period of the token. Based on this, the merchant // will select the relevant signing key. This value is rounded down // according to the configured rounding duration in the token family. valid_after: Timestamp; // How many units of the input are required. // Defaults to 1 if not specified. Output with count == 0 are ignored by // the merchant backend. count?: Integer; } .. ts:def:: OrderOutput type OrderOutput = OrderOutputToken | OrderOutputTaxReceipt; .. ts:def:: OrderOutputToken interface OrderOutputToken { // Token output. type: "token"; // Token family slug as configured in the merchant backend. Slug is unique // across all configured tokens of a merchant. token_family_slug: string; // Start of the validity period of the token. Based on this, the merchant // will select the relevant signing key. This value is rounded down // according to the configured rounding duration in the token family. valid_after: Timestamp; // How many units of the output are issued by the merchant. // Defaults to 1 if not specified. Output with count == 0 are ignored by // the merchant backend. count?: Integer; } .. ts:def:: OrderOutputTaxReceipt interface OrderOutputTaxReceipt { // Tax receipt output. type: "tax-receipt"; // Base URL of the donation authority that will // issue the tax receipt. donau_url: string; } The following `MinimalInventoryProduct` can be provided if the parts of the order are inventory-based, that is if the `PostOrderRequest` uses ``inventory_products``. For such products, which must be in the backend's inventory, the backend can automatically fill in the amount and other details about the product that are known to it from its ``products`` table. Note that the ``inventory_products`` will be appended to the list of ``products`` that the frontend already put into the ``order``. So if the frontend can sell additional non-inventory products together with ``inventory_products``. Note that the backend will NOT update the ``amount`` of the ``order``, so the frontend must already have calculated the total price --- including the ``inventory_products``. .. ts:def:: MinimalInventoryProduct // Note that if the frontend does give details beyond these, // it will override those details (including price or taxes) // that the backend would otherwise fill in via the inventory. interface MinimalInventoryProduct { // Which product is requested (here mandatory!). product_id: string; // How many units of the product are requested. quantity: Integer; } .. ts:def:: PostOrderResponse interface PostOrderResponse { // Order ID of the response that was just created. order_id: string; // Token that authorizes the wallet to claim the order. // Provided only if "create_token" was set to 'true' // in the request. token?: ClaimToken; } .. ts:def:: OutOfStockResponse interface OutOfStockResponse { // Product ID of an out-of-stock item. product_id: string; // Requested quantity. requested_quantity: Integer; // Available quantity (must be below ``requested_quantity``). available_quantity: Integer; // When do we expect the product to be again in stock? // Optional, not given if unknown. restock_expected?: Timestamp; } Inspecting orders ----------------- .. http:get:: [/instances/$INSTANCE]/private/orders Returns known orders up to some point in the past. **Request:** :query paid: *Optional*. If set to yes, only return paid orders, if no only unpaid orders. Do not give (or use "all") to see all orders regardless of payment status. :query refunded: *Optional*. If set to yes, only return refunded orders, if no only unrefunded orders. Do not give (or use "all") to see all orders regardless of refund status. :query wired: *Optional*. If set to yes, only return wired orders, if no only orders with missing wire transfers. Do not give (or use "all") to see all orders regardless of wire transfer status. :query delta: *Optional*. takes value of the form ``N (-N)``, so that at most ``N`` values strictly older (younger) than ``start`` and ``date_s`` are returned. Defaults to ``-20`` to return the last 20 entries (before ``start`` and/or ``date_s``). Deprecated in protocol **v12**. Use *limit* instead. :query limit: *Optional*. At most return the given number of results. Negative for descending by row ID, positive for ascending by row ID. Default is ``20``. Since protocol **v12**. :query date_s: *Optional.* Non-negative date in seconds after the UNIX Epoc, see ``delta`` for its interpretation. If not specified, we default to the oldest or most recent entry, depending on ``delta``. :query start: *Optional*. Row number threshold, see ``delta`` for its interpretation. Defaults to ``INT64_MAX``, namely the biggest row id possible in the database. Deprecated in protocol **v12**. Use *offset* instead. :query offset: *Optional*. Starting ``row_id`` for an iteration. Since protocol **v12**. :query timeout_ms: *Optional*. Timeout in milliseconds to wait for additional orders if the answer would otherwise be negative (long polling). Only useful if delta is positive. Note that the merchant MAY still return a response that contains fewer than ``delta`` orders. :query session_id: *Optional*. Since protocol **v6**. Filters by session ID. :query fulfillment_url: *Optional*. Since protocol **v6**. Filters by fulfillment URL. **Response:** :http:statuscode:`200 OK`: The response is an `OrderHistory`. .. ts:def:: OrderHistory interface OrderHistory { // Timestamp-sorted array of all orders matching the query. // The order of the sorting depends on the sign of ``delta``. orders : OrderHistoryEntry[]; } .. ts:def:: OrderHistoryEntry interface OrderHistoryEntry { // Order ID of the transaction related to this entry. order_id: string; // Row ID of the order in the database. row_id: number; // When the order was created. timestamp: Timestamp; // The amount of money the order is for. amount: Amount; // The summary of the order. summary: string; // Whether some part of the order is refundable, // that is the refund deadline has not yet expired // and the total amount refunded so far is below // the value of the original transaction. refundable: boolean; // Whether the order has been paid or not. paid: boolean; } .. http:get:: [/instances/$INSTANCE]/private/orders/$ORDER_ID Merchant checks the payment status of an order. If the order exists but is not paid and not claimed yet, the response provides a redirect URL. When the user goes to this URL, they will be prompted for payment. Differs from the ``public`` API both in terms of what information is returned and in that the wallet must provide the contract hash to authenticate, while for this API we assume that the merchant is authenticated (as the endpoint is not ``public``). **Request:** :query session_id: *Optional*. Session ID that the payment must be bound to. If not specified, the payment is not session-bound. :query transfer: Deprecated in protocol **V6**. *Optional*. If set to "YES", try to obtain the wire transfer status for this order from the exchange. Otherwise, the wire transfer status MAY be returned if it is available. :query timeout_ms: *Optional*. Timeout in milliseconds to wait for a payment if the answer would otherwise be negative (long polling). :query allow_refunded_for_repurchase: *Optional*. Since protocol **v9** refunded orders are only returned under "already_paid_order_id" if this flag is set explicitly to "YES". **Response:** :http:statuscode:`200 OK`: Returns a `MerchantOrderStatusResponse`, whose format can differ based on the status of the payment. :http:statuscode:`404 Not found`: The order or instance is unknown to the backend. :http:statuscode:`502 Bad gateway`: We failed to obtain a response from the exchange (about the wire transfer status). :http:statuscode:`504 Gateway timeout`: The merchant's interaction with the exchange took too long. The client might want to try again later. .. ts:def:: MerchantOrderStatusResponse type MerchantOrderStatusResponse = CheckPaymentPaidResponse | CheckPaymentClaimedResponse | CheckPaymentUnpaidResponse; .. ts:def:: CheckPaymentPaidResponse interface CheckPaymentPaidResponse { // The customer paid for this contract. order_status: "paid"; // Was the payment refunded (even partially)? refunded: boolean; // True if there are any approved refunds that the wallet has // not yet obtained. refund_pending: boolean; // Did the exchange wire us the funds? wired: boolean; // Total amount the exchange deposited into our bank account // for this contract, excluding fees. deposit_total: Amount; // Numeric `error code ` indicating errors the exchange // encountered tracking the wire transfer for this purchase (before // we even got to specific coin issues). // 0 if there were no issues. exchange_code: number; // HTTP status code returned by the exchange when we asked for // information to track the wire transfer for this purchase. // 0 if there were no issues. exchange_http_status: number; // Total amount that was refunded, 0 if refunded is false. refund_amount: Amount; // Contract terms. contract_terms: ContractTerms; // Index of the selected choice within the ``choices`` array of // ``contract terms``. // @since protocol **vSUBSCRIBE** choice_index?: Integer; // If the order is paid, set to the last time when a payment // was made to pay for this order. Since **v14**. last_payment: Timestamp; // The wire transfer status from the exchange for this order if // available, otherwise empty array. wire_details: TransactionWireTransfer[]; // Reports about trouble obtaining wire transfer details, // empty array if no trouble were encountered. // @deprecated in protocol **v6**. wire_reports: TransactionWireReport[]; // The refund details for this order. One entry per // refunded coin; empty array if there are no refunds. refund_details: RefundDetails[]; // Status URL, can be used as a redirect target for the browser // to show the order QR code / trigger the wallet. order_status_url: string; } .. ts:def:: CheckPaymentClaimedResponse interface CheckPaymentClaimedResponse { // A wallet claimed the order, but did not yet pay for the contract. order_status: "claimed"; // Contract terms. contract_terms: ContractTerms; } .. ts:def:: CheckPaymentUnpaidResponse interface CheckPaymentUnpaidResponse { // The order was neither claimed nor paid. order_status: "unpaid"; // URI that the wallet must process to complete the payment. taler_pay_uri: string; // when was the order created creation_time: Timestamp; // Order summary text. summary: string; // Total amount of the order (to be paid by the customer). total_amount: Amount; // Alternative order ID which was paid for already in the same session. // Only given if the same product was purchased before in the same session. already_paid_order_id?: string; // Fulfillment URL of an already paid order. Only given if under this // session an already paid order with a fulfillment URL exists. already_paid_fulfillment_url?: string; // Status URL, can be used as a redirect target for the browser // to show the order QR code / trigger the wallet. order_status_url: string; // We do we NOT return the contract terms here because they may not // exist in case the wallet did not yet claim them. } .. ts:def:: RefundDetails interface RefundDetails { // Reason given for the refund. reason: string; // Set to true if a refund is still available for the wallet for this payment. pending: boolean; // When was the refund approved. timestamp: Timestamp; // Total amount that was refunded (minus a refund fee). amount: Amount; } .. ts:def:: TransactionWireTransfer interface TransactionWireTransfer { // Responsible exchange. exchange_url: string; // 32-byte wire transfer identifier. wtid: Base32; // Execution time of the wire transfer. execution_time: Timestamp; // Total amount that has been wire transferred // to the merchant. amount: Amount; // Was this transfer confirmed by the merchant via the // POST /transfers API, or is it merely claimed by the exchange? confirmed: boolean; } .. ts:def:: TransactionWireReport interface TransactionWireReport { // Numerical `error code `. code: number; // Human-readable error description. hint: string; // Numerical `error code ` from the exchange. exchange_code: number; // HTTP status code received from the exchange. exchange_http_status: number; // Public key of the coin for which we got the exchange error. coin_pub: CoinPublicKey; } .. _private-order-data-cleanup: Private order data cleanup -------------------------- Some orders may contain sensitive information that the merchant may not want to retain after fulfillment, such as the customer's shipping address. By initially labeling these order components as forgettable, the merchant can later tell the backend to forget those details (without changing the hash of the contract!) to minimize risks from information leakage. .. http:patch:: [/instances/$INSTANCE]/private/orders/$ORDER_ID/forget Forget fields in an order's contract terms that the merchant no longer needs. **Request:** The request must be a `forget request `. The fields specified must have been marked as forgettable when the contract was created. Fields in the request that are not in the `contract terms ` are ignored. A valid JSON path is defined as a string beginning with ``$.`` that follows the dot notation: ``$.wire_fee``, for example. The ``$`` represents the `contract terms ` object, and an identifier following a ``.`` represents the field of that identifier belonging to the object preceding the dot. Arrays can be indexed by an non-negative integer within brackets: ``$.products[1]``. An asterisk ``*`` can be used to index an array as a wildcard, which expands the path into a list of paths containing one path for each valid array index: ``$.products[*].description``. For a path to be valid, it must end with a reference to a field of an object (it cannot end with an array index or wildcard). **Response:** :http:statuscode:`200 OK`: The merchant deleted the specified fields from the contract of order $ORDER_ID. :http:statuscode:`204 No content`: The merchant had already deleted the specified fields from the contract of order $ORDER_ID. :http:statuscode:`400 Bad request`: The request is malformed or one of the paths is invalid. :http:statuscode:`404 Not found`: The merchant backend could not find the order or the instance and thus cannot process the forget request. :http:statuscode:`409 Conflict`: The request includes a field that was not marked as forgettable, so the merchant cannot delete that field. .. ts:def:: ForgetRequest interface ForgetRequest { // Array of valid JSON paths to forgettable fields in the order's // contract terms. fields: string[]; } .. http:delete:: [/instances/$INSTANCE]/private/orders/$ORDER_ID Delete information about an order. Fails if the order was paid in the last 10 years (or whatever ``TAX_RECORD_EXPIRATION`` is set to) or was claimed but is unpaid and thus still a valid offer. **Response:** :http:statuscode:`204 No content`: The backend has successfully deleted the order. :http:statuscode:`404 Not found`: The backend does not know the instance or the order. :http:statuscode:`409 Conflict`: The backend refuses to delete the order. .. _merchant_refund: -------------- Giving Refunds -------------- .. http:post:: [/instances/$INSTANCE]/private/orders/$ORDER_ID/refund Increase the refund amount associated with a given order. The user should be redirected to the ``taler_refund_uri`` to trigger refund processing in the wallet. **Request:** The request body is a `RefundRequest` object. **Response:** :http:statuscode:`200 OK`: The refund amount has been increased, the backend responds with a `MerchantRefundResponse`. :http:statuscode:`403 Forbidden`: For the given order, the refund delay was zero and thus refunds are categorically not allowed. :http:statuscode:`404 Not found`: The order is unknown to the merchant. :http:statuscode:`410 Gone`: It is too late for aborting, the exchange may have already wired the funds to the merchant. :http:statuscode:`409 Conflict`: The refund amount exceeds the amount originally paid. .. ts:def:: RefundRequest interface RefundRequest { // Amount to be refunded. refund: Amount; // Human-readable refund justification. reason: string; } .. ts:def:: MerchantRefundResponse interface MerchantRefundResponse { // URL (handled by the backend) that the wallet should access to // trigger refund processing. // taler://refund/... taler_refund_uri: string; // Contract hash that a client may need to authenticate an // HTTP request to obtain the above URI in a wallet-friendly way. h_contract: HashCode; } ----------------------- Tracking Wire Transfers ----------------------- This API is used by merchants that want to track the payments from the exchange to be sure that they have been paid on time. By telling the merchant backend about all incoming wire transfers, the backend can detect if an exchange failed to perform a wire transfer that was due. Informing the backend about incoming wire transfers --------------------------------------------------- .. http:post:: [/instances/$INSTANCE]/private/transfers Inform the backend over an incoming wire transfer. The backend should inquire about the details with the exchange and mark the respective orders as wired. Note that the request will fail if the WTID is not unique (which should be guaranteed by a correct exchange). This request is idempotent and should also be used to merely re-fetch the transfer information from the merchant's database (assuming we got a non-error response from the exchange before). **Request:** The request must provide `transfer information `. **Response:** :http:statuscode:`204 No content`: The wire transfer is now confirmed at the merchant. :http:statuscode:`404 Not found`: The instance or account are unknown to the exchange. :http:statuscode:`409 Conflict`: The wire transfer identifier is already known to us, but for a different amount. **Details:** .. ts:def:: TransferInformation interface TransferInformation { // How much was wired to the merchant (minus fees). credit_amount: Amount; // Raw wire transfer identifier identifying the wire transfer (a base32-encoded value). wtid: WireTransferIdentifierRawP; // Target account that received the wire transfer. payto_uri: string; // Base URL of the exchange that made the wire transfer. exchange_url: string; } Querying known wire transfers ----------------------------- .. http:get:: [/instances/$INSTANCE]/private/transfers Obtain a list of all wire transfers the backend has checked. Note that when filtering by timestamp (using ``before`` and/or ``after``), we use the time reported by the exchange and thus will ONLY return results for which we already have a response from the exchange. This should be virtually all transfers, however it is conceivable that for some transfer the exchange responded with a temporary error (i.e. HTTP status 500+) and then we do not yet have an execution time to filter by. Thus, IF timestamp filters are given, transfers for which we have no response from the exchange yet are automatically excluded. **Request:** :query payto_uri: *Optional*. Filter for transfers to the given bank account (subject and amount MUST NOT be given in the payto URI). :query before: *Optional*. Filter for transfers executed before the given timestamp. :query after: *Optional*. Filter for transfers executed after the given timestamp. :query limit: *Optional*. At most return the given number of results. Negative for descending in execution time, positive for ascending in execution time. Default is ``-20``. :query offset: *Optional*. Starting ``transfer_serial_id`` for an iteration. :query verified: *Optional*. Filter transfers by verification status. **Response:** :http:statuscode:`200 OK`: The body of the response is a `TransferList`. .. ts:def:: TransferList interface TransferList { // List of all the transfers that fit the filter that we know. transfers : TransferDetails[]; } .. ts:def:: TransferDetails interface TransferDetails { // How much was wired to the merchant (minus fees). credit_amount: Amount; // Raw wire transfer identifier identifying the wire transfer (a base32-encoded value). wtid: WireTransferIdentifierRawP; // Target account that received the wire transfer. payto_uri: string; // Base URL of the exchange that made the wire transfer. exchange_url: string; // Serial number identifying the transfer in the merchant backend. // Used for filtering via ``offset``. transfer_serial_id: number; // Time of the execution of the wire transfer by the exchange, according to the exchange // Only provided if we did get an answer from the exchange. execution_time?: Timestamp; // True if we checked the exchange's answer and are happy with it. // False if we have an answer and are unhappy, missing if we // do not have an answer from the exchange. verified?: boolean; // True if the merchant uses the POST /transfers API to confirm // that this wire transfer took place (and it is thus not // something merely claimed by the exchange). confirmed?: boolean; } Deleting wire transfer ---------------------- Deleting a wire transfer can be useful in case of a data entry mistake. In particular, if the exchange base URL was entered badly, deleting the old entry and adding a correct one is a good idea. Note that deleting wire transfers is no longer possible once we got a reply from the exchange. .. http:delete:: [/instances/$INSTANCE]/private/transfers/$TID Here, the TID is the 'transfer_serial_id' of the transfer to delete. **Response:** :http:statuscode:`204 No content`: The transfer was deleted. :http:statuscode:`404 Not found`: The transfer was already unknown. :http:statuscode:`409 Conflict`: The transfer cannot be deleted anymore. ----------- OTP Devices ----------- OTP devices can be used to allow offline merchants to validate that a customer made a payment. .. http:post:: [/instances/$INSTANCE]/private/otp-devices This is used to associate an OTP device with an instance. **Request:** The request must be a `OtpDeviceAddDetails`. **Response:** :http:statuscode:`204 No content`: The creation of the template is successful. :http:statuscode:`404 Not found`: The merchant instance is unknown or it is not in our data. .. ts:def:: OtpDeviceAddDetails interface OtpDeviceAddDetails { // Device ID to use. otp_device_id: string; // Human-readable description for the device. otp_device_description: string; // A key encoded with RFC 3548 Base32. // IMPORTANT: This is not using the typical // Taler base32-crockford encoding. // Instead it uses the RFC 3548 encoding to // be compatible with the TOTP standard. otp_key: string; // Algorithm for computing the POS confirmation. // "NONE" or 0: No algorithm (no pos confirmation will be generated) // "TOTP_WITHOUT_PRICE" or 1: Without amounts (typical OTP device) // "TOTP_WITH_PRICE" or 2: With amounts (special-purpose OTP device) // The "String" variants are supported @since protocol **v7**. otp_algorithm: Integer | string; // Counter for counter-based OTP devices. otp_ctr?: Integer; } .. http:patch:: [/instances/$INSTANCE]/private/otp-devices/$DEVICE_ID This is used to update an OTP device. It is useful when we need to change information in the OTP device or when we have mistake some information. **Request:** The request must be a `OtpDevicePatchDetails`. **Response:** :http:statuscode:`204 No content`: The template has successfully modified. :http:statuscode:`404 Not found`: The template(ID) is unknown to the backend. :http:statuscode:`409 Conflict`: The provided information is inconsistent with the current state of the template. Changes made is the same with another store. .. ts:def:: OtpDevicePatchDetails interface OtpDevicePatchDetails { // Human-readable description for the device. otp_device_description: string; // A key encoded with RFC 3548 Base32. // IMPORTANT: This is not using the typical // Taler base32-crockford encoding. // Instead it uses the RFC 3548 encoding to // be compatible with the TOTP standard. otp_key?: string; // Algorithm for computing the POS confirmation. otp_algorithm: Integer; // Counter for counter-based OTP devices. otp_ctr?: Integer; } .. http:get:: [/instances/$INSTANCE]/private/otp-devices This is used to return the list of all the OTP devices. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned all the templates. Returns a `OtpDeviceSummaryResponse`. :http:statuscode:`404 Not found`: The backend has does not know about the instance. .. ts:def:: OtpDeviceSummaryResponse interface OtpDeviceSummaryResponse { // Array of devices that are present in our backend. otp_devices: OtpDeviceEntry[]; } .. ts:def:: OtpDeviceEntry interface OtpDeviceEntry { // Device identifier. otp_device_id: string; // Human-readable description for the device. device_description: string; } .. http:get:: [/instances/$INSTANCE]/private/otp-devices/$DEVICE_ID This is used to obtain detailed information about a specific OTP device. The client can provide additional inputs in the query to allow the backend to compute and return a sample OTP code. Note that it is not an error if the client provides query arguments that are not being used *or* that are insufficient for the server to compute the ``otp_code``: If the client provides inadequate query parameters, the ``otp_code`` is simply omitted from the response. **Query:** :query faketime=TIMESTAMP: *Optional*. Timestamp in seconds to use when calculating the current OTP code of the device. Since protocol **v10**. :query price=AMOUNT: *Optional*. Price to use when calculating the current OTP code of the device. Since protocol **v10**. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the detailed information about a specific OTP device. Returns a `OtpDeviceDetails`. :http:statuscode:`404 Not found`: The OTP device or instance is unknown to the backend. .. ts:def:: OtpDeviceDetails interface OtpDeviceDetails { // Human-readable description for the device. device_description: string; // Algorithm for computing the POS confirmation. // // Currently, the following numbers are defined: // 0: None // 1: TOTP without price // 2: TOTP with price otp_algorithm: Integer; // Counter for counter-based OTP devices. otp_ctr?: Integer; // Current time for time-based OTP devices. // Will match the ``faketime`` argument of the // query if one was present, otherwise the current // time at the backend. // // Available since protocol **v10**. otp_timestamp: Integer; // Current OTP confirmation string of the device. // Matches exactly the string that would be returned // as part of a payment confirmation for the given // amount and time (so may contain multiple OTP codes). // // If the ``otp_algorithm`` is time-based, the code is // returned for the current time, or for the ``faketime`` // if a TIMESTAMP query argument was provided by the client. // // When using OTP with counters, the counter is **NOT** // increased merely because this endpoint created // an OTP code (this is a GET request, after all!). // // If the ``otp_algorithm`` requires an amount, the // ``amount`` argument must be specified in the // query, otherwise the ``otp_code`` is not // generated. // // This field is *optional* in the response, as it is // only provided if we could compute it based on the // ``otp_algorithm`` and matching client query arguments. // // Available since protocol **v10**. otp_code?: string; } .. http:delete:: [/instances/$INSTANCE]/private/otp-devices/$DEVICE_ID **Response:** :http:statuscode:`204 No content`: The backend has successfully deleted the OTP device. :http:statuscode:`404 Not found`: The backend does not know the instance or the OTP device. --------- Templates --------- The template is a backend feature that is used to allow wallets to create an order. This is useful in cases where a store does not have Internet connectivity or where a Web site wants to enable payments on a purely static Web page (for example to collect donations). In these cases, the GNU Taler wallet can be used to setup an order (and then of course pay for it). The template itself primarily provides order details that cannot be be changed by the customer when the wallet creates the order. The idea is that the user *may* be prompted to enter certain information, such as the amount to be paid, or the order summary (as a reminder to themselves or a message to the store), while the template provides all of the other contract details. The typical user-experience with templatates is that the user first scans a QR code or clicks on a taler://-URI which contains a ``pay-template`` (see `LSD 0006 `__). The URI specifies which values the user should supply, currently either nothing, the amount, the order summary or both. The URI may also specify defaults or partial defaults for those values. After the user has supplied those values, the wallet will use the public template API to create the order, then fetch the order details, and proceed as if it had been given the respective ``pay`` URI in the first place: show the full contract details and allow the user to make a payment. If the user chooses to aborts the payment, the wallet should give the user the opportunity to edit the values and create another order with different values. If the template does not include any values that the user is allowed to edit (so it is basically a fixed contract), the wallet should directly create the order and immediately proceed to the contract acceptance dialog. The business process for the templating API is also pretty simple. First, the private API is used to setup (or edit) the template, providing all of the contract terms that subsequently cannot be changed by the customer/wallet. This template data is then stored under the template ID which can be freely chosen. The SPA should also make it easy for the merchant to convert the template ID into a taler://-URI and/or QR code. Here, the merchant must additionally specify the defaults (if any) for the customer-editable values. Afterwards, the merchant can print out the QR code for display at the store, add a link to the taler://-URI and/or embed the respective QR-code image into their Web page. To receive a payment confirmation, the mechant may choose to configure a webhook in the merchant backend on the ``pay`` action, for example to send an SMS to their mobile phone. For points-of-sale without a mobile phone or Internet connectivity, the TBD mechanism can also be used to confirm payments. Adding templates ---------------- .. http:post:: [/instances/$INSTANCE]/private/templates This is used to create a template. **Request:** The request must be a `TemplateAddDetails`. **Response:** :http:statuscode:`204 No content`: The creation of the template is successful. :http:statuscode:`404 Not found`: The merchant instance is unknown or it is not in our data. .. ts:def:: TemplateAddDetails interface TemplateAddDetails { // Template ID to use. template_id: string; // Human-readable description for the template. template_description: string; // OTP device ID. // This parameter is optional. otp_id?: string; // Fixed contract information for orders created from // this template. template_contract: TemplateContractDetails; // Key-value pairs matching a subset of the // fields from ``template_contract`` that are // user-editable defaults for this template. // Since protocol **v13**. editable_defaults?: Object; // Required currency for payments. Useful if no // amount is specified in the ``template_contract`` // but the user should be required to pay in a // particular currency anyway. Merchant backends // may reject requests if the ``template_contract`` // or ``editable_defaults`` do // specify an amount in a different currency. // This parameter is optional. // Since protocol **v13**. required_currency?: string; } .. ts:def:: TemplateContractDetails interface TemplateContractDetails { // Human-readable summary for the template. summary?: string; // Required currency for payments to the template. // The user may specify any amount, but it must be // in this currency. // This parameter is optional and should not be present // if "amount" is given. currency?: string; // The price is imposed by the merchant and cannot be changed by the customer. // This parameter is optional. amount?: Amount; // Minimum age buyer must have (in years). Default is 0. minimum_age: Integer; // The time the customer need to pay before his order will be deleted. // It is deleted if the customer did not pay and if the duration is over. pay_duration: RelativeTime; } Editing templates ----------------- .. http:patch:: [/instances/$INSTANCE]/private/templates/$TEMPLATE_ID This is used to update a template. It is useful when we need to change information in the template or when we have mistake some information. **Request:** The request must be a `TemplatePatchDetails`. **Response:** :http:statuscode:`204 No content`: The template has successfully modified. :http:statuscode:`404 Not found`: The template(ID) is unknown to the backend. :http:statuscode:`409 Conflict`: The provided information is inconsistent with the current state of the template. Changes made is the same with another store. .. ts:def:: TemplatePatchDetails interface TemplatePatchDetails { // Human-readable description for the template. template_description: string; // OTP device ID. // This parameter is optional. otp_id?: string; // Additional information in a separate template. template_contract: TemplateContractDetails; // Key-value pairs matching a subset of the // fields from ``template_contract`` that are // user-editable defaults for this template. // Since protocol **v13**. editable_defaults?: Object; // Required currency for payments. Useful if no // amount is specified in the ``template_contract`` // but the user should be required to pay in a // particular currency anyway. Merchant backends // may reject requests if the ``template_contract`` // or ``editable_defaults`` do // specify an amount in a different currency. // This parameter is optional. // Since protocol **v13**. required_currency?: string; } Inspecting template ------------------- .. http:get:: [/instances/$INSTANCE]/private/templates This is used to return the list of all the templates. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned all the templates. Returns a `TemplateSummaryResponse`. :http:statuscode:`404 Not found`: The backend has does not know about the instance. .. ts:def:: TemplateSummaryResponse interface TemplateSummaryResponse { // List of templates that are present in our backend. templates: TemplateEntry[]; } The `TemplateEntry` object describes a template. It has the following structure: .. ts:def:: TemplateEntry interface TemplateEntry { // Template identifier, as found in the template. template_id: string; // Human-readable description for the template. template_description: string; } .. http:get:: [/instances/$INSTANCE]/private/templates/$TEMPLATE_ID This is used to obtain detailed information about a specific template. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the detailed information about a specific template. Returns a `TemplateDetails`. :http:statuscode:`404 Not found`: The instance or template(ID) is unknown to the backend. .. ts:def:: TemplateDetails interface TemplateDetails { // Human-readable description for the template. template_description: string; // OTP device ID. // This parameter is optional. otp_id?: string; // Additional information in a separate template. template_contract: TemplateContractDetails; // Key-value pairs matching a subset of the // fields from ``template_contract`` that are // user-editable defaults for this template. // Since protocol **v13**. editable_defaults?: Object; // Required currency for payments. Useful if no // amount is specified in the ``template_contract`` // but the user should be required to pay in a // particular currency anyway. Merchant backends // may reject requests if the ``template_contract`` // or ``editable_defaults`` do // specify an amount in a different currency. // This parameter is optional. // Since protocol **v13**. required_currency?: string; } Removing template ----------------- .. http:delete:: [/instances/$INSTANCE]/private/templates/$TEMPLATE_ID This is used to delete information about a template. If we no longer use it. **Response:** :http:statuscode:`204 No content`: The backend has successfully deleted the template. :http:statuscode:`404 Not found`: The backend does not know the instance or the template. Using template -------------- .. http:get:: [/instances/$INSTANCE]/templates/$TEMPLATE_ID This is used to obtain information about a specific template by wallets before they ask the user to fill in details. This endpoint is available since protocol **v11**. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the detailed information about a specific template. Returns a `WalletTemplateDetails`. :http:statuscode:`404 Not found`: The instance or template(ID) is unknown to the backend. .. ts:def:: WalletTemplateDetails interface WalletTemplateDetails { // Hard-coded information about the contrac terms // for this template. template_contract: TemplateContractDetails; // Key-value pairs matching a subset of the // fields from ``template_contract`` that are // user-editable defaults for this template. // Since protocol **v13**. editable_defaults?: Object; // Required currency for payments. Useful if no // amount is specified in the ``template_contract`` // but the user should be required to pay in a // particular currency anyway. Merchant backends // may reject requests if the ``template_contract`` // or ``editable_defaults`` do // specify an amount in a different currency. // This parameter is optional. // Since protocol **v13**. required_currency?: string; } .. http:post:: [/instances/$INSTANCES]/templates/$TEMPLATE_ID This using template can be modified by everyone and will be used to create order. **Request:** The request must be a `UsingTemplateDetails` and we accept JSON application and URL encoded. **Response:** The response is exactly the same type of response as when creating an order using :ref:`POST /private/orders `. **Details:** .. ts:def:: UsingTemplateDetails interface UsingTemplateDetails { // Summary of the template summary?: string; // The amount entered by the customer. amount?: Amount; } -------- Webhooks -------- The webhook is a backend feature that is used to send a confirmation to the merchant. It can be send with a SMS, email or with another method. It will confirm that the customer paid the merchant. It will show the date and the price the customer paid. Adding webhooks --------------- .. http:post:: [/instances/$INSTANCES]/private/webhooks This is used to create a webhook. **Request:** The request must be a `WebhookAddDetails`. **Response:** :http:statuscode:`204 No content`: The creation of the webhook is successsful. :http:statuscode:`404 Not found`: The merchant instance is unknown or it not in our data. .. ts:def:: WebhookAddDetails interface WebhookAddDetails { // Webhook ID to use. webhook_id: string; // The event of the webhook: why the webhook is used. event_type: string; // URL of the webhook where the customer will be redirected. url: string; // Method used by the webhook http_method: string; // Header template of the webhook header_template?: string; // Body template by the webhook body_template?: string; } Editing webhooks ---------------- .. http:patch:: [/instances/$INSTANCES]/private/webhooks/$WEBHOOK_ID This is used to update a webhook. **Request:** The request must be a `WebhookPatchDetails`. **Response:** :http:statuscode:`204 No content`: The webhook has successfully modified. :http:statuscode:`404 Not found`: The webhook(ID) is unknown to the backend. :http:statuscode:`409 Conflict`: The provided information is inconsistent with the current state of the webhook. Changes made is the same with another store. .. ts:def:: WebhookPatchDetails interface WebhookPatchDetails { // The event of the webhook: why the webhook is used. event_type: string; // URL of the webhook where the customer will be redirected. url: string; // Method used by the webhook http_method: string; // Header template of the webhook header_template?: string; // Body template by the webhook body_template?: string; } Inspecting webhook ------------------ .. http:get:: [/instances/$INSTANCES]/private/webhooks This is used to return all the webhooks that are present in our backend. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned all the webhooks. Returns a `WebhookSummaryResponse`. :http:statuscode:`404 Not found`: The backend has does not know about the instance. .. ts:def:: WebhookSummaryResponse interface WebhookSummaryResponse { // Return webhooks that are present in our backend. webhooks: WebhookEntry[]; } The `WebhookEntry` object describes a webhook. It has the following structure: .. ts:def:: WebhookEntry interface WebhookEntry { // Webhook identifier, as found in the webhook. webhook_id: string; // The event of the webhook: why the webhook is used. event_type: string; } .. http:get:: [/instances/$INSTANCES]/private/webhooks/$WEBHOOK_ID This is used to obtain detailed information about apecific template. **Response:** :http:statuscode:`200 OK`: The backend has successfully returned the detailed information about a specific webhook. Returns a `WebhookDetails`. :http:statuscode:`404 Not found`: The webhook(ID) is unknown to the backend. .. ts:def:: WebhookDetails interface WebhookDetails { // The event of the webhook: why the webhook is used. event_type: string; // URL of the webhook where the customer will be redirected. url: string; // Method used by the webhook http_method: string; // Header template of the webhook header_template?: string; // Body template by the webhook body_template?: string; } Removing webhook ----------------- .. http:delete:: [/instances/$INSTANCES]/private/webhooks/$WEBHOOK_ID This is used to delete information about a webhook. **Response:** :http:statuscode:`204 No content`: The backend has successfully deleted the webhook. :http:statuscode:`404 Not found`: The webhook(ID) or the instance is unknown to the backend. ---------------------------------------- Token Families: Subscriptions, Discounts ---------------------------------------- This API provides functionalities for the issuance, management, and revocation of token families. Tokens facilitate the implementation of subscriptions and discounts, engaging solely the merchant and the user. Each token family encapsulates details pertaining to its respective tokens, guiding the merchant's backend on the appropriate processing and handling. Creating token families ----------------------- .. http:post:: [/instances/$INSTANCES]/private/tokenfamilies This is used to create a token family. **Request:** The request must be a `TokenFamilyCreateRequest`. **Response:** :http:statuscode:`204 No content`: The token family was created successfully. :http:statuscode:`404 Not found`: The merchant backend is unaware of the instance. .. ts:def:: TokenFamilyCreateRequest interface TokenFamilyCreateRequest { // Identifier for the token family consisting of unreserved characters // according to RFC 3986. slug: string; // Human-readable name for the token family. name: string; // Human-readable description for the token family. description: string; // Optional map from IETF BCP 47 language tags to localized descriptions. description_i18n?: { [lang_tag: string]: string }; // Start time of the token family's validity period. // If not specified, merchant backend will use the current time. valid_after?: Timestamp; // End time of the token family's validity period. valid_before: Timestamp; // Validity duration of an issued token. duration: RelativeTime; // Kind of the token family. kind: TokenFamilyKind; } .. ts:def:: TokenFamilyKind enum TokenFamilyKind { Discount = "discount", Subscription = "subscription", } Updating token families ----------------------- .. http:patch:: [/instances/$INSTANCES]/private/tokenfamilies/$TOKEN_FAMILY_SLUG This is used to update a token family. **Request:** The request must be a `TokenFamilyUpdateRequest`. **Response:** :http:statuscode:`200 OK`: The token family was successsful updated. Returns a `TokenFamilyDetails`. :http:statuscode:`404 Not found`: The merchant backend is unaware of the token family or instance. .. ts:def:: TokenFamilyUpdateRequest interface TokenFamilyUpdateRequest { // Human-readable name for the token family. name: string; // Human-readable description for the token family. description: string; // Optional map from IETF BCP 47 language tags to localized descriptions. description_i18n: { [lang_tag: string]: string }; // Start time of the token family's validity period. valid_after: Timestamp; // End time of the token family's validity period. valid_before: Timestamp; // Validity duration of an issued token. duration: RelativeTime; } Inspecting token families ------------------------- .. http:get:: [/instances/$INSTANCES]/private/tokenfamilies This is used to list all configured token families for an instance. **Response:** :http:statuscode:`200 OK`: The merchant backend has successfully returned all token families. Returns a `TokenFamiliesList`. :http:statuscode:`404 Not found`: The merchant backend is unaware of the instance. .. ts:def:: TokenFamiliesList // TODO: Add pagination interface TokenFamiliesList { // All configured token families of this instance. token_families: TokenFamilySummary[]; } .. ts:def:: TokenFamilySummary interface TokenFamilySummary { // Identifier for the token family consisting of unreserved characters // according to RFC 3986. slug: string; // Human-readable name for the token family. name: string; // Start time of the token family's validity period. valid_after: Timestamp; // End time of the token family's validity period. valid_before: Timestamp; // Kind of the token family. kind: TokenFamilyKind; } .. http:get:: [/instances/$INSTANCES]/private/tokenfamilies/$TOKEN_FAMILY_SLUG This is used to get detailed information about a specific token family. **Response:** :http:statuscode:`200 OK`: The merchant backend has successfully returned the detailed information about a specific token family. Returns a `TokenFamilyDetails`. :http:statuscode:`404 Not found`: The merchant backend is unaware of the token family or instance. The `TokenFamilyDetails` object describes a configured token family. .. ts:def:: TokenFamilyDetails interface TokenFamilyDetails { // Identifier for the token family consisting of unreserved characters // according to RFC 3986. slug: string; // Human-readable name for the token family. name: string; // Human-readable description for the token family. description: string; // Optional map from IETF BCP 47 language tags to localized descriptions. description_i18n?: { [lang_tag: string]: string }; // Start time of the token family's validity period. valid_after: Timestamp; // End time of the token family's validity period. valid_before: Timestamp; // Validity duration of an issued token. duration: RelativeTime; // Kind of the token family. kind: TokenFamilyKind; // How many tokens have been issued for this family. issued: Integer; // How many tokens have been redeemed for this family. redeemed: Integer; } Deleting token families ----------------------- .. http:delete:: [/instances/$INSTANCES]/private/tokenfamilies/$TOKEN_FAMILY_SLUG This is used to delete a token family. Issued tokens of this family will not be spendable anymore. **Response:** :http:statuscode:`204 No content`: The backend has successfully deleted the token family. :http:statuscode:`404 Not found`: The merchant backend is unaware of the token family or instance. ------------------ The Contract Terms ------------------ This section describes the overall structure of the contract terms that are the foundation for Taler payments. .. _contract-terms: The contract terms must have the following structure: .. ts:def:: ContractTerms interface ContractTerms { // Human-readable description of the whole purchase. summary: string; // Map from IETF BCP 47 language tags to localized summaries. summary_i18n?: { [lang_tag: string]: string }; // Unique, free-form identifier for the proposal. // Must be unique within a merchant instance. // For merchants that do not store proposals in their DB // before the customer paid for them, the ``order_id`` can be used // by the frontend to restore a proposal from the information // encoded in it (such as a short product identifier and timestamp). order_id: string; // List of contract choices that the customer can select from. // @since protocol **vSUBSCRIBE** choices: ContractChoice[]; // Total price for the transaction. // The exchange will subtract deposit fees from that amount // before transferring it to the merchant. amount: Amount; // URL where the same contract could be ordered again (if // available). Returned also at the public order endpoint // for people other than the actual buyer (hence public, // in case order IDs are guessable). public_reorder_url?: string; // URL that will show that the order was successful after // it has been paid for. Optional, but either ``fulfillment_url`` // or ``fulfillment_message`` must be specified in every // contract terms. // // If a non-unique fulfillment URL is used, a customer can only // buy the order once and will be redirected to a previous purchase // when trying to buy an order with the same fulfillment URL a second // time. This is useful for digital goods that a customer only needs // to buy once but should be able to repeatedly download. // // For orders where the customer is expected to be able to make // repeated purchases (for equivalent goods), the fulfillment URL // should be made unique for every order. The easiest way to do // this is to include a unique order ID in the fulfillment URL. // // When POSTing to the merchant, the placeholder text "${ORDER_ID}" // is be replaced with the actual order ID (useful if the // order ID is generated server-side and needs to be // in the URL). Note that this placeholder can only be used once. // Front-ends may use other means to generate a unique fulfillment URL. fulfillment_url?: string; // Message shown to the customer after paying for the order. // Either fulfillment_url or fulfillment_message must be specified. fulfillment_message?: string; // Map from IETF BCP 47 language tags to localized fulfillment // messages. fulfillment_message_i18n?: { [lang_tag: string]: string }; // Maximum total deposit fee accepted by the merchant for this contract. // Overrides defaults of the merchant instance. max_fee: Amount; // List of products that are part of the purchase (see `Product`). products: Product[]; // Time when this contract was generated. timestamp: Timestamp; // After this deadline has passed, no refunds will be accepted. refund_deadline: Timestamp; // After this deadline, the merchant won't accept payments for the contract. pay_deadline: Timestamp; // Transfer deadline for the exchange. Must be in the // deposit permissions of coins used to pay for this order. wire_transfer_deadline: Timestamp; // Merchant's public key used to sign this proposal; this information // is typically added by the backend. Note that this can be an ephemeral key. merchant_pub: EddsaPublicKey; // Base URL of the (public!) merchant backend API. // Must be an absolute URL that ends with a slash. merchant_base_url: string; // More info about the merchant, see below. merchant: Merchant; // The hash of the merchant instance's wire details. h_wire: HashCode; // Wire transfer method identifier for the wire method associated with ``h_wire``. // The wallet may only select exchanges via a matching auditor if the // exchange also supports this wire method. // The wire transfer fees must be added based on this wire transfer method. wire_method: string; // Exchanges that the merchant accepts even if it does not accept any auditors that audit them. exchanges: Exchange[]; // Delivery location for (all!) products. delivery_location?: Location; // Time indicating when the order should be delivered. // May be overwritten by individual products. delivery_date?: Timestamp; // Nonce generated by the wallet and echoed by the merchant // in this field when the proposal is generated. nonce: string; // Specifies for how long the wallet should try to get an // automatic refund for the purchase. If this field is // present, the wallet should wait for a few seconds after // the purchase and then automatically attempt to obtain // a refund. The wallet should probe until "delay" // after the payment was successful (i.e. via long polling // or via explicit requests with exponential back-off). // // In particular, if the wallet is offline // at that time, it MUST repeat the request until it gets // one response from the merchant after the delay has expired. // If the refund is granted, the wallet MUST automatically // recover the payment. This is used in case a merchant // knows that it might be unable to satisfy the contract and // desires for the wallet to attempt to get the refund without any // customer interaction. Note that it is NOT an error if the // merchant does not grant a refund. auto_refund?: RelativeTime; // Extra data that is only interpreted by the merchant frontend. // Useful when the merchant needs to store extra information on a // contract without storing it separately in their database. // Must really be an Object (not a string, integer, float or array). extra?: Object; // Minimum age the buyer must have (in years). Default is 0. // This value is at least as large as the maximum over all // mimimum age requirements of the products in this contract. // It might also be set independent of any product, due to // legal requirements. minimum_age?: Integer; } The wallet must select an exchange that either the merchant accepts directly by listing it in the exchanges array, or for which the merchant accepts an auditor that audits that exchange by listing it in the auditors array. The `Product` object describes the product being purchased from the merchant. It has the following structure: .. ts:def:: Product interface Product { // Merchant-internal identifier for the product. product_id?: string; // Human-readable product description. description: string; // Map from IETF BCP 47 language tags to localized descriptions. description_i18n?: { [lang_tag: string]: string }; // The number of units of the product to deliver to the customer. quantity?: Integer; // Unit in which the product is measured (liters, kilograms, packages, etc.). unit?: string; // The price of the product; this is the total price for ``quantity`` times ``unit`` of this product. price?: Amount; // An optional base64-encoded product image. image?: ImageDataUrl; // A list of taxes paid by the merchant for this product. Can be empty. taxes?: Tax[]; // Time indicating when this product should be delivered. delivery_date?: Timestamp; } .. ts:def:: Tax interface Tax { // The name of the tax. name: string; // Amount paid in tax. tax: Amount; } .. ts:def:: Merchant interface Merchant { // The merchant's legal name of business. name: string; // Label for a location with the business address of the merchant. email?: string; // Label for a location with the business address of the merchant. website?: string; // An optional base64-encoded product image. logo?: ImageDataUrl; // Label for a location with the business address of the merchant. address?: Location; // Label for a location that denotes the jurisdiction for disputes. // Some of the typical fields for a location (such as a street address) may be absent. jurisdiction?: Location; } .. ts:def:: Location // Delivery location, loosely modeled as a subset of // ISO20022's PostalAddress25. interface Location { // Nation with its own government. country?: string; // Identifies a subdivision of a country such as state, region, county. country_subdivision?: string; // Identifies a subdivision within a country sub-division. district?: string; // Name of a built-up area, with defined boundaries, and a local government. town?: string; // Specific location name within the town. town_location?: string; // Identifier consisting of a group of letters and/or numbers that // is added to a postal address to assist the sorting of mail. post_code?: string; // Name of a street or thoroughfare. street?: string; // Name of the building or house. building_name?: string; // Number that identifies the position of a building on a street. building_number?: string; // Free-form address lines, should not exceed 7 elements. address_lines?: string[]; } .. ts:def:: Auditor interface Auditor { // Official name. name: string; // Auditor's public key. auditor_pub: EddsaPublicKey; // Base URL of the auditor. url: string; } .. ts:def:: Exchange interface Exchange { // The exchange's base URL. url: string; // How much would the merchant like to use this exchange. // The wallet should use a suitable exchange with high // priority. The following priority values are used, but // it should be noted that they are NOT in any way normative. // // 0: likely it will not work (recently seen with account // restriction that would be bad for this merchant) // 512: merchant does not know, might be down (merchant // did not yet get /wire response). // 1024: good choice (recently confirmed working) priority: Integer; // Master public key of the exchange. master_pub: EddsaPublicKey; } In addition to the fields described above, each object (from ``ContractTerms`` down) can mark certain fields as "forgettable" by listing the names of those fields in a special peer field ``_forgettable``. (See :ref:`Private order data cleanup `.)