summaryrefslogtreecommitdiff
path: root/core/api-merchant.rst
blob: 331f4eb5b0bc03f8ef105723cdffc6da2e2f7d27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
..
  This file is part of GNU TALER.
  Copyright (C) 2014-2020 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 <http://www.gnu.org/licenses/>

  @author Marcello Stanisci
  @author Florian Dold
  @author Christian Grothoff

.. _merchant-api:

====================
Merchant Backend API
====================

.. contents:: Table of Contents

-----------------------
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.  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 a 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.

To manage instances, private endpoints only available to the ``default``
instance must be used.

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):
   https://merchant-backend.example.com/orders

   A private endpoint ("myinst" instance):
   https://merchant-backend.example.com/instances/myinst/private/orders

   A public endpoint ("myinst" instance):
   https://merchant-backend.example.com/instances/myinst/orders

   A private endpoint (explicit "default" instance):
   https://merchant-backend.example.com/instances/default/private/orders

   A public endpoint (explicit "default" instance):
   https://merchant-backend.example.com/instances/default/orders

   Endpoints to manage other instances (ONLY for implicit "default" instance):
   https://merchant-backend.example.com/private/instances
   https://merchant-backend.example.com/private/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 auth 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.

-----------------
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.

  **Response:**

  :http:statuscode:`200 OK`:
    The exchange accepted all of the coins. 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";

      // Currency supported by this backend.
      currency: string;

    }


----------
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),
process refunds (checking refund status, obtaining the refund),
and to pick up tips.


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:: /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 <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:: /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 <PayRequest>`.

  **Response:**

  :http:statuscode:`200 OK`:
    The exchange accepted all of the coins.
    The body is a `payment response <PaymentResponse>`.
    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.
  :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 "406 Not Acceptable", 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:`406 Not acceptable`:
    The payment is insufficient (sum is below the required total amount).
  :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.
    The response will include the ``coin_pub`` for which the payment failed,
    in addition to the response from the exchange to the ``/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.
  :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 <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;

    }

  .. ts:def:: PayRequest

    interface PayRequest {
      // The coins used to make the payment.
      coins: CoinPaySig[];

      // 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: RsaSignature;

      // 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;
    }

Querying payment status
-----------------------

.. http:get:: /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: 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 refund=AMOUNT: *Optional*. Indicates that we are polling for a refund above the given AMOUNT. Only useful in combination with timeout.
  :query await_refund_obtained=BOOLEAN: *Optional*. If set to "yes", poll for the order's pending refunds to be picked up.

  **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.
  :http:statuscode:`302 Found`:
    The client should go to the indicated location. Only returned if the content type requested was HTML.
  :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:`410 Gone`:
    The response is a `StatusGoneResponse`.
  :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;
    }

  .. ts:def:: StatusGotoResponse

    interface StatusGotoResponse {
      // The client should go to the fulfillment URL, it may be ready or
      // might have some other interesting status.
      fulfillment_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;
    }

  .. ts:def:: StatusGoneResponse

    // The client tried to access the order via the claim
    // token (and not a valid ``h_contract``), but the order can't be claimed
    // anymore, as it is already paid.
    interface StatusGoneResponse {
      // Fulfillment URL for the order.
      fulfillment_url: 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:: /orders/$ORDER_ID/paid

  Prove that the client previously paid for an order by providing
  the merchant's signature from the `payment response <PaymentResponse>`.
  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 <PaidRequest>`.

  **Response:**

  :http:statuscode:`204 No content`:
    The merchant accepted the signature.
    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.
  :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.
  :http:statuscode:`409 Conflict`:
    The provided contract hash does not match this order.

  .. 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;

      // 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:: /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 <AbortRequest>`.  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 `merchant refund response <MerchantRefundResponse>`. 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 <AbortResponse>`, which includes
  verbatim the error codes received from the exchange's
  :ref:`refund <exchange_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:: /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;
    }

  .. 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;
    }


Picking up tips
---------------

Tips are a way for wallets to obtain e-cash from
a website.

.. http:get:: /tips/$TIP_ID

  Handle request from wallet to provide details about a tip.

  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. If the backend
  installation does not include the required HTML templates, a 406 status
  code is returned.

  **Response:**

  :http:statuscode:`200 OK`:
    A tip is being returned. The backend responds with a `TipInformation`.
  :http:statuscode:`404 Not found`:
    The tip identifier is unknown.
  :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.)
  :http:statuscode:`410 Gone`:
    A tip has been fully claimed. The JSON reply still contains the `TipInformation`.

  .. ts:def:: TipInformation

    interface TipInformation {

      // Exchange from which the tip will be withdrawn. Needed by the
      // wallet to determine denominations, fees, etc.
      exchange_url: string;

      // (Remaining) amount of the tip (including fees).
      tip_amount: Amount;

      // Timestamp indicating when the tip is set to expire (may be in the past).
      // Note that tips that have expired MAY also result in a 404 response.
      expiration: Timestamp;
    }


.. http:post:: /tips/$TIP_ID/pickup

  Handle request from wallet to pick up a tip.

  **Request:**

  The request body is a `TipPickupRequest` object.

  **Response:**

  :http:statuscode:`200 OK`:
    A tip is being returned. The backend responds with a `TipResponse`.
  :http:statuscode:`401 Unauthorized`:
    The tip amount requested exceeds the tip.
  :http:statuscode:`404 Not found`:
    The tip identifier is unknown.
  :http:statuscode:`409 Conflict`:
    Some of the denomination key hashes of the request do not match those currently available from the exchange (hence there is a conflict between what the wallet requests and what the merchant believes the exchange can provide).
  :http:statuscode:`410 Gone`:
    The tip has expired.

  .. ts:def:: TipPickupRequest

    interface TipPickupRequest {

      // List of planchets the wallet wants to use for the tip.
      planchets: PlanchetDetail[];
    }

  .. ts:def:: PlanchetDetail

    interface PlanchetDetail {
      // Hash of the denomination's public key (hashed to reduce
      // bandwidth consumption).
      denom_pub_hash: HashCode;

      // Coin's blinded public key.
      coin_ev: CoinEnvelope;
    }

  .. ts:def:: TipResponse

    interface TipResponse {

      // Blind RSA signatures over the planchets.
      // The order of the signatures matches the planchets list.
      blind_sigs: BlindSignature[];
    }

  .. ts:def:: BlindSignature

    interface BlindSignature {

      // The (blind) RSA signature. Still needs to be unblinded.
      blind_sig: BlindedRsaSignature;
    }


-------------------
Instance management
-------------------

Instances allow one merchant backend to be shared by multiple merchants.
Every backend must have at least one instance, typcially the "default"
instance setup before it can be used to manage inventory or process payments.


Setting up instances
--------------------

.. http:post:: /private/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 {
      // The URI where the wallet will send coins.  A merchant may have
      // multiple accounts, thus this is an array.  Note that by
      // removing URIs from this list the respective account is set to
      // inactive and thus unavailable for new contracts, but preserved
      // in the database as existing offers and contracts may still refer
      // to it.
      payto_uris: string[];

      // 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;

      // 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;

      // Maximum wire fee this instance is willing to pay.
      // Can be overridden by the frontend on a per-order basis.
      default_max_wire_fee: Amount;

      // Default factor for wire fee amortization calculations.
      // Can be overridden by the frontend on a per-order basis.
      default_wire_fee_amortization: Integer;

      // Maximum deposit fee (sum over all coins) this instance is willing to pay.
      // Can be overridden by the frontend on a per-order basis.
      default_max_deposit_fee: Amount;

      // 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:: /private/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 "external", 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:patch:: /private/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 {
      // The URI where the wallet will send coins.  A merchant may have
      // multiple accounts, thus this is an array.  Note that removing
      // URIs from this list deactivates the specified accounts
      // (they will no longer be used for future contracts).
      payto_uris: string[];

      // Merchant name corresponding to this instance.
      name: string;

      // 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;

      // Maximum wire fee this instance is willing to pay.
      // Can be overridden by the frontend on a per-order basis.
      default_max_wire_fee: Amount;

      // Default factor for wire fee amortization calculations.
      // Can be overridden by the frontend on a per-order basis.
      default_wire_fee_amortization: Integer;

      // Maximum deposit fee (sum over all coins) this instance is willing to pay.
      // Can be overridden by the frontend on a per-order basis.
      default_max_deposit_fee: Amount;

      // 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:: /private/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;

      // 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:: /private/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 {
      // The URI where the wallet will send coins.  A merchant may have
      // multiple accounts, thus this is an array.
      accounts: MerchantAccount[];

      // Merchant name corresponding to this instance.
      name: string;

      // 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;

      // Maximum wire fee this instance is willing to pay.
      // Can be overridden by the frontend on a per-order basis.
      default_max_wire_fee: Amount;

      // Default factor for wire fee amortization calculations.
      // Can be overridden by the frontend on a per-order basis.
      default_wire_fee_amortization: Integer;

      // Maximum deposit fee (sum over all coins) this instance is willing to pay.
      // Can be overridden by the frontend on a per-order basis.
      default_max_deposit_fee: Amount;

      // 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: {
        type: "external" | "token";
      };

    }

  .. ts:def:: MerchantAccount

    interface MerchantAccount {

      // 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;

      // true if this account is active,
      // false if it is historic.
      active: boolean;
    }


Deleting instances
------------------

.. http:delete:: /private/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.


--------------------
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;

    }



.. 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;

    }

Inspecting inventory
--------------------

.. http:get:: [/instances/$INSTANCE]/private/products

  This is used to return the list of all items in the inventory.

  **Response:**

  :http:statuscode:`200 OK`:
    The backend has successfully returned the inventory. Returns
    a `InventorySummaryResponse`.

  .. 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;

    }


.. 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`.

  .. 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;

    }


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
      // It is suggested that clients use a timeflake for this,
      // see https://github.com/anthonynsimon/timeflake
      lock_uuid: UUID;

      // 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:`/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.

    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;

      // 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?: UUID[];

      // 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'.
      create_token?: boolean;

    }

  .. ts:def:: Order

    type Order : MinimalOrderDetail | ContractTerms;

  The following fields must be specified in the ``order`` field of the request.  Other fields from
  `ContractTerms` are optional, and will override the defaults in the merchant configuration.

  .. ts:def:: MinimalOrderDetail

    interface MinimalOrderDetail {
      // Amount to be paid by the customer.
      amount: Amount;

      // Short summary of the order.
      summary: string;

      // URL that will show that the order was successful after
      // it has been paid for.  Optional. When POSTing to the
      // merchant, the placeholder "${ORDER_ID}" will be
      // replaced with the actual order ID (useful if the
      // order ID is generated server-side and needs to be
      // in the URL).
      fulfillment_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 date_ms: *Optional.* Non-negative date in milliseconds 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 ``UINT64_MAX``, namely the biggest row id possible in the database.
  :query delta: *Optional*. takes value of the form ``N (-N)``, so that at most ``N`` values strictly older (younger) than ``start`` and ``date_ms`` are returned.  Defaults to ``-20`` to return the last 20 entries (before ``start`` and/or ``date_ms``).
  :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.

  **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: *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).

  **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 <error-codes>` 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_ec: 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_hc: number;

      // Total amount that was refunded, 0 if refunded is false.
      refund_amount: Amount;

      // Contract terms.
      contract_terms: ContractTerms;

      // 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.
      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;

      // 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 <error-codes>`.
      code: number;

      // Human-readable error description.
      hint: string;

      // Numerical `error code <error-codes>` from the exchange.
      exchange_ec: number;

      // HTTP status code received from the exchange.
      exchange_hc: 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 <ForgetRequest>`. 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 <ContractTerms>` 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 <ContractTerms>`
  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 <TransferInformation>`.

  **Response:**

  :http:statuscode:`200 OK`:
    The wire transfer is known to the exchange, details about it follow in the body.
    The body of the response is a `MerchantTrackTransferResponse`.
  :http:statuscode:`202 Accepted`:
    The exchange provided conflicting information about the transfer. Namely,
    there is at least one deposit among the deposits aggregated by ``wtid``
    that accounts for a coin whose
    details don't match the details stored in merchant's database about the same keyed coin.
    The response body contains the `ExchangeConflictDetails`.
    This is indicative of a malicious exchange that claims one thing, but did
    something else.  (With respect to the HTTP specficiation, it is not
    precisely that we did not act upon the request, more that the usual
    action of filing the transaction as 'finished' does not apply.  In
    the future, this is a case where the backend actually should report
    the bad behavior to the auditor -- and then hope for the auditor to
    resolve it. So in that respect, 202 is the right status code as more
    work remains to be done for a final resolution.)
  :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,
    wire method or exchange, or the amount reported by the exchange differs from
    the amount reported by the merchant.
  :http:statuscode:`502 Bad gateway`:
    The exchange returned an error when we asked it about the ``GET /transfer`` status
    for this wire transfer. Details of the exchange error are returned.
  :http:statuscode:`504 Gateway timeout`:
    The merchant's interaction with the exchange took too long.
    The client might want to try again later.

  **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;
    }

  .. ts:def:: MerchantTrackTransferResponse

    interface MerchantTrackTransferResponse {
      // Total amount transferred.
      total: Amount;

      // Applicable wire fee that was charged.
      wire_fee: Amount;

      // Time of the execution of the wire transfer by the exchange, according to the exchange.
      execution_time: Timestamp;

      // Details about the deposits.
      deposits_sums: MerchantTrackTransferDetail[];
    }

  .. ts:def:: MerchantTrackTransferDetail

    interface MerchantTrackTransferDetail {
      // Business activity associated with the wire transferred amount
      // ``deposit_value``.
      order_id: string;

      // The total amount the exchange paid back for ``order_id``.
      deposit_value: Amount;

      // Applicable fees for the deposit.
      deposit_fee: Amount;
    }


  .. ts:def:: ExchangeConflictDetails

    type ExchangeConflictDetails = WireFeeConflictDetails |
                                   TrackTransferConflictDetails;


  .. ts:def:: WireFeeConflictDetails

    // Note: this is not the full 'proof' of misbehavior, as
    // the bogus message from the exchange with a signature
    // over the 'different' wire fee is missing.
    //
    // This information is NOT provided by the current implementation,
    // because this would be quite expensive to generate and is
    // hardly needed _here_. Once we add automated reports for
    // the Taler auditor, we need to generate this data anyway
    // and should probably return it here as well.
    interface WireFeeConflictDetails {
      // Numerical `error code <error-codes>`:
      code: "TALER_EC_MERCHANT_PRIVATE_POST_TRANSFERS_BAD_WIRE_FEE";

      // Text describing the issue for humans.
      hint: string;

      // Wire fee (wrongly) charged by the exchange, breaking the
      // contract affirmed by the ``exchange_sig``.
      wire_fee: Amount;

      // Timestamp of the wire transfer.
      execution_time: Timestamp;

      // The expected wire fee (as signed by the exchange).
      expected_wire_fee: Amount;

      // Expected closing fee (needed to verify signature).
      expected_closing_fee: Amount;

      // Start date of the expected fee structure.
      start_date: Timestamp;

      // End date of the expected fee structure.
      end_date: Timestamp;

      // Signature of the exchange affirming the expected fee structure.
      master_sig: EddsaSignature;

      // Master public key of the exchange.
      master_pub: EddsaPublicKey;
    }


  .. ts:def:: TrackTransferConflictDetails

    interface TrackTransferConflictDetails {
      // Numerical `error code <error-codes>`.
      code: "TALER_EC_MERCHANT_PRIVATE_POST_TRANSFERS_CONFLICTING_REPORTS";

      // Text describing the issue for humans.
      hint: string;

      // Offset in the ``exchange_transfer`` where the
      // exchange's response fails to match the ``exchange_deposit_proof``.
      conflict_offset: number;

      // The response from the exchange which tells us when the
      // coin was returned to us, except that it does not match
      // the expected value of the coin.
      //
      // This field is NOT provided by the current implementation,
      // because this would be quite expensive to generate and is
      // hardly needed _here_. Once we add automated reports for
      // the Taler auditor, we need to generate this data anyway
      // and should probably return it here as well.
      exchange_transfer?: TrackTransferResponse;

      // Public key of the exchange used to sign the response to
      // our deposit request.
      deposit_exchange_pub: EddsaPublicKey;

      // Signature of the exchange signing the (conflicting) response.
      // Signs over a ``struct TALER_DepositConfirmationPS``.
      deposit_exchange_sig: EddsaSignature;

      // Hash of the merchant's bank account the wire transfer went to.
      h_wire: HashCode;

      // Hash of the contract terms with the conflicting deposit.
      h_contract_terms: HashCode;

      // At what time the exchange received the deposit.  Needed
      // to verify the ``exchange_sig``.
      deposit_timestamp: Timestamp;

      // At what time the refund possibility expired (needed to verify ``exchange_sig``).
      refund_deadline: Timestamp;

      // Public key of the coin for which we have conflicting information.
      coin_pub: EddsaPublicKey;

      // Amount the exchange counted the coin for in the transfer.
      amount_with_fee: Amount;

      // Expected value of the coin.
      coin_value: Amount;

      // Expected deposit fee of the coin.
      coin_fee: Amount;

      // Expected deposit fee of the coin.
      deposit_fee: Amount;

    }

  .. ts:def:: TrackTransferProof

    interface TrackTransferProof {
      // Signature from the exchange made with purpose
      // ``TALER_SIGNATURE_EXCHANGE_CONFIRM_WIRE_DEPOSIT``.
      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``.  Again given
      // explicitly as the client might otherwise be confused by clock skew as to
      // which signing key was used.
      exchange_pub: EddsaSignature;

      // Hash of the wire details (identical for all deposits).
      // Needed to check the ``exchange_sig``
      h_wire: HashCode;
    }


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 ist 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.


--------------------
Backend: Giving tips
--------------------

Tips are a way for websites to give small amounts of e-cash to visitors (for
example as a financial reward for providing information or watching
advertisements).  Tips are non-contractual: neither merchant nor consumer
have any contractual information about the other party as a result of the
tip.


Create reserve
--------------

Reserves are basically funds a merchant has provided
to an exchange for a tipping campaign. Each reserve
has a limited lifetime (say 2--4 weeks). Any funds
not used to tip customers will automatically be wired
back from the exchange to the originating account.

To begin tipping, a merchant must tell the backend
to set up a reserve. The backend will return a
reserve public key which must be used as the wire
transfer subject when wiring the tipping campaign
funds to the exchange.

.. _tips:
.. http:post:: [/instances/$INSTANCE]/private/reserves

  Create a reserve for tipping.

  This request is **not** idempotent.  However, while repeating
  it will create another reserve, that is generally pretty harmless
  (assuming only one of the reserves is filled with a wire transfer).
  Clients may want to eventually delete the unused reserves to
  avoid clutter.

  **Request:**

  The request body is a `ReserveCreateRequest` object.

  **Response:**

  :http:statuscode:`200 OK`:
    The backend is waiting for the reserve to be established. The merchant
    must now perform the wire transfer indicated in the `ReserveCreateConfirmation`.
  :http:statuscode:`408 Request timeout`:
    The exchange did not respond on time.
  :http:statuscode:`409 Conflict`:
    The exchange does not support the requested wire method.
  :http:statuscode:`502 Bad gateway`:
    We could not obtain ``/wire`` details from the specified exchange base URL.
  :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:: ReserveCreateRequest

    interface ReserveCreateRequest {
      // Amount that the merchant promises to put into the reserve.
      initial_balance: Amount;

      // Exchange the merchant intends to use for tipping.
      exchange_url: string;

      // Desired wire method, for example "iban" or "x-taler-bank".
      wire_method: string;
    }

  .. ts:def:: ReserveCreateConfirmation

    interface ReserveCreateConfirmation {
      // Public key identifying the reserve.
      reserve_pub: EddsaPublicKey;

      // Wire account of the exchange where to transfer the funds.
      payto_uri: string;
    }

.. http:get:: [/instances/$INSTANCE]/private/reserves

  Obtain list of reserves that have been created for tipping.

  **Request:**

  :query after: *Optional*.  Only return reserves created after the given timestamp in milliseconds.
  :query active: *Optional*.  Only return active/inactive reserves depending on the boolean given.
  :query failures: *Optional*.  Only return reserves where we disagree with the exchange about the initial balance.

  **Response:**

  :http:statuscode:`200 OK`:
    Returns a list of known tipping reserves.
    The body is a `TippingReserveStatus`.

  .. ts:def:: TippingReserveStatus

    interface TippingReserveStatus {
      // Array of all known reserves (possibly empty!).
      reserves: ReserveStatusEntry[];
    }

  .. ts:def:: ReserveStatusEntry

     interface ReserveStatusEntry {
      // Public key of the reserve.
      reserve_pub: EddsaPublicKey;

      // Timestamp when it was established.
      creation_time: Timestamp;

      // Timestamp when it expires.
      expiration_time: Timestamp;

      // Initial amount as per reserve creation call.
      merchant_initial_amount: Amount;

      // Initial amount as per exchange, 0 if exchange did
      // not confirm reserve creation yet.
      exchange_initial_amount: Amount;

      // Amount picked up so far.
      pickup_amount: Amount;

      // Amount approved for tips that exceeds the pickup_amount.
      committed_amount: Amount;

      // Is this reserve active (false if it was deleted but not purged)?
      active: boolean;
    }


Query funds remaining
---------------------

.. http:get:: [/instances/$INSTANCE]/private/reserves/$RESERVE_PUB

  Obtain information about a specific reserve that have been created for tipping.

  **Request:**

  :query tips: *Optional*. If set to "yes", returns also information about all of the tips created.

  **Response:**

  :http:statuscode:`200 OK`:
    Returns the `ReserveDetail`.
  :http:statuscode:`404 Not found`:
    The tipping reserve is not known.
  :http:statuscode:`502 Bad gateway`:
    We are having trouble with the request because of a problem with the exchange.
    Likely returned with an "exchange_code" in addition to a "code" and
    an "exchange_http_status" in addition to our own HTTP status. Also usually
    includes the full exchange reply to our request under "exchange_reply".
    This is only returned if there was actual trouble with the exchange, not
    if the exchange merely did not respond yet or if it responded that the
    reserve was not yet filled.
  :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:: ReserveDetail

    interface ReserveDetail {
      // Timestamp when it was established.
      creation_time: Timestamp;

      // Timestamp when it expires.
      expiration_time: Timestamp;

      // Initial amount as per reserve creation call.
      merchant_initial_amount: Amount;

      // Initial amount as per exchange, 0 if exchange did
      // not confirm reserve creation yet.
      exchange_initial_amount: Amount;

      // Amount picked up so far.
      pickup_amount: Amount;

      // Amount approved for tips that exceeds the pickup_amount.
      committed_amount: Amount;

      // Array of all tips created by this reserves (possibly empty!).
      // Only present if asked for explicitly.
      tips?: TipStatusEntry[];

      // Is this reserve active (false if it was deleted but not purged)?
      active: boolean;

      // URI to use to fill the reserve, can be NULL
      // if the reserve is inactive or was already filled
      payto_uri: string;

      // URL of the exchange hosting the reserve,
      // NULL if the reserve is inactive
      exchange_url: string;
    }

  .. ts:def:: TipStatusEntry

    interface TipStatusEntry {

      // Unique identifier for the tip.
      tip_id: HashCode;

      // Total amount of the tip that can be withdrawn.
      total_amount: Amount;

      // Human-readable reason for why the tip was granted.
      reason: string;
    }


Authorizing tips
----------------

.. http:post:: [/instances/$INSTANCE]/private/reserves/$RESERVE_PUB/authorize-tip

  Authorize creation of a tip from the given reserve.

  **Request:**

  The request body is a `TipCreateRequest` object.

  **Response:**

  :http:statuscode:`200 OK`:
    A tip has been created. The backend responds with a `TipCreateConfirmation`.
  :http:statuscode:`404 Not found`:
    The instance or the reserve is unknown to the backend.
  :http:statuscode:`412 Precondition failed`:
    The tip amount requested exceeds the available reserve balance for tipping.

  .. ts:def:: TipCreateRequest

    interface TipCreateRequest {
      // Amount that the customer should be tipped.
      amount: Amount;

      // Justification for giving the tip.
      justification: string;

      // URL that the user should be directed to after tipping,
      // will be included in the tip_token.
      next_url: string;
    }

  .. ts:def:: TipCreateConfirmation

    interface TipCreateConfirmation {
      // Unique tip identifier for the tip that was created.
      tip_id: HashCode;

      // taler://tip URI for the tip.
      taler_tip_uri: string;

      // URL that will directly trigger processing
      // the tip when the browser is redirected to it.
      tip_status_url: string;

      // When does the tip expire?
      tip_expiration: Timestamp;
    }


.. http:post:: [/instances/$INSTANCE]/private/tips

  Authorize creation of a tip from the given reserve, except with
  automatic selection of a working reserve of the instance by the
  backend. Intentionally otherwise identical to the ``/authorize-tip``
  endpoint given above.

  **Request:**

  The request body is a `TipCreateRequest` object.

  **Response:**

  :http:statuscode:`200 OK`:
    A tip has been created. The backend responds with a `TipCreateConfirmation`.
  :http:statuscode:`404 Not found`:
    The instance is unknown to the backend.
  :http:statuscode:`412 Precondition failed`:
    The tip amount requested exceeds the available reserve balance for tipping
    in all of the reserves of the instance.


Deleting reserves
-----------------

.. http:delete:: [/instances/$INSTANCE]/private/reserves/$RESERVE_PUB

  Delete information about a reserve.  Fails if the reserve still has
  committed to tips that were not yet picked up and that have not yet
  expired.

  **Request:**

  :query purge: *Optional*. If set to YES, the reserve and all information
      about tips it issued will be fully deleted.
      Otherwise only the private key would be deleted.

  **Response:**

  :http:statuscode:`204 No content`:
    The backend has successfully deleted the reserve.
  :http:statuscode:`404 Not found`:
    The backend does not know the instance or the reserve.
  :http:statuscode:`409 Conflict`:
    The backend refuses to delete the reserve (committed tips awaiting pickup).


Checking tip status
-------------------

.. http:get:: [/instances/$INSTANCE]/private/tips/$TIP_ID

  Obtain information about a particular tip.

  **Request:**

  :query pickups: If set to "yes", returns also information about all of the pickups.

  **Response:**

  :http:statuscode:`200 OK`:
    The tip is known. The backend responds with a `TipDetails` message.
  :http:statuscode:`404 Not found`:
    The tip is unknown to the backend.

  .. ts:def:: TipDetails

    interface TipDetails {
      // Amount that we authorized for this tip.
      total_authorized: Amount;

      // Amount that was picked up by the user already.
      total_picked_up: Amount;

      // Human-readable reason given when authorizing the tip.
      reason: string;

      // Timestamp indicating when the tip is set to expire (may be in the past).
      expiration: Timestamp;

      // Reserve public key from which the tip is funded.
      reserve_pub: EddsaPublicKey;

      // Array showing the pickup operations of the wallet (possibly empty!).
      // Only present if asked for explicitly.
      pickups?: PickupDetail[];
    }

  .. ts:def:: PickupDetail

    interface PickupDetail {
      // Unique identifier for the pickup operation.
      pickup_id: HashCode;

      // Number of planchets involved.
      num_planchets: Integer;

      // Total amount requested for this pickup_id.
      requested_amount: Amount;
    }


.. http:get:: [/instances/$INSTANCES]/private/tips

  Return the list of all tips.

  **Request:**

  :query include_expired: *Optional*. If set to "yes", the result includes expired tips also. Otherwise, only active tips are returned.

  :query limit: *Optional*. At most return the given number of results. Negative for descending in database row id, positive for ascending in database row id.

  :query offset: *Optional*. Starting ``row_id`` for an iteration.

  **Response:**

  :http:statuscode:`200 OK`:
    The backend has successfully found the list of tips. The backend responds
    with a `TipsResponse`.

  .. ts:def:: TipsResponse

    interface TipsResponse {

      // List of tips that are present in the backend.
      tips: Tip[];
    }

  .. ts:def:: Tip

    interface Tip {

      // ID of the tip in the backend database.
      row_id: number;

      // Unique identifier for the tip.
      tip_id: HashCode;

      // (Remaining) amount of the tip (including fees).
      tip_amount: Amount;
    }



------------------
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;

    // Total price for the transaction.
    // The exchange will subtract deposit fees from that amount
    // before transferring it to the merchant.
    amount: Amount;

    // The URL for this purchase.  Every time it is visited, the merchant
    // will send back to the customer the same proposal.
    // The URL should be bookmarkable.
    // Either fulfillment_url or fulfillment_message must be specified.
    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.
    max_fee: Amount;

    // 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.
    max_wire_fee: Amount;

    // 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.
    wire_fee_amortization: number;

    // 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 contact.
    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;

    // Any exchanges audited by these auditors are accepted by the merchant.
    auditors: Auditor[];

    // 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.
    extra?: any;
  }

The wallet must select a 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 {
    // Label for a location with the business address of the merchant.
    address: Location;

    // The merchant's legal name of business.
    name: string;

    // 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;

    // 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 <private-order-data-cleanup>`.)