lunixi-sdk 1.3.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +35 -0
  3. data/README.md +44 -9
  4. data/README.tr.md +39 -8
  5. data/docs/card-rewards.md +21 -0
  6. data/docs/ruby.en.md +11 -1
  7. data/docs/ruby.tr.md +11 -1
  8. data/lib/lunixi/bank_connect.rb +132 -15
  9. data/lib/lunixi/bank_connect_filters.rb +13 -3
  10. data/lib/lunixi/bank_connect_pos.rb +165 -0
  11. data/lib/lunixi/bank_connect_values.rb +127 -5
  12. data/lib/lunixi/card_requests.rb +34 -5
  13. data/lib/lunixi/client.rb +15 -8
  14. data/lib/lunixi/direct_method_payment_request.rb +27 -3
  15. data/lib/lunixi/fraud.rb +3 -2
  16. data/lib/lunixi/fraud_uk_claims.rb +127 -0
  17. data/lib/lunixi/fraud_values.rb +46 -0
  18. data/lib/lunixi/marketplace.rb +8 -2
  19. data/lib/lunixi/order_details.rb +115 -0
  20. data/lib/lunixi/payment_link_rules.rb +13 -1
  21. data/lib/lunixi/payment_link_values.rb +9 -3
  22. data/lib/lunixi/payment_links.rb +3 -1
  23. data/lib/lunixi/payment_values.rb +22 -2
  24. data/lib/lunixi/payments.rb +45 -9
  25. data/lib/lunixi/product_webhooks.rb +17 -1
  26. data/lib/lunixi/route_table.rb +10 -5
  27. data/lib/lunixi/routing_pin.rb +247 -0
  28. data/lib/lunixi/sanction.rb +77 -17
  29. data/lib/lunixi/sanction_batch.rb +215 -0
  30. data/lib/lunixi/sanction_values.rb +289 -5
  31. data/lib/lunixi/split_payment.rb +22 -2
  32. data/lib/lunixi/subscription_resources.rb +3 -1
  33. data/lib/lunixi/subscription_routing.rb +70 -0
  34. data/lib/lunixi/subscription_values.rb +40 -4
  35. data/lib/lunixi/subscriptions.rb +22 -2
  36. data/lib/lunixi/version.rb +1 -1
  37. data/lib/lunixi/wallet_resources.rb +7 -2
  38. data/lib/lunixi/wallet_routes.rb +5 -2
  39. data/lib/lunixi.rb +7 -0
  40. metadata +9 -1
@@ -49,10 +49,11 @@ module Lunixi
49
49
  bin_or_pan!(data['binOrPan']) unless data['binOrPan'].nil?
50
50
  installment!(data['installment']) unless data['installment'].nil?
51
51
  data['enabledInstallments'] = EnabledInstallments.check!(data['enabledInstallments']) if data.key?('enabledInstallments')
52
- data
52
+ RoutingPin.field!(data)
53
53
  end
54
54
 
55
- # Body of POST /api/v1/payments/cards: card, cardUserKey, an HTTPS callbackUrl and an optional currency.
55
+ # Body of POST /api/v1/payments/cards: card, cardUserKey, an HTTPS callbackUrl, the buyer and the
56
+ # billing address (OrderDetails, no basket) and an optional currency.
56
57
  def store_card_body!(body)
57
58
  data = plain!(body, 'Store card request')
58
59
  raise ConfigurationError, 'Store card request requires the card object' unless data['card'].is_a?(Hash) && !data['card'].empty?
@@ -60,7 +61,7 @@ module Lunixi
60
61
  text!(data['cardUserKey'], 'cardUserKey')
61
62
  callback_url!(data['callbackUrl'])
62
63
  currency!(data['currency']) unless data['currency'].nil?
63
- data
64
+ OrderDetails.check!(data, 'Storing a card', basket: false)
64
65
  end
65
66
 
66
67
  def callback_url!(url)
@@ -115,6 +116,14 @@ module Lunixi
115
116
  self
116
117
  end
117
118
 
119
+ # The same routing you will charge with: the table is computed for the pinned target (STRICT: only
120
+ # the installments it is authorized for) and the quote token is bound to the pin; another pin
121
+ # answers 422 installment.quote.pin_mismatch.
122
+ def with_routing(value)
123
+ @payload['routing'] = RoutingPin.pin!(value)
124
+ self
125
+ end
126
+
118
127
  def to_h
119
128
  @payload.dup
120
129
  end
@@ -124,8 +133,8 @@ module Lunixi
124
133
  end
125
134
  end
126
135
 
127
- # Body of payments.store_card (verify and store a card for cardUserKey). Its inspect output never
128
- # shows the card.
136
+ # Body of payments.store_card (verify and store a card for cardUserKey). with_buyer and
137
+ # with_billing_address are required (no basket). Its inspect output never shows the card.
129
138
  class StoreCardRequest
130
139
  def initialize(card, card_user_key, callback_url)
131
140
  raise ConfigurationError, 'card must be an object' unless card.is_a?(Hash) && !card.empty?
@@ -139,6 +148,18 @@ module Lunixi
139
148
  self
140
149
  end
141
150
 
151
+ # The card holder as the buyer (required; BUYER_REQUIRED_FIELDS).
152
+ def with_buyer(value)
153
+ @payload['buyer'] = object!(value, 'buyer')
154
+ self
155
+ end
156
+
157
+ # The billing address (required; ADDRESS_REQUIRED_FIELDS).
158
+ def with_billing_address(value)
159
+ @payload['billingAddress'] = object!(value, 'billingAddress')
160
+ self
161
+ end
162
+
142
163
  def to_h
143
164
  @payload.dup
144
165
  end
@@ -146,5 +167,13 @@ module Lunixi
146
167
  def inspect
147
168
  "#<#{self.class.name} card=[REDACTED]>"
148
169
  end
170
+
171
+ private
172
+
173
+ def object!(value, field)
174
+ raise ConfigurationError, "#{field} must be an object" unless value.is_a?(Hash)
175
+
176
+ JSON.parse(JsonBody.dump(value))
177
+ end
149
178
  end
150
179
  end
data/lib/lunixi/client.rb CHANGED
@@ -5,7 +5,7 @@ require 'time'
5
5
 
6
6
  module Lunixi
7
7
  # Thread-safe server-side gateway client. Responses retain the gateway envelope.
8
- class Client
8
+ class Client # rubocop:disable Metrics/ClassLength -- one entry point for every product client
9
9
  AUTH_PATH = '/api/v1/auth/token'
10
10
  METHODS = %w[GET HEAD POST PUT PATCH DELETE].freeze
11
11
  ACCEPT_JSON = 'application/json'
@@ -39,7 +39,8 @@ module Lunixi
39
39
  @physical_pos_management = PhysicalPosManagement.new(physical_pos_gateway)
40
40
  @wallet = Wallet.new(self)
41
41
  @bank_connect = BankConnect.new(self, max_retries: max_retries, backoff: ->(attempt) { pause(attempt, {}) })
42
- @sanction = Sanction.new(self)
42
+ # The transport also carries the bulk screening file part PUTs to storage, outside Client#request.
43
+ @sanction = Sanction.new(self, storage_transport: @transport)
43
44
  @insurance = Insurance.new(self)
44
45
  @subscriptions = Subscriptions.new(self)
45
46
  @kyc = Kyc.new(self)
@@ -51,8 +52,10 @@ module Lunixi
51
52
  # not invent field schemas, interpret financial results or retry an unsafe POST. With binary: true a
52
53
  # 2xx body is returned as frozen bytes; accept: names the media types the endpoint answers with.
53
54
  # max_retries: lowers the client's retry budget for this call (0 sends a single attempt).
54
- def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false, accept: ACCEPT_JSON,
55
- max_retries: nil)
55
+ # actor_id is sent as X-Actor-Id: the person in your organization acting, on endpoints that record a
56
+ # person's action (validated by the operation that needs it).
57
+ def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false, accept: ACCEPT_JSON, # rubocop:disable Metrics/ParameterLists -- transport options are keyword arguments
58
+ max_retries: nil, actor_id: nil)
56
59
  method = method.to_s.upcase
57
60
  raise ConfigurationError, 'Unsupported HTTP method' unless METHODS.include?(method)
58
61
  raise ConfigurationError, 'GET and HEAD cannot have a body' if %w[GET HEAD].include?(method) && !body.nil?
@@ -69,7 +72,9 @@ module Lunixi
69
72
  bytes = body.nil? ? nil : JsonBody.dump(body)
70
73
  raise ConfigurationError, 'Request body exceeds the size limit' if bytes && bytes.bytesize > 1024 * 1024
71
74
 
72
- perform_request(method, path, bytes, key, signed, binary, accept, retries)
75
+ raise ConfigurationError, 'Invalid X-Actor-Id' unless actor_id.nil? || actor_id.match?(/\A[A-Za-z0-9._@+-]{1,64}\z/)
76
+
77
+ perform_request(method, path, bytes, key, signed, binary, accept, retries, actor_id)
73
78
  end
74
79
 
75
80
  # Validates caller-owned durable keys; a generated key on every retry is unsafe.
@@ -95,6 +100,7 @@ module Lunixi
95
100
  return RouteRequest.printable_idempotency_key!(key) if path.match?(RouteRequest::PRINTABLE_KEY_ROUTE)
96
101
  return WalletInvoker.idempotency_key!(key) if path.match?(WalletInvoker::ROUTE)
97
102
  return RouteTable.idempotency_key!(key) if path.match?(RouteTable::KEY_ROUTE)
103
+ return Sanction.screening_key!(key) if path.match?(Sanction::SCREENING_ROUTE)
98
104
 
99
105
  self.class.idempotency_key!(key)
100
106
  end
@@ -106,13 +112,13 @@ module Lunixi
106
112
  max_retries
107
113
  end
108
114
 
109
- def perform_request(method, path, bytes, key, signed, binary, accept, max_retries)
115
+ def perform_request(method, path, bytes, key, signed, binary, accept, max_retries, actor_id = nil)
110
116
  safe_to_retry = %w[GET HEAD].include?(method) || !key.nil?
111
117
  retries = 0
112
118
  reauthenticated = false
113
119
  loop do
114
120
  token = access_token
115
- response = transmit(method, path, bytes, key, token, signed, accept)
121
+ response = transmit(method, path, bytes, key, token, signed, accept, actor_id)
116
122
  if response.status == 401 && !reauthenticated && safe_to_retry
117
123
  invalidate_token(token)
118
124
  reauthenticated = true
@@ -188,11 +194,12 @@ module Lunixi
188
194
  headers
189
195
  end
190
196
 
191
- def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON)
197
+ def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON, actor_id = nil)
192
198
  headers = { 'Accept' => accept, 'User-Agent' => "lunixi-sdk-ruby/#{VERSION}" }
193
199
  headers['Authorization'] = "Bearer #{token}" if token
194
200
  headers['Content-Type'] = 'application/json' unless body.nil?
195
201
  headers['Idempotency-Key'] = key if key
202
+ headers['X-Actor-Id'] = actor_id if actor_id
196
203
  headers.merge!(signed_headers(method, path, body)) if signed
197
204
  response = @transport.call(method: method, uri: URI.parse(@origin + path), headers: headers.freeze, body: body)
198
205
  unless response.is_a?(Response) && response.status.is_a?(Integer) && response.headers.is_a?(Hash) && response.body.is_a?(String)
@@ -4,6 +4,8 @@ module Lunixi
4
4
  # Body of POST /api/v1/payments/direct/payment (payments.direct_method_payment). amount is the order
5
5
  # total as a positive canonical minor-unit string. Choose the method with with_method_fields or
6
6
  # with_card; the provider code and the fields of a method come from payments.list_payment_methods.
7
+ # The order details are required: with_buyer, with_billing_address, with_basket_items (at least one
8
+ # item) and with_shipping_address when an item is PHYSICAL (OrderDetails).
7
9
  class DirectMethodPaymentRequest
8
10
  REQUIRED_FIELDS = %w[paymentMethod amount currency orderId].freeze
9
11
 
@@ -69,6 +71,12 @@ module Lunixi
69
71
  end
70
72
 
71
73
  # Card only. true charges with 3D Secure: the response carries a REDIRECT action.
74
+ # Attach the buyer-approved amount from query_card_rewards.
75
+ def with_card_reward_selection(selection_id, amount_minor)
76
+ @payload['cardRewardSelection'] = { 'selectionId' => text(selection_id, 'selectionId'), 'amountMinor' => Money.minor(amount_minor) }
77
+ self
78
+ end
79
+
72
80
  def with_force3d(value)
73
81
  @payload['force3D'] = boolean(value, 'force3D')
74
82
  self
@@ -121,6 +129,15 @@ module Lunixi
121
129
  assign('metadata', value)
122
130
  end
123
131
 
132
+ # Pins the payment to a provider and/or one of your connections ({ providerCode:, credentialId:,
133
+ # mode: }, RoutingPinMode). Card: STRICT uses only the target (422 payment.routing.pin_not_eligible
134
+ # when it cannot take the payment, nothing is charged); PREFER (default) falls back to normal
135
+ # routing. Other methods: the block's providerCode stays strict and must equal routing.providerCode
136
+ # when both are given; mode applies to the connection choice. Not for BANK_TRANSFER.
137
+ def with_routing(value)
138
+ assign('routing', RoutingPin.pin!(value))
139
+ end
140
+
124
141
  def with_basket_items(items)
125
142
  raise ConfigurationError, 'basketItems must be an array of objects' unless items.is_a?(Array)
126
143
 
@@ -147,13 +164,19 @@ module Lunixi
147
164
  # Checks a direct/payment body (a Hash or the result of to_h) before sending and returns a
148
165
  # string-keyed copy: known fields only, the chosen method's block and no other, card fields only
149
166
  # with CARD, block structure, promissory-note plan, shopping-loan basket, no providerCode for
150
- # BANK_TRANSFER.
151
- def self.payload!(body)
167
+ # BANK_TRANSFER. payments.direct_method_payment also checks the order details (OrderDetails).
168
+ def self.payload!(body) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity -- one check per gateway rule, in gateway order
152
169
  raise ConfigurationError, 'A direct method payment needs a body; use DirectMethodPaymentRequest to build it' unless body.is_a?(Hash)
153
170
 
154
171
  data = JSON.parse(JsonBody.dump(body))
155
172
  raise ConfigurationError, 'Removed amount field; use amount in integer minor units' if %w[price paidPrice].any? { |key| data.key?(key) }
156
173
 
174
+ if data.key?('cardRewardSelection')
175
+ selection = data['cardRewardSelection']
176
+ raise ConfigurationError, 'Invalid reward selection' unless selection.is_a?(Hash) && selection['selectionId'].is_a?(String)
177
+
178
+ Money.minor(selection['amountMinor'])
179
+ end
157
180
  unknown = data.keys - DIRECT_METHOD_PAYMENT_FIELDS
158
181
  raise ConfigurationError, "Unknown direct method payment field(s): #{unknown.join(', ')}" unless unknown.empty?
159
182
 
@@ -170,7 +193,8 @@ module Lunixi
170
193
  %w[preauth force3D].each do |field|
171
194
  raise ConfigurationError, "#{field} must be a JSON boolean" if data.key?(field) && ![true, false].include?(data[field])
172
195
  end
173
- data
196
+ own = method == PaymentMethod::CARD ? nil : data[block_name]
197
+ RoutingPin.field!(data, payment_method: method, block_provider_code: own.is_a?(Hash) ? own['providerCode'] : nil)
174
198
  end
175
199
 
176
200
  # Block name of a method other than card; a method without a block cannot be paid here yet.
data/lib/lunixi/fraud.rb CHANGED
@@ -7,13 +7,14 @@ module Lunixi
7
7
  paymentId payment bankTransfer cryptoTransfer walletOperation billPayment loanApplication payout
8
8
  customer device session merchant mobileApp telemetry metadata identitySnapshot identityAssertion].freeze
9
9
 
10
- # Transaction event ingest (signed) and the persisted decision log.
11
- attr_reader :events, :decisions
10
+ # Transaction event ingest (signed), the persisted decision log and UK APP reimbursement claims.
11
+ attr_reader :events, :decisions, :uk_claims
12
12
 
13
13
  def initialize(client)
14
14
  @client = client
15
15
  @events = FraudEvents.new(client)
16
16
  @decisions = FraudDecisions.new(client)
17
+ @uk_claims = FraudUkClaims.new(client)
17
18
  end
18
19
 
19
20
  # Evaluate the documented fraud DTO; tenant identity comes from credentials.
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'time'
5
+
6
+ module Lunixi
7
+ # UK APP reimbursement claims (POST /api/v1/fraud/uk-claims). Opening a claim is the only claim action
8
+ # available with an API key; the assessment, approval, milestones and clock stops are done in the panel.
9
+ class FraudUkClaims
10
+ PATH = '/api/v1/fraud/uk-claims'
11
+ # X-Actor-Id: the analyst recording the claim.
12
+ ACTOR_ID = /\A[A-Za-z0-9._@+-]{1,64}\z/
13
+ POSITIVE_MINOR = /\A[1-9][0-9]*\z/
14
+ NONNEGATIVE_MINOR = /\A(0|[1-9][0-9]*)\z/
15
+ PAYMENTS_LIMIT = 200
16
+ LINKED_CLAIMS_LIMIT = 20
17
+
18
+ def initialize(client)
19
+ @client = client
20
+ end
21
+
22
+ # Records a UK APP reimbursement claim and returns the claim view (id, caseId, regime, claimState,
23
+ # amounts, deadlines, deadlineAlerts, channel: "api"). Keys are the wire names (UK_CLAIM_FIELDS,
24
+ # UK_CLAIM_PAYMENT_FIELDS); amounts are minor-unit strings and the currency is GBP only.
25
+ #
26
+ # actor_id is sent as X-Actor-Id: the analyst recording the claim. It is required with an API key and
27
+ # is stored as your declaration. Sending the same externalClaimRef again returns the existing claim.
28
+ def open(claim, actor_id:)
29
+ actor = actor!(actor_id)
30
+ body = claim!(claim)
31
+ RouteResponse.unwrap(@client.request('POST', PATH, body: body, signed: false, actor_id: actor))
32
+ end
33
+
34
+ private
35
+
36
+ def actor!(actor_id)
37
+ actor = actor_id.is_a?(String) ? actor_id.strip : ''
38
+ return actor if actor.match?(ACTOR_ID)
39
+
40
+ raise ConfigurationError, 'actor_id (X-Actor-Id) is required: the analyst recording the claim, 1-64 characters of ' \
41
+ 'letters, digits and . _ @ + -'
42
+ end
43
+
44
+ def claim!(claim)
45
+ raise ConfigurationError, 'UK claim must be an object' unless claim.is_a?(Hash)
46
+
47
+ data = JSON.parse(JsonBody.dump(claim))
48
+ unknown!(data, UK_CLAIM_FIELDS, 'UK claim')
49
+ raise ConfigurationError, 'role is required (sending | receiving).' if data['role'].nil?
50
+
51
+ one_of!(data, 'role', UK_CLAIM_ROLES)
52
+ iso!(data['reportedAt'], 'reportedAt')
53
+ one_of!(data, 'payerType', UK_CLAIM_PAYER_TYPES)
54
+ one_of!(data, 'reportedBy', UK_CLAIM_REPORTED_BY)
55
+ one_of!(data, 'scamType', UK_CLAIM_SCAM_TYPES)
56
+ raise ConfigurationError, 'UK reimbursement claims are GBP only.' if data.key?('currency') && data['currency'] != 'GBP'
57
+
58
+ payer!(data)
59
+ payments!(data['payments'])
60
+ data
61
+ end
62
+
63
+ def payer!(data)
64
+ staff = data['payerStaffCount']
65
+ raise ConfigurationError, 'payerStaffCount must be a non-negative integer.' if data.key?('payerStaffCount') && !(staff.is_a?(Integer) && staff >= 0)
66
+
67
+ %w[payerTurnoverOrBalanceEurMinor payerAnnualIncomeGbpMinor].each do |field|
68
+ minor!(data[field], NONNEGATIVE_MINOR, field) if data.key?(field)
69
+ end
70
+ linked = data['linkedClaimIds']
71
+ return unless data.key?('linkedClaimIds') && !(linked.is_a?(Array) && linked.size <= LINKED_CLAIMS_LIMIT)
72
+
73
+ raise ConfigurationError, "linkedClaimIds must be an array of at most #{LINKED_CLAIMS_LIMIT} ids."
74
+ end
75
+
76
+ def payments!(payments)
77
+ unless payments.is_a?(Array) && payments.size.between?(1, PAYMENTS_LIMIT)
78
+ raise ConfigurationError, "payments must be an array of 1 to #{PAYMENTS_LIMIT} payments."
79
+ end
80
+
81
+ payments.each_with_index do |payment, index|
82
+ where = "payments[#{index}]"
83
+ raise ConfigurationError, "#{where} must be an object." unless payment.is_a?(Hash)
84
+
85
+ unknown!(payment, UK_CLAIM_PAYMENT_FIELDS, where)
86
+ iso!(payment['executedAt'], "#{where}.executedAt")
87
+ raise ConfigurationError, "#{where}.amountMinor is required." unless payment.key?('amountMinor')
88
+
89
+ minor!(payment['amountMinor'], POSITIVE_MINOR, "#{where}.amountMinor")
90
+ one_of!(payment, 'scheme', UK_CLAIM_SCHEMES, where)
91
+ end
92
+ end
93
+
94
+ def unknown!(object, allowed, where)
95
+ key = object.keys.find { |name| !allowed.include?(name) }
96
+ raise ConfigurationError, "Unknown #{where} field \"#{key}\"; the gateway rejects it with 400." if key
97
+ end
98
+
99
+ def one_of!(object, field, values, where = nil)
100
+ return unless object.key?(field) && !values.include?(object[field])
101
+
102
+ raise ConfigurationError, "#{[where, field].compact.join('.')} must be one of: #{values.join(', ')}."
103
+ end
104
+
105
+ def iso!(value, field)
106
+ raise ConfigurationError, "#{field} must be an ISO 8601 date-time string." unless value.is_a?(String) && iso?(value.strip)
107
+ end
108
+
109
+ def iso?(value)
110
+ Time.iso8601(value)
111
+ true
112
+ rescue ArgumentError
113
+ begin
114
+ Date.iso8601(value)
115
+ true
116
+ rescue ArgumentError
117
+ false
118
+ end
119
+ end
120
+
121
+ def minor!(value, pattern, field)
122
+ return if value.is_a?(String) && value.match?(pattern)
123
+
124
+ raise ConfigurationError, "#{field} must be a minor-unit integer string (e.g. \"250000\"), not a number."
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Fraud webhook event types your endpoint can subscribe to, delivered in the platform's signed envelope
5
+ # and verified with WebhookVerifier. (Lunixi::FraudEvents is the transaction event client.)
6
+ module FraudWebhookEvents
7
+ # Async flow result is ready; correlate with decisionRequestId. Advisory: the synchronous decision stands.
8
+ FLOW_ASYNC_COMPLETED = 'fraud.flow.async_completed'
9
+ # A "Platform Event" node in your flow fired; label and data are the values you defined in the flow.
10
+ FLOW_ACTION_TRIGGERED = 'fraud.flow.action_triggered'
11
+ # Fraud API quota threshold reached, or a request was rejected with 429. Sent once per day and lane.
12
+ QUOTA_THRESHOLD_REACHED = 'fraud.quota.threshold_reached'
13
+ # One of your fraud alert rules fired.
14
+ ALERT_TRIGGERED = 'fraud.alert.triggered'
15
+ # An outage affecting fraud evaluation was detected or declared.
16
+ SERVICE_DEGRADED = 'fraud.service.degraded'
17
+ # The outage closed; carries the duration and how many decisions could not be checked.
18
+ SERVICE_RECOVERED = 'fraud.service.recovered'
19
+ # A scheduled report finished its period and was produced (no download link; download from the console).
20
+ REPORT_READY = 'fraud.report.ready'
21
+ # A UK APP claim obligation (receiving-firm notice, reimbursement, hard close) is due soon or overdue.
22
+ UK_CLAIM_DEADLINE = 'fraud.uk_claim.deadline'
23
+
24
+ ALL = [FLOW_ASYNC_COMPLETED, FLOW_ACTION_TRIGGERED, QUOTA_THRESHOLD_REACHED, ALERT_TRIGGERED, SERVICE_DEGRADED,
25
+ SERVICE_RECOVERED, REPORT_READY, UK_CLAIM_DEADLINE].freeze
26
+ end
27
+
28
+ # Every fraud webhook event type, in catalog order.
29
+ FRAUD_EVENT_TYPES = FraudWebhookEvents::ALL
30
+
31
+ # UK APP reimbursement claim: wire values of POST /api/v1/fraud/uk-claims. The gateway answers an unknown
32
+ # key with 400; these lists let the SDK fail locally with the offending key name.
33
+ UK_CLAIM_FIELDS = %w[role reportedAt externalClaimRef linkedClaimIds subMerchantRef victimRef payerType payerStaffCount
34
+ payerTurnoverOrBalanceEurMinor payerAnnualIncomeGbpMinor reportedBy scamType currency
35
+ counterpartyPspCode payments].freeze
36
+ UK_CLAIM_PAYMENT_FIELDS = %w[paymentRef fraudDecisionLogId traceId scheme executedAt amountMinor receivingPspCode payeeIban
37
+ payeeSortCode payeeAccountNumber warningRecord delayRecord].freeze
38
+ UK_CLAIM_ROLES = %w[sending receiving].freeze
39
+ UK_CLAIM_PAYER_TYPES = %w[individual micro_enterprise charity business_other].freeze
40
+ UK_CLAIM_REPORTED_BY = %w[victim agent].freeze
41
+ UK_CLAIM_SCAM_TYPES = %w[impersonation_bank_police impersonation_other investment romance purchase advance_fee invoice_mandate
42
+ ceo_fraud other].freeze
43
+ UK_CLAIM_SCHEMES = %w[faster_payments chaps bacs sepa swift on_us card other].freeze
44
+ # Deadline kinds carried by the fraud.uk_claim.deadline webhook event.
45
+ UK_CLAIM_DEADLINE_KINDS = %w[receiving_notify reimburse hard_close].freeze
46
+ end
@@ -35,9 +35,13 @@ module Lunixi
35
35
  # orderId, callbackUrl, basketItems ...) plus the seller legs. Returns the answer as it came (token,
36
36
  # checkoutFormContent, paymentId ...); an answer without a token or a form (a seller not eligible
37
37
  # under ALL_OR_NOTHING) raises ApiError instead of leaving the buyer on an empty page. The same route
38
- # as payments.create_marketplace_intent, which takes the legs inside the body.
38
+ # as payments.create_marketplace_intent, which takes the legs inside the body. The order details
39
+ # (buyer, billingAddress, basketItems, shippingAddress for a PHYSICAL item) are required; buyer.ip
40
+ # may be left out (CHECKOUT_INTENT_BUYER_OPTIONAL_FIELDS).
39
41
  def create_checkout_intent(request, sellers, multi_seller_policy: MarketplaceMultiSellerPolicy::ALL_OR_NOTHING, idempotency_key: nil)
40
42
  body = split_body(payload!(request, 'create_checkout_intent request'), sellers, multi_seller_policy)
43
+ OrderDetails.check!(body, 'A marketplace payment intent', checkout_intent: true)
44
+ RoutingPin.field!(body)
41
45
  response = @routes.call('createCheckoutIntent', body: body, idempotency_key: idempotency_key)
42
46
  intent = RouteResponse.merge_root(response)
43
47
  return response if RouteResponse.text(intent['token']) || RouteResponse.text(intent['checkoutFormContent'])
@@ -49,12 +53,14 @@ module Lunixi
49
53
  # Direct split card charge from a raw body (amount, currency, orderId, card, buyer, billingAddress,
50
54
  # basketItems, sellers, multiSellerPolicy, preauth? ...): POST /payments/marketplace/3d with
51
55
  # three_ds: true, /2d otherwise. Prefer charge_marketplace_card2d / charge_marketplace_card3d, which
52
- # check the body and the legs.
56
+ # check the body and the legs. The order details are checked before sending (OrderDetails).
53
57
  def charge_marketplace_card(payload, three_ds: false, idempotency_key: nil)
54
58
  raise ConfigurationError, "'three_ds' must be true or false." unless [true, false].include?(three_ds)
55
59
 
56
60
  body = payload!(payload, 'charge_marketplace_card payload')
57
61
  charge_amount!(body)
62
+ OrderDetails.check!(body, 'A marketplace card charge')
63
+ RoutingPin.field!(body, payment_method: PaymentMethod::CARD)
58
64
  @routes.call(three_ds ? 'chargeMarketplaceCard3d' : 'chargeMarketplaceCard2d', body: body, idempotency_key: idempotency_key)
59
65
  end
60
66
 
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Order details every payment endpoint requires: the buyer, the billing address and at least one
5
+ # basket item; a basket with a PHYSICAL item also requires the shipping address. Payment providers do
6
+ # not start a payment without them.
7
+ #
8
+ # The gateway refuses a missing field with payment.order.field_required and an invalid one with
9
+ # payment.order.field_invalid; details.field is the dotted path of the first failing field. The SDK
10
+ # checks the same rule before sending and names the same paths. The same values as the Node, PHP and
11
+ # Python SDKs.
12
+
13
+ # Order objects required on every payment endpoint.
14
+ ORDER_DETAILS_REQUIRED_FIELDS = %w[buyer billingAddress basketItems].freeze
15
+
16
+ # buyer fields that must be nonempty strings. identityNumber: Turkish ID or passport number; email:
17
+ # ASCII; ip: the buyer's browser IP (IPv4 or IPv6).
18
+ BUYER_REQUIRED_FIELDS = %w[name surname identityNumber email gsmNumber city country zipCode ip].freeze
19
+
20
+ # buyer fields a checkout intent may leave out (payments.create_intent, payments.create_marketplace_intent,
21
+ # marketplace.create_checkout_intent): the Lunixi form takes the IP from the buyer's browser. A given
22
+ # ip is still sent and wins.
23
+ CHECKOUT_INTENT_BUYER_OPTIONAL_FIELDS = %w[ip].freeze
24
+
25
+ # Fields of billingAddress and shippingAddress that must be nonempty strings.
26
+ ADDRESS_REQUIRED_FIELDS = %w[contactName address city country zipCode].freeze
27
+
28
+ # Fields of each basketItems[] entry the gateway requires.
29
+ BASKET_ITEM_REQUIRED_FIELDS = %w[id name category1 itemType price].freeze
30
+
31
+ # Error codes of a missing or invalid order field.
32
+ module OrderFieldErrorCode
33
+ FIELD_REQUIRED = 'payment.order.field_required'
34
+ FIELD_INVALID = 'payment.order.field_invalid'
35
+
36
+ ALL = [FIELD_REQUIRED, FIELD_INVALID].freeze
37
+ end
38
+
39
+ # details.reason of an order field error.
40
+ module OrderFieldReason
41
+ REQUIRED = 'required'
42
+ REQUIRED_WHEN_PHYSICAL = 'required_when_physical'
43
+ INVALID_TYPE = 'invalid_type'
44
+ INVALID_FORMAT = 'invalid_format'
45
+ TOO_LONG = 'too_long'
46
+ TOO_FEW_ITEMS = 'too_few_items'
47
+
48
+ ALL = [REQUIRED, REQUIRED_WHEN_PHYSICAL, INVALID_TYPE, INVALID_FORMAT, TOO_LONG, TOO_FEW_ITEMS].freeze
49
+ end
50
+
51
+ # The order details check of the payment endpoints.
52
+ module OrderDetails
53
+ PHYSICAL_ITEM_TYPE = 'PHYSICAL'
54
+
55
+ module_function
56
+
57
+ # Paths of the missing order fields of a payment body (String or Symbol keys), in the gateway's
58
+ # format: buyer, buyer.email, billingAddress.city, basketItems.0.category1, shippingAddress. An empty
59
+ # Array means the order details are complete. basket: false checks the buyer and the billing address
60
+ # only (card storage, wallet card top-up); checkout_intent: true does not require
61
+ # CHECKOUT_INTENT_BUYER_OPTIONAL_FIELDS.
62
+ def missing(body, basket: true, checkout_intent: false)
63
+ data = body.is_a?(Hash) ? JSON.parse(JsonBody.dump(body)) : {}
64
+ buyer_fields = checkout_intent ? BUYER_REQUIRED_FIELDS - CHECKOUT_INTENT_BUYER_OPTIONAL_FIELDS : BUYER_REQUIRED_FIELDS
65
+ paths = object_paths(data['buyer'], buyer_fields, 'buyer') +
66
+ object_paths(data['billingAddress'], ADDRESS_REQUIRED_FIELDS, 'billingAddress')
67
+ return paths unless basket
68
+
69
+ items = data['basketItems']
70
+ return paths << 'basketItems' unless items.is_a?(Array) && !items.empty?
71
+
72
+ paths.concat(basket_paths(items))
73
+ shipping = data['shippingAddress']
74
+ if shipping.nil?
75
+ paths << 'shippingAddress' if items.any? { |item| item.is_a?(Hash) && item['itemType'] == PHYSICAL_ITEM_TYPE }
76
+ else
77
+ paths.concat(object_paths(shipping, ADDRESS_REQUIRED_FIELDS, 'shippingAddress'))
78
+ end
79
+ paths
80
+ end
81
+
82
+ # Raises ConfigurationError naming the missing order fields (see missing); label names the request
83
+ # ("A payment intent").
84
+ def check!(body, label, basket: true, checkout_intent: false)
85
+ paths = missing(body, basket: basket, checkout_intent: checkout_intent)
86
+ raise ConfigurationError, "#{label} requires the order details: #{paths.join(', ')}." unless paths.empty?
87
+
88
+ body
89
+ end
90
+
91
+ def object_paths(value, fields, path)
92
+ return [path] unless value.is_a?(Hash)
93
+
94
+ fields.reject { |field| filled?(value[field]) }.map { |field| "#{path}.#{field}" }
95
+ end
96
+
97
+ def basket_paths(items)
98
+ items.each_with_index.flat_map do |item, index|
99
+ next ["basketItems.#{index}"] unless item.is_a?(Hash)
100
+
101
+ BASKET_ITEM_REQUIRED_FIELDS.select { |field| blank?(item[field]) }.map { |field| "basketItems.#{index}.#{field}" }
102
+ end
103
+ end
104
+
105
+ def filled?(value)
106
+ value.is_a?(String) && !value.strip.empty?
107
+ end
108
+
109
+ def blank?(value)
110
+ value.nil? || (value.is_a?(String) && value.strip.empty?)
111
+ end
112
+
113
+ private_class_method :object_paths, :basket_paths, :filled?, :blank?
114
+ end
115
+ end
@@ -6,7 +6,7 @@ module Lunixi
6
6
  # Local checks of the payment-link bodies (list filters: PaymentLinkFilters; image uploads:
7
7
  # PaymentLinkImageRules).
8
8
  module PaymentLinkRules
9
- CREATE_FIELDS = (['environment'] + PAYMENT_LINK_SPEC_FIELDS).freeze
9
+ CREATE_FIELDS = (PAYMENT_LINK_CREATE_ONLY_FIELDS + PAYMENT_LINK_SPEC_FIELDS).freeze
10
10
  UPDATE_FIELDS = PAYMENT_LINK_SPEC_FIELDS
11
11
  TIME_FIELDS = %w[startsAt expiresAt eventAt].freeze
12
12
  LINK_ACTIONS = %w[pause resume deactivate].freeze
@@ -18,6 +18,7 @@ module Lunixi
18
18
  def create_body!(body)
19
19
  data = root!(body, 'Payment link request')
20
20
  known!(data, CREATE_FIELDS, 'create')
21
+ checkout_routing!(data)
21
22
  times(data)
22
23
  end
23
24
 
@@ -30,9 +31,20 @@ module Lunixi
30
31
  raise ConfigurationError, "'#{fixed}' is fixed when a payment link is created and cannot be updated; create a new link instead" if fixed
31
32
 
32
33
  known!(data, UPDATE_FIELDS, 'update')
34
+ checkout_routing!(data)
33
35
  times(data)
34
36
  end
35
37
 
38
+ # checkout.routing, when given, is a routing pin (routing is not a top-level link field). The pin
39
+ # must be in the link's environment (otherwise 400 payment.routing.pin_mismatch, details.mismatch
40
+ # ENVIRONMENT); a target in maintenance or inactive does not stop the link (a STRICT pin is checked
41
+ # when the buyer pays).
42
+ def checkout_routing!(data)
43
+ return unless data['checkout'].is_a?(Hash)
44
+
45
+ data['checkout'] = RoutingPin.field!(data['checkout'].transform_keys(&:to_s), 'checkout.routing')
46
+ end
47
+
36
48
  # pause / resume / deactivate body: expectedRowVersion (optional) and reason.
37
49
  def action_body!(action, expected_row_version, reason)
38
50
  raise ConfigurationError, "Payment link action must be one of #{LINK_ACTIONS.join(', ')}" unless LINK_ACTIONS.include?(action.to_s)
@@ -54,12 +54,14 @@ module Lunixi
54
54
  ALL = [TEST, LIVE].freeze
55
55
  end
56
56
 
57
+ # Value of a buyerFields entry (name, email, phone, address, identityNumber). Payment providers
58
+ # require the buyer, the identity number and the billing address, so the link page always asks all
59
+ # five fields: REQUIRED is the only value (the gateway answers any other with 400; leaving a field
60
+ # out means REQUIRED).
57
61
  module BuyerFieldRequirement
58
- HIDDEN = 'HIDDEN'
59
- OPTIONAL = 'OPTIONAL'
60
62
  REQUIRED = 'REQUIRED'
61
63
 
62
- ALL = [HIDDEN, OPTIONAL, REQUIRED].freeze
64
+ ALL = [REQUIRED].freeze
63
65
  end
64
66
 
65
67
  module CustomFieldType
@@ -116,6 +118,10 @@ module Lunixi
116
118
  ALL = [PNG, JPEG, WEBP].freeze
117
119
  end
118
120
 
121
+ # Fields a create body may carry besides PAYMENT_LINK_SPEC_FIELDS: environment. An update does not
122
+ # take it. The routing pin of a link is checkout.routing (create and update).
123
+ PAYMENT_LINK_CREATE_ONLY_FIELDS = %w[environment].freeze
124
+
119
125
  # Every field of a payment-link definition in the gateway's spelling. Create and update bodies may
120
126
  # carry only these keys (plus environment on create); the gateway rejects any other key with 400.
121
127
  PAYMENT_LINK_SPEC_FIELDS = %w[
@@ -24,7 +24,9 @@ module Lunixi
24
24
 
25
25
  # Create a link. The idempotency key is required: the same key with the same body returns the stored
26
26
  # link with replayed: true; the same key with another body is 409 payment_link.idempotency.conflict.
27
- # Only PAYMENT_LINK_SPEC_FIELDS and environment are accepted; amounts are minor-unit strings.
27
+ # Only PAYMENT_LINK_SPEC_FIELDS and PAYMENT_LINK_CREATE_ONLY_FIELDS are accepted; amounts are
28
+ # minor-unit strings. checkout.routing pins every payment of the link (create and update; a
29
+ # connection in another environment than the link is refused with 400).
28
30
  def create(body, idempotency_key: nil)
29
31
  client.request('POST', BASE, body: PaymentLinkRules.create_body!(body), idempotency_key: Client.idempotency_key!(idempotency_key))
30
32
  end