merchant.go (13930B)
1 package merchant 2 3 import ( 4 "bytes" 5 "context" 6 "encoding/json" 7 "errors" 8 "fmt" 9 "io" 10 "net/http" 11 "net/url" 12 "strings" 13 "time" 14 15 "github.com/schanzen/taler-go/pkg/util" 16 ) 17 18 type MerchantConfig struct { 19 // Default currency 20 Currency string `json:"currency"` 21 22 // Supported currencies 23 Currencies map[string]util.CurrencySpecification `json:"currencies"` 24 25 // Name 26 Name string `json:"name"` 27 28 // Version string 29 Version string `json:"version"` 30 } 31 32 // Timestamp is an absolute time as the merchant API encodes it: 33 // {"t_s": seconds since the epoch}. 34 type Timestamp struct { 35 Seconds int64 `json:"t_s"` 36 } 37 38 // TimestampOf converts t to a Timestamp, truncating to whole seconds. 39 func TimestampOf(t time.Time) *Timestamp { 40 return &Timestamp{Seconds: t.Unix()} 41 } 42 43 // RelativeTime is a duration as the merchant API encodes it: 44 // {"d_us": microseconds}. 45 type RelativeTime struct { 46 Microseconds int64 `json:"d_us"` 47 } 48 49 // RelativeTimeOf converts d to a RelativeTime. 50 func RelativeTimeOf(d time.Duration) *RelativeTime { 51 return &RelativeTime{Microseconds: d.Microseconds()} 52 } 53 54 type PostOrderRequest struct { 55 // The order must at least contain the minimal 56 // order detail, but can override all. 57 Order CommonOrder `json:"order"` 58 59 // If set, the backend will then set the refund deadline to the current 60 // time plus the specified delay. If it's not set, refunds will not be 61 // possible. 62 RefundDelay *RelativeTime `json:"refund_delay,omitempty"` 63 64 // Specifies the payment target preferred by the client. Can be used 65 // to select among the various (active) wire methods supported by the instance. 66 PaymentTarget string `json:"payment_target,omitempty"` 67 68 // Specifies that some products are to be included in the 69 // order from the inventory. For these inventory management 70 // is performed (so the products must be in stock) and 71 // details are completed from the product data of the backend. 72 // FIXME: Not sure we actually need this for now 73 //InventoryProducts []MinimalInventoryProduct `json:"inventory_products,omitempty"` 74 75 // Specifies a lock identifier that was used to 76 // lock a product in the inventory. Only useful if 77 // inventory_products is set. Used in case a frontend 78 // reserved quantities of the individual products while 79 // the shopping cart was being built. Multiple UUIDs can 80 // be used in case different UUIDs were used for different 81 // products (i.e. in case the user started with multiple 82 // shopping sessions that were combined during checkout). 83 LockUuids []string `json:"lock_uuids,omitempty"` 84 85 // Should a token for claiming the order be generated? 86 // False can make sense if the ORDER_ID is sufficiently 87 // high entropy to prevent adversarial claims (like it is 88 // if the backend auto-generates one). Default is 'true'. 89 // A pointer, so that false is sent; omitempty would drop a plain false. 90 CreateToken *bool `json:"create_token,omitempty"` 91 } 92 93 type CommonOrder struct { 94 // Total price for the transaction. The exchange will subtract deposit 95 // fees from that amount before transferring it to the merchant. 96 Amount string `json:"amount"` 97 98 // Maximum total deposit fee accepted by the merchant for this contract. 99 // Overrides defaults of the merchant instance. 100 MaxFee string `json:"max_fee,omitempty"` 101 102 // Human-readable description of the whole purchase. 103 Summary string `json:"summary"` 104 105 // Map from IETF BCP 47 language tags to localized summaries. 106 SummaryI18n string `json:"summary_i18n,omitempty"` 107 108 // Unique identifier for the order. Only characters 109 // allowed are "A-Za-z0-9" and ".:_-". 110 // Must be unique within a merchant instance. 111 // For merchants that do not store proposals in their DB 112 // before the customer paid for them, the order_id can be used 113 // by the frontend to restore a proposal from the information 114 // encoded in it (such as a short product identifier and timestamp). 115 OrderId string `json:"order_id,omitempty"` 116 117 // URL where the same contract could be ordered again (if 118 // available). Returned also at the public order endpoint 119 // for people other than the actual buyer (hence public, 120 // in case order IDs are guessable). 121 PublicReorderUrl string `json:"public_reorder_url,omitempty"` 122 123 // See documentation of fulfillment_url field in ContractTerms. 124 // Either fulfillment_url or fulfillment_message must be specified. 125 // When creating an order, the fulfillment URL can 126 // contain ${ORDER_ID} which will be substituted with the 127 // order ID of the newly created order. 128 FulfillmentUrl string `json:"fulfillment_url,omitempty"` 129 130 // See documentation of fulfillment_message in ContractTerms. 131 // Either fulfillment_url or fulfillment_message must be specified. 132 FulfillmentMessage string `json:"fulfillment_message,omitempty"` 133 134 // Map from IETF BCP 47 language tags to localized fulfillment 135 // messages. 136 FulfillmentMessageI18n string `json:"fulfillment_message_i18n,omitempty"` 137 138 // Minimum age the buyer must have to buy. 139 MinimumAge *uint64 `json:"minimum_age,omitempty"` 140 141 // List of products that are part of the purchase. 142 //products?: Product[]; 143 144 // Time when this contract was generated. If null, defaults to current 145 // time of merchant backend. 146 Timestamp *Timestamp `json:"timestamp,omitempty"` 147 148 // After this deadline has passed, no refunds will be accepted. 149 // Overrides deadline calculated from refund_delay in 150 // PostOrderRequest. 151 RefundDeadline *Timestamp `json:"refund_deadline,omitempty"` 152 153 // After this deadline, the merchant won't accept payments for the contract. 154 // Overrides deadline calculated from default pay delay configured in 155 // merchant backend. 156 PayDeadline *Timestamp `json:"pay_deadline,omitempty"` 157 158 // Transfer deadline for the exchange. Must be in the deposit permissions 159 // of coins used to pay for this order. 160 // Overrides deadline calculated from default wire transfer delay 161 // configured in merchant backend. Must be after refund deadline. 162 WireTransferDeadline *Timestamp `json:"wire_transfer_deadline,omitempty"` 163 164 // Base URL of the (public!) merchant backend API. 165 // Must be an absolute URL that ends with a slash. 166 // Defaults to the base URL this request was made to. 167 MerchantBaseUrl string `json:"merchant_base_url,omitempty"` 168 169 // Delivery location for (all!) products. 170 //DeliveryLocation?: Location; 171 172 // Time indicating when the order should be delivered. 173 // May be overwritten by individual products. 174 // Must be in the future. 175 DeliveryDate *Timestamp `json:"delivery_date,omitempty"` 176 177 // See documentation of auto_refund in ContractTerms. 178 // Specifies for how long the wallet should try to get an 179 // automatic refund for the purchase. 180 AutoRefund *RelativeTime `json:"auto_refund,omitempty"` 181 182 // Extra data that is only interpreted by the merchant frontend. 183 // Useful when the merchant needs to store extra information on a 184 // contract without storing it separately in their database. 185 // Must really be an Object (not a string, integer, float or array). 186 Extra json.RawMessage `json:"extra,omitempty"` 187 } 188 189 // NOTE: Part of the above but optional 190 type FulfillmentMetadata struct { 191 // See documentation of fulfillment_url in ContractTerms. 192 // Either fulfillment_url or fulfillment_message must be specified. 193 FulfillmentUrl string `json:"fulfillment_url,omitempty"` 194 195 // See documentation of fulfillment_message in ContractTerms. 196 // Either fulfillment_url or fulfillment_message must be specified. 197 FulfillmentMessage string `json:"fulfillment_message,omitempty"` 198 } 199 200 type PostOrderResponse struct { 201 // Order ID of the response that was just created. 202 OrderId string `json:"order_id"` 203 } 204 205 type PostOrderResponseToken struct { 206 // Token that authorizes the wallet to claim the order. 207 // Provided only if "create_token" was set to 'true' 208 // in the request. 209 Token string 210 } 211 212 type CheckPaymentStatusResponse struct { 213 // Status of the order 214 OrderStatus string `json:"order_status"` 215 } 216 217 type CheckPaymentPaytoResponse struct { 218 // Status of the order 219 TalerPayUri string `json:"taler_pay_uri"` 220 } 221 222 type Merchant struct { 223 224 // The host of this merchant 225 BaseUrlPrivate string 226 227 // The access token to use for the private API 228 AccessToken string 229 230 // HTTPClient sends the requests. When it is nil, a client whose 231 // requests time out after DefaultTimeout is used. 232 HTTPClient *http.Client 233 } 234 235 // DefaultTimeout limits each request when Merchant.HTTPClient is nil. 236 const DefaultTimeout = 30 * time.Second 237 238 var defaultClient = &http.Client{Timeout: DefaultTimeout} 239 240 func NewMerchant(merchBaseUrlPrivate string, merchAccessToken string) Merchant { 241 return Merchant{ 242 BaseUrlPrivate: merchBaseUrlPrivate, 243 AccessToken: merchAccessToken, 244 } 245 } 246 247 func (m *Merchant) client() *http.Client { 248 if m.HTTPClient != nil { 249 return m.HTTPClient 250 } 251 return defaultClient 252 } 253 254 // authorization is the Authorization header value for the private API. 255 // AccessToken may be given with or without its "secret-token:" prefix. 256 func (m *Merchant) authorization() string { 257 if strings.HasPrefix(m.AccessToken, secretTokenPrefix) { 258 return "Bearer " + m.AccessToken 259 } 260 return "Bearer " + secretTokenPrefix + m.AccessToken 261 } 262 263 const secretTokenPrefix = "secret-token:" 264 265 type PaymentStatus string 266 267 const ( 268 OrderStatusUnknown = "" 269 OrderPaid = "paid" 270 OrderUnpaid = "unpaid" 271 OrderClaimed = "claimed" 272 ) 273 274 func (m *Merchant) IsOrderPaid(orderId string) (int, PaymentStatus, string, error) { 275 return m.IsOrderPaidContext(context.Background(), orderId) 276 } 277 278 // IsOrderPaidContext is IsOrderPaid with a context that can cancel the 279 // request or limit its duration. 280 func (m *Merchant) IsOrderPaidContext(ctx context.Context, orderId string) (int, PaymentStatus, string, error) { 281 var orderPaidResponse CheckPaymentStatusResponse 282 var paytoResponse CheckPaymentPaytoResponse 283 req, err := http.NewRequestWithContext(ctx, "GET", m.BaseUrlPrivate+"/private/orders/"+url.PathEscape(orderId), nil) 284 if err != nil { 285 return 0, OrderStatusUnknown, "", err 286 } 287 req.Header.Set("Authorization", m.authorization()) 288 resp, err := m.client().Do(req) 289 if nil != err { 290 // resp is nil when the request failed; there is no status code. 291 return 0, OrderStatusUnknown, "", err 292 } 293 defer resp.Body.Close() 294 if http.StatusOK != resp.StatusCode { 295 message := fmt.Sprintf("Expected response code %d. Got %d", http.StatusOK, resp.StatusCode) 296 return resp.StatusCode, OrderStatusUnknown, "", errors.New(message) 297 } 298 respData, err := io.ReadAll(resp.Body) 299 if err != nil { 300 return resp.StatusCode, OrderStatusUnknown, "", err 301 } 302 err = json.NewDecoder(bytes.NewReader(respData)).Decode(&orderPaidResponse) 303 if err != nil { 304 return resp.StatusCode, OrderStatusUnknown, "", err 305 } 306 if orderPaidResponse.OrderStatus == "unpaid" { 307 err = json.NewDecoder(bytes.NewReader(respData)).Decode(&paytoResponse) 308 return resp.StatusCode, PaymentStatus(orderPaidResponse.OrderStatus), paytoResponse.TalerPayUri, err 309 } 310 return resp.StatusCode, PaymentStatus(orderPaidResponse.OrderStatus), "", nil 311 } 312 313 func (m *Merchant) GetConfig() (*MerchantConfig, error) { 314 return m.GetConfigContext(context.Background()) 315 } 316 317 // GetConfigContext is GetConfig with a context that can cancel the request 318 // or limit its duration. 319 func (m *Merchant) GetConfigContext(ctx context.Context) (*MerchantConfig, error) { 320 var configResponse MerchantConfig 321 req, err := http.NewRequestWithContext(ctx, "GET", m.BaseUrlPrivate+"/config", nil) 322 if err != nil { 323 return nil, err 324 } 325 resp, err := m.client().Do(req) 326 if nil != err { 327 return nil, err 328 } 329 defer resp.Body.Close() 330 if http.StatusOK != resp.StatusCode { 331 message := fmt.Sprintf("Expected response code %d. Got %d", http.StatusOK, resp.StatusCode) 332 return nil, errors.New(message) 333 } 334 respData, err := io.ReadAll(resp.Body) 335 if err != nil { 336 return nil, err 337 } 338 err = json.NewDecoder(bytes.NewReader(respData)).Decode(&configResponse) 339 if err != nil { 340 return nil, err 341 } 342 return &configResponse, nil 343 } 344 345 // ErrOrderExists is returned by CreateOrder when the backend already has an 346 // order with the requested OrderId (HTTP 409 Conflict). A caller that 347 // chooses its own order IDs can treat it as success when it retries a 348 // creation whose answer it never received. 349 var ErrOrderExists = errors.New("merchant: an order with this ID already exists") 350 351 func (m *Merchant) CreateOrder(order CommonOrder) (string, error) { 352 return m.CreateOrderContext(context.Background(), order) 353 } 354 355 // CreateOrderContext is CreateOrder with a context that can cancel the 356 // request or limit its duration. 357 func (m *Merchant) CreateOrderContext(ctx context.Context, order CommonOrder) (string, error) { 358 var newOrder PostOrderRequest 359 newOrder.Order = order 360 return m.postOrder(ctx, newOrder) 361 } 362 363 func (m *Merchant) postOrder(ctx context.Context, newOrder PostOrderRequest) (string, error) { 364 var orderResponse PostOrderResponse 365 reqString, err := json.Marshal(newOrder) 366 if nil != err { 367 return "", err 368 } 369 req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.BaseUrlPrivate+"/private/orders", bytes.NewReader(reqString)) 370 if err != nil { 371 return "", err 372 } 373 req.Header.Set("Authorization", m.authorization()) 374 resp, err := m.client().Do(req) 375 376 if nil != err { 377 return "", err 378 } 379 defer resp.Body.Close() 380 if http.StatusConflict == resp.StatusCode { 381 return newOrder.Order.OrderId, ErrOrderExists 382 } 383 if http.StatusOK != resp.StatusCode { 384 message := fmt.Sprintf("Expected response code %d. Got %d. With request %s", http.StatusOK, resp.StatusCode, reqString) 385 return "", errors.New(message) 386 } 387 err = json.NewDecoder(resp.Body).Decode(&orderResponse) 388 return orderResponse.OrderId, err 389 } 390 391 func (m *Merchant) AddNewOrder(cost util.Amount, summary string, fulfillment_url string) (string, error) { 392 var newOrder PostOrderRequest 393 var orderDetail CommonOrder 394 orderDetail.Amount = cost.String() 395 // FIXME get from cfg 396 orderDetail.Summary = summary 397 orderDetail.FulfillmentUrl = fulfillment_url 398 newOrder.Order = orderDetail 399 return m.postOrder(context.Background(), newOrder) 400 }