The GNU Taler Merchant API Tutorial (Version for LANGNAME)
**********************************************************

This document is a tutorial for the GNU Taler Merchant API (version VERSION, UPDATED)

Copyright © 2018 Taler Systems SA

     Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts.  A copy of the license is included in the section entitled ``GNU Free Documentation License''.

Introduction
************

About GNU Taler
===============

GNU Taler is an open protocol for an electronic payment system with a free software reference implementation.  GNU Taler offers secure, fast and easy payment processing using well understood cryptographic techniques.  GNU Taler allows customers to remain anonymous, while ensuring that merchants can be held accountable by governments.  Hence, GNU Taler is compatible with anti-money-laundering (AML) and know-your-customer (KYC) regulation, as well as data protection regulation (such as GDPR).

About this tutorial
===================

This tutorial addresses how to process payments using the GNU Taler merchant Backend. This chapter explains some basic concepts.  In the second chapter, you will learn how to do basic payments.

Versions for other languages/environments are available as well.

If you want to look at some simple, running examples, check out these:

  * The essay merchant (https://git.taler.net/blog.git/tree/talerblog/blog/blog.py) that sells single chapters of a book.

  * The donation page (https://git.taler.net/donations.git/tree/talerdonations/donations/donations.py) that accepts donations for software projects and gives donation receipts.

  * The survey (https://git.taler.net/survey.git/tree/talersurvey/survey/survey.py) that gives users who answer a question a small reward.

Architecture overview
=====================

The Taler software stack for a merchant consists of the following main components:

  * A frontend which interacts with the customer's browser. The frontend enables the customer to build a shopping cart and place an order.  Upon payment, it triggers the respective business logic to satisfy the order.  This component is not included with Taler, but rather assumed to exist at the merchant. This tutorial describes how to develop a Taler frontend.

  * A Taler-specific payment backend which makes it easy for the frontend to process financial transactions with Taler.  For this tutorial, you will use a public sandbox backend.  For production use, you must either set up your own backend or ask another person to do so for you.

The following image illustrates the various interactions of these key components:

The backend provides the cryptographic protocol support, stores Taler-specific financial information and communicates with the GNU Taler exchange over the Internet.  The frontend accesses the backend via a RESTful API.  As a result, the frontend never has to directly communicate with the exchange, and also does not deal with sensitive data.  In particular, the merchant's signing keys and bank account information are encapsulated within the Taler backend.

Some functionality of the backend (the ``public interface``) is also exposed to the customer's browser directly.  In the HTTP API, all public endpoints are prefixed with /public/.

Public Sandbox Backend and Authentication
=========================================

How the frontend authenticates with the Taler backend depends in the configuration. See Taler Merchant Operating Manual.

The public sandbox backend https://backend.demo.taler.net uses an API key in the Authorization header.  The value of this header must be ApiKey sandbox for the public sandbox backend.

     (example not available for this language)

If an HTTP status code other than 200 is returned, something went wrong. You should figure out what the problem is before continuing with this tutorial.

The sandbox backend https://backend.demo.taler.net uses KUDOS as an imaginary currency.  Coins denominated with KUDOS can be withdrawn from https://bank.demo.taler.net.

Merchant Instances
==================

The same Taler merchant backend server can be used by multiple separate merchants that are separate business entities.  Each of these separate business entities is called a merchant instance, and is identified by an alphanumeric instance id.  If the instance is omitted, the instance id default is assumed.

The following merchant instances are configured on https://backend.demo.taler.net:

  * GNUnet (The GNUnet project)

  * FSF (The Free Software Foundation)

  * Tor (The Tor Project)

  * default (Kudos Inc.)

Note that these are fictional merchants and not necessarily affiliated with the respective project.

Accepting a Simple Payment
**************************

Creating an Order for a Payment
===============================

Payments in Taler revolve around an order, which is a machine-readable description of the payment's details.  Before accepting a Taler payment as a merchant you must create an order.

This is done by posting a JSON object to the backend's /order API endpoint.  At least the following fields must be given:

  * AMOUNT: The amount to be paid, as a string in the format CURRENCY:DECIMAL_VALUE, for example EUR:10 for 10 Euros or KUDOS:1.5 for 1.5 KUDOS.

  * SUMMARY:  A human-readable summary for what the payment is about, should be short enough to fit into titles, though currently no hard limit is enforced.

  * FULFILLMENT_URL:  A URL that will be displayed once the payment is completed.  For digital goods, this should be a page that displays the product that was purchased.  On successful payment, the wallet automatically appends the order_id as a query parameter, as well as the session_sig for session-bound payments (discussed later).

After successfully POSTing to /order, an order_id will be returned.  Together with the merchant instance, the order id uniquely identifies the order within a merchant backend.

     (example not available for this language)

The backend will fill in some details missing in the order, such as the address of the merchant instance.  The full details are often called the contract terms.

Checking Payment Status and Prompting for Payment
=================================================

The status of a payment can be checked with the /check-payment endpoint.  If the payment wasn't completed yet by the customer, /check-payment will give the frontend a URL (PAYMENT_REDIRECT_URL) that will trigger the customer's wallet to trigger the payment.

Note that the only way to obtain the PAYMENT_REDIRECT_URL is to check the status of the payment, even if you know that the user did not pay yet.

     (example not available for this language)

Depending on the value of the PAID field in the response, the other fields will be different.  Once the payment was completed by the user, the response will contain the following fields:

  * PAID: Set to TRUE.

  * CONTRACT_TERMS:  The full contract terms derived from the order.

  * REFUNDED:  Boolean that indicates whether any (partial) refund happened for this purchase.

  * REFUNDED_AMOUNT:  Amount that was refunded

  * LAST_SESSION_ID:  Last session ID used by the customer's wallet.  Advanced feature, explained later.

Giving Refunds
**************

A refund in GNU Taler is a way to ``undo'' a payment.  It needs to be authorized by the merchant at request of the customer.  Refunds can be full refunds, or only refund a fraction of the original amount paid.  Refunds are time-limited and can only happen while the exchange holds funds for a particular payment in escrow.  The time during which a refund is possible can be controlled by setting the refund_deadline in an order.  The default value for the refund deadline depends on the configuration of the backend.

The frontend can instruct the merchant backend to authorize a refund by posting to the /refund endpoint.

The refund request JSON object has the following fields:

  * ORDER_ID: The ID that identifies the order to be refunded.

  * INSTRANCE: The merchant instance to use (defaults to default).

  * REFUND:  The amount to be refunded.  If a previous refund was authorized for the same order, the new amout must be higher.  Indicates the total amount refunded, not an increase in the refund.

  * REASON:  Reason for the refund, only used for the Back Office and not directly shown to the customer.

If the request is successful (indicated by HTTP status code 200), the response includes a refund_redirect_url.  The frontend must navigate the customer's browser to allow the refund to be processed by the wallet.

This code snipped illustrates giving a refund:

     (example not available for this language)

Giving Customer Tips
********************

GNU Taler allows merchants to give small sums of money directly to the customer, for example to incentivize actions such as filling out a survey or trying a new feature.  The merchant backend must be properly configured for this, and enough funds must be made available for tipping see Taler Merchant Operating Manual.

To check if tipping is configured properly and if there are enough funds available to tip, query the /tip-query endpoint:

     (example not available for this language)

To authorize a tip, post to /tip-authorize.  The following fields are recognized in the JSON request object:

  * AMOUNT: Amount that should be given to the customer as a tip.

  * INSTANCE: Merchant instance that gives the tip (each instance has their own independend tipping funds configured).

  * JUSTIFICATION: Description of why the tip was given.  Not given to the customer, but used from back office purposes.

  * NEXT_URL: The URL that the user's browser will be redirected to by the wallet, once the tip has been processed.

The response contains a tip_redirect_url, the customer's browser must be redirected to this URL to accept the tip.

This code snipped illustrates giving a tip:

     (example not available for this language)

Advanced topics
***************

Detecting the Presence of the Taler Wallet
==========================================

Taler offers ways to detect whether a user has the wallet installed in their browser, and take actions accordingly.  Note that not all platforms can do presence detection reliably.  Some platforms might have a Taler wallet installed, but the browser is not aware of its presence.

Presence detection without JavaScript
-------------------------------------

Presence detection without JavaScript is based on CSS classes.  You can hide or show elements selectively depending on whether the wallet is detected or not.

In order to work correctly, a special fallback stylesheet must be included that will be used when the wallet is not present.  The stylesheet can be put into any file, but must be included via a link tag with the id attribute set to taler-presence-stylesheet.  If a wallet is present, it will ``hijack'' this stylesheet to change how elements with the following classes are rendered:

The following CSS classes can be used:

taler-installed-hide
     A CSS rule will set the display property for this class to none once the Taler wallet is installed and enabled. If the wallet is not installed, display will be inherit.

taler-installed-show
     A CSS rule will set the display property for this class to inherit once the Taler wallet is installed and enabled. If the wallet is not installed, display will be none.

The following is a complete example:

     <!DOCTYPE html>
     <html data-taler-nojs="true">
       <head>
         <title>Tutorial</title>
         <link rel="stylesheet"
               type="text/css"
               href="/web-common/taler-fallback.css"
               id="taler-presence-stylesheet" />
       </head>
       <body>
         <p class="taler-installed-hide">
           No wallet found.
         </p>
         <p class="taler-installed-show">
           Wallet found!
         </p>
       </body>
     </html>

The taler-fallback.css is part of the Taler's web-common repository, available at https://git.taler.net/web-common.git.  Please adjust the href attribute in order to make it work with your Web site.

Detection with JavaScript
-------------------------

The following functions are defined in the taler namespace of the taler-wallet-lib helper library available at https://git.taler.net/web-common.git/tree/taler-wallet-lib.js.

onPresent(callback: () => void)
     Add a callback to be called when support for Taler payments is detected.

onAbsent(callback: () => void)
     Add a callback to be called when support for Taler payments is disabled.

Note that the registered callbacks can be called more than once, since a user can disable/enable the wallet in the browser's setting while a shop frontend page is open.

Integration with the Back Office
================================

Taler ships the back-office feature as a stand-alone Web application. See how to run it, on its own documentaion: https://docs.taler.net/backoffice/html/manual.html.

Session-Bound Payments
======================

Sometimes checking if an order has been paid for is not enough, but the merchant wants to checked if the ``payment receipt'' is available on the user's current device.  This prevents users from easily sharing digital goods by just sharing a link to the fulfillment page.  Of course advanced users can easily share these payment receipts, but it is not as easy as sharing a link.

To use this feature, the merchant must first assign the user's current browser an ephemeral session_id, usually via a session cookie.  When executing or re-playing a payment, the wallet will receive a signature (session_sig) that certifies that in the current session, the wallet showed a payment receipt for the respective order.

Session-bound payments are triggerd by passing the session_id parameter to the /check-payment endpoint.  The wallet will then redirect to the fulfillment page, but include an additional session_sig parameter.  The frontend can query /check-payment with both the session_id and the session_sig again to verify that the signature is correct.

The last session ID that was successfuly used to prove that the payment receipt is in the user's wallet is also available as last_session_id in the response to /check-payment.

In some situations the user has paid for some digital good, but the frontend does not know the exact order ID, and thus can't instruct the wallet to show the existing payment receipt.  This is common for simple shops without a login system.  In this case, the user would be prompted for payment again, even though they already purchased the product.  To allow the wallet to instead show the existing payment receipt, the resource_url parameter must be given to /check-payment.  It should correspond to the fulfillment URL for the potentially existing payment for the same product.

The Taler Order Format
======================

A Taler order can specify many details about the payment. This section describes each of the fields in depth.

Financial amounts are always specified as a string in the format "CURRENCY:DECIMAL_VALUE".

amount
     Specifies the total amount to be paid to the merchant by the customer.

max_fee
     This is the maximum total amount of deposit fees that the merchant is willing to pay.  If the deposit fees for the coins exceed this amount, the customer has to include it in the payment total.  The fee is specified using the same triplet used for AMOUNT.

max_wire_fee
     Maximum wire fee accepted by the merchant (customer share to be divided by the 'wire_fee_amortization' factor, and further reduced if deposit fees are below 'max_fee').  Default if missing is zero.

wire_fee_amortization
     Over how many customer transactions does the merchant expect to amortize wire fees on average?  If the exchange's wire fee is above 'max_wire_fee', the difference is divided by this number to compute the expected customer's contribution to the wire fee. The customer's contribution may further be reduced by the difference between the 'max_fee' and the sum of the actual deposit fees. Optional, default value if missing is 1.  0 and negative values are invalid and also interpreted as 1.

pay_url
     Which URL accepts payments. This is the URL where the wallet will POST coins.

fulfillment_url
     Which URL should the wallet go to for obtaining the fulfillment, for example the HTML or PDF of an article that was bought, or an order tracking system for shipments, or a simple human-readable Web page indicating the status of the contract.

order_id
     Alphanumeric identifier, freely definable by the merchant. Used by the merchant to uniquely identify the transaction.

summary
     Short, human-readable summary of the contract. To be used when displaying the contract in just one line, for example in the transaction history of the customer.

timestamp
     Time at which the offer was generated.

pay_deadline
     Timestamp of the time by which the merchant wants the exchange to definitively wire the money due from this contract.  Once this deadline expires, the exchange will aggregate all deposits where the contracts are past the REFUND_DEADLINE and execute one large wire payment for them.  Amounts will be rounded down to the wire transfer unit; if the total amount is still below the wire transfer unit, it will not be disbursed.

refund_deadline
     Timestamp until which the merchant willing (and able) to give refunds for the contract using Taler.  Note that the Taler exchange will hold the payment in escrow at least until this deadline.  Until this time, the merchant will be able to sign a message to trigger a refund to the customer.  After this time, it will no longer be possible to refund the customer.  Must be smaller than the PAY_DEADLINE.

products
     Array of products that are being sold to the customer.  Each entry contains a tuple with the following values:

     description
          Description of the product.

     quantity
          Quantity of the items to be shipped. May specify a unit (1 kg) or just the count.

     price
          Price for QUANTITY units of this product shipped to the given DELIVERY_LOCATION. Note that usually the sum of all of the prices should add up to the total amount of the contract, but it may be different due to discounts or because individual prices are unavailable.

     product_id
          Unique ID of the product in the merchant's catalog.  Can generally be chosen freely as it only has meaning for the merchant, but should be a number in the range [0,2^51).

     taxes
          Map of applicable taxes to be paid by the merchant.  The label is the name of the tax, i.e. VAT, SALES TAX or INCOME TAX, and the value is the applicable tax amount.  Note that arbitrary labels are permitted, as long as they are used to identify the applicable tax regime.  Details may be specified by the regulator. This is used to declare to the customer which taxes the merchant intends to pay, and can be used by the customer as a receipt. The information is also likely to be used by tax audits of the merchant.

     delivery_date
          Time by which the product is to be delivered to the DELIVERY_LOCATION.

     delivery_location
          This should give a label in the LOCATIONS map, specifying where the item is to be delivered.

     Values can be omitted if they are not applicable. For example, if a purchase is about a bundle of products that have no individual prices or product IDs, the PRODUCT_ID or PRICE may not be specified in the contract.  Similarly, for virtual products delivered directly via the fulfillment URI, there is no delivery location.

merchant

     address
          This should give a label in the LOCATIONS map, specifying where the merchant is located.

     name
          This should give a human-readable name for the merchant's business.

     jurisdiction
          This should give a label in the LOCATIONS map, specifying the jurisdiction under which this contract is to be arbitrated.

locations
     Associative map of locations used in the contract. Labels for locations in this map can be freely chosen and used whenever a location is required in other parts of the contract.  This way, if the same location is required many times (such as the business address of the customer or the merchant), it only needs to be listed (and transmitted) once, and can otherwise be referred to via the label.  A non-exhaustive list of location attributes is the following:

     country
          Name of the country for delivery, as found on a postal package, i.e. ``France''.

     state
          Name of the state for delivery, as found on a postal package, i.e. ``NY''.

     region
          Name of the region for delivery, as found on a postal package.

     province
          Name of the province for delivery, as found on a postal package.

     city
          Name of the city for delivery, as found on a postal package.

     ZIP code
          ZIP code for delivery, as found on a postal package.

     street
          Street name for delivery, as found on a postal package.

     street number
          Street number (number of the house) for delivery, as found on a postal package.

     name receiver name for delivery, either business or person name.

     Note that locations are not required to specify all of these fields, and it is also allowed to have additional fields.  Contract renderers must render at least the fields listed above, and should render fields that they do not understand as a key-value list.

GNU-LGPL
********

     [file lgpl.texi not included]

GNU-FDL
*******

     [file fdl-1.3.texi not included]