lunixi-sdk 1.2.2 → 2.0.2
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +62 -0
- data/README.md +278 -10
- data/README.tr.md +282 -8
- data/docs/ruby.en.md +11 -1
- data/docs/ruby.tr.md +11 -1
- data/lib/lunixi/bank_connect.rb +340 -0
- data/lib/lunixi/bank_connect_filters.rb +114 -0
- data/lib/lunixi/bank_connect_values.rb +205 -0
- data/lib/lunixi/bank_transfer.rb +106 -0
- data/lib/lunixi/card_requests.rb +171 -0
- data/lib/lunixi/client.rb +57 -16
- data/lib/lunixi/direct_method_payment_request.rb +245 -0
- data/lib/lunixi/enabled_installments.rb +28 -0
- data/lib/lunixi/errors.rb +69 -3
- data/lib/lunixi/fraud.rb +81 -5
- data/lib/lunixi/identity.rb +94 -0
- data/lib/lunixi/identity_values.rb +28 -0
- data/lib/lunixi/insurance.rb +294 -0
- data/lib/lunixi/insurance_request.rb +134 -0
- data/lib/lunixi/insurance_values.rb +200 -0
- data/lib/lunixi/kyc.rb +189 -0
- data/lib/lunixi/kyc_values.rb +158 -0
- data/lib/lunixi/marketplace.rb +268 -0
- data/lib/lunixi/marketplace_values.rb +86 -0
- data/lib/lunixi/method_fields.rb +142 -0
- data/lib/lunixi/money.rb +7 -4
- data/lib/lunixi/order_details.rb +115 -0
- data/lib/lunixi/payment_link_filters.rb +32 -0
- data/lib/lunixi/payment_link_image_rules.rb +85 -0
- data/lib/lunixi/payment_link_rules.rb +132 -0
- data/lib/lunixi/payment_link_values.rb +136 -0
- data/lib/lunixi/payment_links.rb +152 -0
- data/lib/lunixi/payment_values.rb +86 -0
- data/lib/lunixi/payments.rb +170 -8
- data/lib/lunixi/physical_pos.rb +183 -0
- data/lib/lunixi/physical_pos_card_data.rb +117 -0
- data/lib/lunixi/physical_pos_card_number.rb +65 -0
- data/lib/lunixi/physical_pos_device_identity.rb +44 -0
- data/lib/lunixi/physical_pos_filters.rb +58 -0
- data/lib/lunixi/physical_pos_gateway.rb +153 -0
- data/lib/lunixi/physical_pos_identifiers.rb +62 -0
- data/lib/lunixi/physical_pos_management.rb +326 -0
- data/lib/lunixi/physical_pos_money.rb +46 -0
- data/lib/lunixi/physical_pos_request.rb +126 -0
- data/lib/lunixi/physical_pos_responses.rb +102 -0
- data/lib/lunixi/physical_pos_results.rb +52 -0
- data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
- data/lib/lunixi/physical_pos_value.rb +43 -0
- data/lib/lunixi/physical_pos_values.rb +203 -0
- data/lib/lunixi/physical_pos_webhook.rb +147 -0
- data/lib/lunixi/product_webhooks.rb +106 -0
- data/lib/lunixi/promissory_note.rb +155 -0
- data/lib/lunixi/reference.rb +41 -0
- data/lib/lunixi/route_request.rb +121 -0
- data/lib/lunixi/route_response.rb +101 -0
- data/lib/lunixi/route_table.rb +128 -0
- data/lib/lunixi/route_value.rb +60 -0
- data/lib/lunixi/sanction.rb +244 -0
- data/lib/lunixi/sanction_values.rb +132 -0
- data/lib/lunixi/split_payment.rb +150 -0
- data/lib/lunixi/subscription_resources.rb +357 -0
- data/lib/lunixi/subscription_values.rb +233 -0
- data/lib/lunixi/subscriptions.rb +202 -0
- data/lib/lunixi/version.rb +1 -1
- data/lib/lunixi/wallet.rb +153 -0
- data/lib/lunixi/wallet_resources.rb +407 -0
- data/lib/lunixi/wallet_routes.rb +126 -0
- data/lib/lunixi/wallet_values.rb +71 -0
- data/lib/lunixi/wire_money.rb +67 -0
- data/lib/lunixi.rb +58 -0
- metadata +59 -1
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Lunixi
|
|
4
|
+
# Physical POS: payments on your card terminals, transactions, reports, end-of-day runs and results
|
|
5
|
+
# (/api/v1/physical-pos). Every call is signed; the signing key decides the environment (a TEST key
|
|
6
|
+
# can read, but every payment write is 403 physical_pos.environment.test_key_read_only). Payment
|
|
7
|
+
# writes need the physical_pos:payments scope; reads physical_pos:view or physical_pos:payments.
|
|
8
|
+
#
|
|
9
|
+
# Card data is never sent: the card is read on the device. A field that looks like card data (pan,
|
|
10
|
+
# cardNumber, cvv, expiry …) or a card number in merchantReference, an item name / tax group or a
|
|
11
|
+
# free-text filter raises PhysicalPosCardDataRejectedError before anything is sent; any other unknown
|
|
12
|
+
# field raises ConfigurationError. Body and filter keys are the wire names (String or Symbol;
|
|
13
|
+
# snake_case is accepted too). Amounts are canonical minor-unit strings ("4500"); counts and rates
|
|
14
|
+
# are numbers.
|
|
15
|
+
#
|
|
16
|
+
# A payment write is asynchronous: the answer means "accepted", not "paid". Follow the outcome with
|
|
17
|
+
# the physical_pos.payment.* webhooks or get_payment. A payment under manual review is resolved in
|
|
18
|
+
# the panel only.
|
|
19
|
+
#
|
|
20
|
+
# Idempotency: store the key first, then call.
|
|
21
|
+
#
|
|
22
|
+
# key = Lunixi::PhysicalPos.new_idempotency_key
|
|
23
|
+
# order.update!(pos_key: key) # your storage
|
|
24
|
+
# begin
|
|
25
|
+
# lunixi.physical_pos.create_payment(request, idempotency_key: key)
|
|
26
|
+
# rescue Lunixi::PhysicalPosOutcomeUnknownError
|
|
27
|
+
# # the payment may exist: call again later with the SAME key
|
|
28
|
+
# end
|
|
29
|
+
#
|
|
30
|
+
# A new key for the same payment can charge the card twice. For a SALE also send merchantReference
|
|
31
|
+
# with allowDuplicateReference: false; the gateway then refuses a second sale while one with that
|
|
32
|
+
# reference is unresolved (physical_pos.payment.previous_outcome_unknown).
|
|
33
|
+
class PhysicalPos
|
|
34
|
+
NEW_PAYMENT = ->(replayed) { replayed ? 200 : 202 }
|
|
35
|
+
OK = ->(_replayed) { 200 }
|
|
36
|
+
|
|
37
|
+
# A new Idempotency-Key (UUID v4). Store it with your order before you call.
|
|
38
|
+
def self.new_idempotency_key
|
|
39
|
+
PhysicalPosIdentifiers.new_idempotency_key
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Verifies (signature, event id, timestamp) and reads a physical_pos.* webhook from the raw body,
|
|
43
|
+
# the headers and your webhook secret (or a WebhookVerifier). See PhysicalPosWebhook.parse.
|
|
44
|
+
def self.parse_webhook_event(raw_body, headers, secret_or_verifier, tolerance: 300)
|
|
45
|
+
PhysicalPosWebhook.parse(raw_body, headers, secret_or_verifier, tolerance: tolerance)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def initialize(gateway)
|
|
49
|
+
@gateway = gateway
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Starts a payment on a device: SALE, PREAUTH_OPEN or REFUND_UNMATCHED (POST /payments). target is
|
|
53
|
+
# exactly one of { deviceId }, { vendorCode, serialNumber } or { externalRef }; items carry a
|
|
54
|
+
# taxGroupCode per line.
|
|
55
|
+
#
|
|
56
|
+
# instrument is CARD (default) or a provider-collected card such as MEAL_CARD; for those send
|
|
57
|
+
# interaction (INSTRUMENT_READ: the device reads the card, CODE_DISPLAY: the device shows the
|
|
58
|
+
# provider's QR / short code) and, when the terminal has several provider rows, terminalProviderId
|
|
59
|
+
# (a list_terminal_providers row id). Leave both out for CARD.
|
|
60
|
+
#
|
|
61
|
+
# idempotency_key is required. Returns a PhysicalPosWriteResult: 202 with paymentStatus NOT_STARTED
|
|
62
|
+
# for a new payment, 200 with replayed true when the same key and body were sent before (the
|
|
63
|
+
# payment's current view). Raises PhysicalPosOutcomeUnknownError when the outcome is unknown.
|
|
64
|
+
def create_payment(request, idempotency_key: nil)
|
|
65
|
+
key = PhysicalPosIdentifiers.required_idempotency_key!(idempotency_key, 'a physical POS payment')
|
|
66
|
+
body = PhysicalPosRequest.body!(request, PHYSICAL_POS_REQUEST_FIELDS['createPayment'], 'createPayment request')
|
|
67
|
+
@gateway.payment_write('/payments', body, key, NEW_PAYMENT)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Reverses an approved payment (POST /payments/{paymentId}/reversals): VOID, REFUND (by amountMinor
|
|
71
|
+
# or by items: [{ lineNo, quantityMilli }]), PREAUTH_CLOSE or PREAUTH_CANCEL. The reversal is a new
|
|
72
|
+
# child payment (originalPaymentId = payment_id) followed like any payment. idempotency_key is
|
|
73
|
+
# required; same result and errors as create_payment.
|
|
74
|
+
def create_reversal(payment_id, request, idempotency_key: nil)
|
|
75
|
+
path = "/payments/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}/reversals"
|
|
76
|
+
key = PhysicalPosIdentifiers.required_idempotency_key!(idempotency_key, 'a physical POS reversal')
|
|
77
|
+
body = PhysicalPosRequest.body!(request, PHYSICAL_POS_REQUEST_FIELDS['createReversal'], 'createReversal request')
|
|
78
|
+
@gateway.payment_write(path, body, key, NEW_PAYMENT)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Cancels a payment before its start command reaches the device (POST /payments/{paymentId}/cancel,
|
|
82
|
+
# 200). Read payment['paymentStatus']: only EXPIRED with statusReason
|
|
83
|
+
# MERCHANT_CANCELLED_BEFORE_DISPATCH means it was cancelled; a payment already in a final state
|
|
84
|
+
# comes back unchanged with replayed true. To undo an approved sale use a reversal. Cancelling is
|
|
85
|
+
# idempotent, so the key is optional (a new UUID when nil).
|
|
86
|
+
def cancel_payment(payment_id, idempotency_key: nil)
|
|
87
|
+
path = "/payments/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}/cancel"
|
|
88
|
+
@gateway.payment_write(path, {}, PhysicalPosIdentifiers.idempotency_key_or_new(idempotency_key), OK)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# One payment with its items and refund items (GET /payments/{paymentId}).
|
|
92
|
+
def get_payment(payment_id)
|
|
93
|
+
@gateway.record('GET', "/payments/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}", 'payment')
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Payments, newest first (GET /payments). Roots and reversals are in one list; items and
|
|
97
|
+
# refundItems are empty here (read one payment for them). merchantReference finds a payment after
|
|
98
|
+
# an unknown outcome.
|
|
99
|
+
def list_payments(**filters)
|
|
100
|
+
@gateway.page('/payments', PhysicalPosFilters.query!(filters, 'listPayments'))
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def iterate_payments(**filters, &block)
|
|
104
|
+
PhysicalPosResponses.each_item(filters, block) { |query| list_payments(**query) }
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Transaction trees (root payment + its reversals), newest first (GET /transactions).
|
|
108
|
+
def list_transactions(**filters)
|
|
109
|
+
@gateway.page('/transactions', PhysicalPosFilters.query!(filters, 'listTransactions'))
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def iterate_transactions(**filters, &block)
|
|
113
|
+
PhysicalPosResponses.each_item(filters, block) { |query| list_transactions(**query) }
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# The tree of a root or child payment with its timeline (GET /transactions/{paymentId}).
|
|
117
|
+
def get_transaction(payment_id)
|
|
118
|
+
@gateway.record('GET', "/transactions/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}", 'transaction')
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Payments with an unknown outcome or under manual review (GET /transactions/ambiguous).
|
|
122
|
+
def list_ambiguous_payments(**filters)
|
|
123
|
+
@gateway.page('/transactions/ambiguous', PhysicalPosFilters.query!(filters, 'listAmbiguousPayments'))
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def iterate_ambiguous_payments(**filters, &block)
|
|
127
|
+
PhysicalPosResponses.each_item(filters, block) { |query| list_ambiguous_payments(**query) }
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Sale / refund / void counts and amounts with net per currency (GET /reports/sales-summary).
|
|
131
|
+
# dateFrom / dateTo are business days (YYYY-MM-DD, Europe/Istanbul); groupBy DAY, STORE, DEVICE or
|
|
132
|
+
# INSTRUMENT.
|
|
133
|
+
def get_sales_summary(**filters)
|
|
134
|
+
@gateway.data('GET', '/reports/sales-summary', query: PhysicalPosFilters.query!(filters, 'getSalesSummary'))
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# Tax breakdown with refunds and voids deducted (GET /reports/tax-summary).
|
|
138
|
+
def get_tax_summary(**filters)
|
|
139
|
+
@gateway.data('GET', '/reports/tax-summary', query: PhysicalPosFilters.query!(filters, 'getTaxSummary'))
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# End-of-day results per bank line, with the reported / system / difference totals (GET /settlements).
|
|
143
|
+
def list_settlements(**filters)
|
|
144
|
+
@gateway.page('/settlements', PhysicalPosFilters.query!(filters, 'listSettlements'))
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def iterate_settlements(**filters, &block)
|
|
148
|
+
PhysicalPosResponses.each_item(filters, block) { |query| list_settlements(**query) }
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# Starts end-of-day (batch close) on a device (POST /devices/{deviceId}/settlement,
|
|
152
|
+
# physical_pos:payments). End-of-day cannot be undone. The answer means "accepted": the device
|
|
153
|
+
# reports the result later; follow it with get_settlement_run or list_settlements.
|
|
154
|
+
#
|
|
155
|
+
# Returns a PhysicalPosWriteResult (result['run'], 202 new / 200 replay). Pass the key you stored,
|
|
156
|
+
# or nil for a new UUID (returned as idempotency_key; after an unknown outcome call again with it).
|
|
157
|
+
# A TEST key is refused with 403 physical_pos.environment.test_key_read_only.
|
|
158
|
+
def start_settlement(device_id, idempotency_key: nil)
|
|
159
|
+
path = "/devices/#{PhysicalPosIdentifiers.path_id(device_id, 'deviceId')}/settlement"
|
|
160
|
+
@gateway.keyed_write(path, {}, idempotency_key, NEW_PAYMENT)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# End-of-day runs started by Lunixi (manual and scheduled), newest first (GET /settlement-runs).
|
|
164
|
+
# Filters: deviceId, source (MANUAL_API, MANUAL_PANEL, SCHEDULED), runStatus (PENDING, STARTED,
|
|
165
|
+
# SKIPPED, FAILED), createdFrom / createdTo, includeTotal.
|
|
166
|
+
def list_settlement_runs(**filters)
|
|
167
|
+
@gateway.page('/settlement-runs', PhysicalPosFilters.query!(filters, 'listSettlementRuns'))
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def iterate_settlement_runs(**filters, &block)
|
|
171
|
+
PhysicalPosResponses.each_item(filters, block) { |query| list_settlement_runs(**query) }
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# One end-of-day run with its command status and result state (GET /settlement-runs/{runId}).
|
|
175
|
+
def get_settlement_run(run_id)
|
|
176
|
+
@gateway.record('GET', "/settlement-runs/#{PhysicalPosIdentifiers.path_id(run_id, 'runId')}", 'run')
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
def inspect
|
|
180
|
+
'#<Lunixi::PhysicalPos>'
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
end
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Lunixi
|
|
4
|
+
# The gateway's card-data rules for physical POS requests: card-data field names (any depth of a body
|
|
5
|
+
# or filter set) and the refusal of card data, field names and card numbers in free text (read by
|
|
6
|
+
# PhysicalPosCardNumber). The card is read on the device; a request never carries card data.
|
|
7
|
+
module PhysicalPosCardData
|
|
8
|
+
NUMBER_TERMS = %w[pan pannumber cardpan cardnumber cardno cardnum cardnr ccnumber ccnum primaryaccountnumber].freeze
|
|
9
|
+
SECRET_TERMS = %w[
|
|
10
|
+
cvv cvv2 cvc cvc2 cvn cvn2 cav2 cvvcode cvccode cardcode securitycode cardverificationcode cardverificationvalue
|
|
11
|
+
track1 track2 track3 tracki trackii trackiii trackdata magstripe magneticstripe pinblock pincode pinnumber pindata
|
|
12
|
+
cardpin cardholderpin encryptedpin expdate expmonth expyear expmmyy expirydate expirymonth expiryyear expirymmyy
|
|
13
|
+
expirationdate expirationmonth expirationyear expiremonth expireyear cardexpiry cardexpiration
|
|
14
|
+
].freeze
|
|
15
|
+
SUFFIX_TERMS = %w[
|
|
16
|
+
cardnumber pannumber primaryaccountnumber cvv cvv2 cvc cvc2 cvvcode securitycode track1 track2 trackdata pinblock
|
|
17
|
+
expmonth expyear expirydate expirymonth expiryyear expirationdate cardexpiry
|
|
18
|
+
].freeze
|
|
19
|
+
WHOLE_KEY_TERMS = %w[track expiry expiration pin cid csc].freeze
|
|
20
|
+
MASK_TOKENS = %w[masked mask].freeze
|
|
21
|
+
|
|
22
|
+
# Term lists of the card-data key rule (the parity test compares them with the shared fixture).
|
|
23
|
+
KEY_RULE = {
|
|
24
|
+
'numberTerms' => NUMBER_TERMS, 'secretTerms' => SECRET_TERMS, 'suffixTerms' => SUFFIX_TERMS,
|
|
25
|
+
'wholeKeyTerms' => WHOLE_KEY_TERMS, 'maskTokens' => MASK_TOKENS
|
|
26
|
+
}.freeze
|
|
27
|
+
|
|
28
|
+
DIGIT_RUN_KEY_SOURCE = '[0-9](?:[ -]?[0-9]){12,}'
|
|
29
|
+
DIGIT_RUN_KEY = Regexp.new(DIGIT_RUN_KEY_SOURCE)
|
|
30
|
+
IDENTIFIER_KEY = /\A[A-Za-z_$][A-Za-z0-9_$]*\z/
|
|
31
|
+
|
|
32
|
+
CARD_DATA_TERMS = (NUMBER_TERMS + SECRET_TERMS).freeze
|
|
33
|
+
CARD_DATA_MESSAGE = 'Physical POS requests must not contain card data: the card is read on the device. Remove the field ' \
|
|
34
|
+
'or value; do not send card numbers, expiry dates or security codes.'
|
|
35
|
+
|
|
36
|
+
module_function
|
|
37
|
+
|
|
38
|
+
def key_tokens(key)
|
|
39
|
+
key.to_s
|
|
40
|
+
.gsub(/([a-z0-9])([A-Z])/, '\1 \2')
|
|
41
|
+
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1 \2')
|
|
42
|
+
.gsub(/([A-Za-z])([0-9])/, '\1 \2')
|
|
43
|
+
.gsub(/([0-9])([A-Za-z])/, '\1 \2')
|
|
44
|
+
.downcase
|
|
45
|
+
.split(/[^a-z0-9]+/)
|
|
46
|
+
.reject(&:empty?)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# True when a field name is card data (pan, cardNumber, cvv, track2Data, expiryDate …).
|
|
50
|
+
def card_data_key?(key)
|
|
51
|
+
tokens = key_tokens(key)
|
|
52
|
+
return false if tokens.empty?
|
|
53
|
+
return true if WHOLE_KEY_TERMS.include?(tokens.join)
|
|
54
|
+
|
|
55
|
+
masked = tokens.any? { |token| MASK_TOKENS.include?(token) }
|
|
56
|
+
tokens.each_index.any? { |start| card_data_run?(tokens, start, masked) }
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def card_data_run?(tokens, start, masked)
|
|
60
|
+
joined = +''
|
|
61
|
+
tokens[start..].any? do |token|
|
|
62
|
+
joined << token
|
|
63
|
+
next true if CARD_DATA_TERMS.include?(joined) && !(masked && NUMBER_TERMS.include?(joined))
|
|
64
|
+
|
|
65
|
+
SUFFIX_TERMS.any? { |term| joined.end_with?(term) && !(masked && NUMBER_TERMS.include?(term)) }
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Path of the first card-data key in a body or filter set (items[1].cvv), or nil. A key holding a
|
|
70
|
+
# 13+ digit run stops at the parent path. Values are not read here.
|
|
71
|
+
def find_card_data_field(value, root = '(body)')
|
|
72
|
+
stack = [[value, '']]
|
|
73
|
+
until stack.empty?
|
|
74
|
+
node, path = stack.pop
|
|
75
|
+
if node.is_a?(Array)
|
|
76
|
+
(node.size - 1).downto(0) { |index| stack << [node[index], "#{path}[#{index}]"] }
|
|
77
|
+
next
|
|
78
|
+
end
|
|
79
|
+
next unless node.is_a?(Hash)
|
|
80
|
+
|
|
81
|
+
keys = node.keys
|
|
82
|
+
keys.each do |key|
|
|
83
|
+
return path.empty? ? root : path if key.to_s.match?(DIGIT_RUN_KEY)
|
|
84
|
+
return child_path(path, key) if card_data_key?(key)
|
|
85
|
+
end
|
|
86
|
+
keys.reverse_each { |key| stack << [node[key], child_path(path, key)] }
|
|
87
|
+
end
|
|
88
|
+
nil
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def child_path(path, key)
|
|
92
|
+
name = key.to_s
|
|
93
|
+
return "#{path}[?]" unless name.match?(IDENTIFIER_KEY)
|
|
94
|
+
|
|
95
|
+
path.empty? ? name : "#{path}.#{name}"
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def card_data_rejected(field)
|
|
99
|
+
PhysicalPosCardDataRejectedError.new(status: 0, field: field, message: "#{CARD_DATA_MESSAGE} Field: #{field}.")
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def reject_card_data!(value, root)
|
|
103
|
+
field = find_card_data_field(value, root)
|
|
104
|
+
raise card_data_rejected(field) unless field.nil?
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Card-number values in the free-text fields the gateway scans (the value never reaches the error).
|
|
108
|
+
def reject_card_numbers!(body)
|
|
109
|
+
raise card_data_rejected('merchantReference') if PhysicalPosCardNumber.contains_pan_like_value?(body['merchantReference'])
|
|
110
|
+
|
|
111
|
+
Array(body['items']).each_with_index do |item, index|
|
|
112
|
+
raise card_data_rejected("items[#{index}].name") if PhysicalPosCardNumber.contains_pan_like_value?(item['name'], PhysicalPosCardNumber::ITEM_TEXT)
|
|
113
|
+
raise card_data_rejected("items[#{index}].taxGroupCode") if PhysicalPosCardNumber.contains_pan_like_value?(item['taxGroupCode'])
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
end
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Lunixi
|
|
4
|
+
# Card numbers written into the free-text values of a physical POS request (merchantReference, item
|
|
5
|
+
# names, tax groups, free-text filters). Not a public API.
|
|
6
|
+
module PhysicalPosCardNumber
|
|
7
|
+
PAN_CANDIDATE = /(?<![\p{L}\p{N}])(?<![\p{L}\p{N}]-)[0-9](?:[ -]?[0-9]){12,18}(?![\p{L}\p{N}])(?!-[\p{L}\p{N}])/
|
|
8
|
+
GTIN = /\A(?:[0-9]{8}|[0-9]{12,14})\z/
|
|
9
|
+
|
|
10
|
+
# contains_pan_like_value? modes: STRICT for every scanned field, ITEM_TEXT for item names (an
|
|
11
|
+
# unseparated 13 or 14 digit number with a valid GTIN check digit is a barcode, not a card).
|
|
12
|
+
STRICT = 'STRICT'
|
|
13
|
+
ITEM_TEXT = 'ITEM_TEXT'
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# True when the text holds a stand-alone, Luhn-valid 13–19 digit number (plain, space or dash
|
|
18
|
+
# separated). In ITEM_TEXT mode a valid unseparated 13 or 14 digit GTIN is a barcode.
|
|
19
|
+
def contains_pan_like_value?(text, mode = STRICT)
|
|
20
|
+
return false unless text.is_a?(String)
|
|
21
|
+
|
|
22
|
+
utf8_text(text).scan(PAN_CANDIDATE).any? do |candidate|
|
|
23
|
+
digits = candidate.delete(' -')
|
|
24
|
+
next false unless digits.length.between?(13, 19)
|
|
25
|
+
next false if mode == ITEM_TEXT && digits == candidate && digits.length <= 14 && gtin_valid?(digits)
|
|
26
|
+
|
|
27
|
+
luhn_valid?(digits)
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def utf8_text(text)
|
|
32
|
+
utf8 = text.encode(Encoding::UTF_8)
|
|
33
|
+
raise ConfigurationError, 'Physical POS request text must be valid UTF-8' unless utf8.valid_encoding?
|
|
34
|
+
|
|
35
|
+
utf8
|
|
36
|
+
rescue EncodingError
|
|
37
|
+
raise ConfigurationError, 'Physical POS request text must be valid UTF-8', cause: nil
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def luhn_valid?(digits)
|
|
41
|
+
sum = 0
|
|
42
|
+
digits.reverse.each_char.with_index do |char, index|
|
|
43
|
+
digit = char.to_i
|
|
44
|
+
if index.odd?
|
|
45
|
+
digit *= 2
|
|
46
|
+
digit -= 9 if digit > 9
|
|
47
|
+
end
|
|
48
|
+
sum += digit
|
|
49
|
+
end
|
|
50
|
+
(sum % 10).zero?
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def gtin_valid?(digits)
|
|
54
|
+
return false unless digits.match?(GTIN)
|
|
55
|
+
|
|
56
|
+
sum = 0
|
|
57
|
+
weight = 3
|
|
58
|
+
(digits.length - 2).downto(0) do |index|
|
|
59
|
+
sum += digits[index].to_i * weight
|
|
60
|
+
weight = weight == 3 ? 1 : 3
|
|
61
|
+
end
|
|
62
|
+
(10 - (sum % 10)) % 10 == digits[-1].to_i
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Lunixi
|
|
4
|
+
# Device identity routes of PhysicalPosManagement (physical_pos:identity for writes). Mixed into
|
|
5
|
+
# PhysicalPosManagement; uses its request and path helpers.
|
|
6
|
+
module PhysicalPosDeviceIdentity
|
|
7
|
+
# The device's identity keys, fingerprints only (GET /devices/{deviceId}/keys). Each key: keyId,
|
|
8
|
+
# algorithm, keyStatus (ACTIVE | SUPERSEDED | REVOKED), enrolledVia (PAIRING | ACTIVATION_CODE |
|
|
9
|
+
# ROTATION), fingerprint, lineageRootKeyId, rotatedFromKeyId, activatedAt, supersededAt, revokedAt,
|
|
10
|
+
# revokeReason, rowVersion.
|
|
11
|
+
def list_device_keys(device_id, **filters)
|
|
12
|
+
@gateway.page("#{device_path(device_id)}/keys", query(filters, 'history'))
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def iterate_device_keys(device_id, **filters, &block)
|
|
16
|
+
PhysicalPosResponses.each_item(filters, block) { |page| list_device_keys(device_id, **page) }
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Revokes a device key: { rowVersion (the key's), reasonCode }; reasonCode DEVICE_LOST,
|
|
20
|
+
# DEVICE_STOLEN, KEY_COMPROMISED, DEVICE_REPLACED, MERCHANT_REQUEST or OTHER.
|
|
21
|
+
# { 'key', 'lifecycleStatus', 'replayed' }.
|
|
22
|
+
def revoke_device_key(device_id, key_id, request)
|
|
23
|
+
@gateway.data('POST', "#{key_path(device_id, key_id)}/revoke", body: body(request, 'revokeDeviceKey'))
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Reverts an activation-code enrollment (revokes the key, suspends the device): { reasonCode };
|
|
27
|
+
# NOT_MY_DEVICE, SUSPECTED_PHISHING, WRONG_DEVICE or OTHER. { 'key', 'lifecycleStatus', 'replayed' }.
|
|
28
|
+
def revert_device_enrollment(device_id, key_id, request)
|
|
29
|
+
@gateway.data('POST', "#{key_path(device_id, key_id)}/revert-enrollment", body: body(request, 'revertDeviceEnrollment'))
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Revokes the device's open activation code: { reasonCode }; MERCHANT_REVOKED, DEVICE_LOST,
|
|
33
|
+
# DEVICE_STOLEN or OTHER. { 'deviceId', 'revokedAt', 'revokeReason' }.
|
|
34
|
+
def revoke_activation_code(device_id, request)
|
|
35
|
+
@gateway.data('POST', "#{device_path(device_id)}/activation-code/revoke", body: body(request, 'revokeActivationCode'))
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
def key_path(device_id, key_id)
|
|
41
|
+
"#{device_path(device_id)}/keys/#{id(key_id, 'keyId')}"
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'date'
|
|
4
|
+
|
|
5
|
+
module Lunixi
|
|
6
|
+
# Local checks of the physical POS list and report filters (PHYSICAL_POS_FILTERS).
|
|
7
|
+
module PhysicalPosFilters
|
|
8
|
+
AMOUNT_FILTERS = %w[amountFromMinor amountToMinor].freeze
|
|
9
|
+
CALENDAR_DAY_FILTERS = %w[dateFrom dateTo].freeze
|
|
10
|
+
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
# Checks list / report filters of a route (PHYSICAL_POS_FILTERS) and returns the query. nil and ''
|
|
14
|
+
# are left out. limit is 1–100; includeTotal a boolean; amountFromMinor / amountToMinor canonical
|
|
15
|
+
# minor-unit strings; a Time in createdFrom / createdTo is sent as ISO 8601 UTC; dateFrom / dateTo
|
|
16
|
+
# take a YYYY-MM-DD string, a Date or a Time (its own calendar day, not converted to
|
|
17
|
+
# Europe/Istanbul). merchantReference and q are scanned for card numbers.
|
|
18
|
+
def query!(filters, route)
|
|
19
|
+
return {} if filters.nil?
|
|
20
|
+
|
|
21
|
+
PhysicalPosCardData.reject_card_data!(filters, '(query)')
|
|
22
|
+
allowed = PHYSICAL_POS_FILTERS.fetch(route)
|
|
23
|
+
given = PhysicalPosRequest.wire_keys!(filters, allowed, 'physical POS', 'filter')
|
|
24
|
+
allowed.each_with_object({}) do |key, query|
|
|
25
|
+
next unless given.key?(key)
|
|
26
|
+
|
|
27
|
+
value = given[key]
|
|
28
|
+
next query[key] = PhysicalPosValue.money!(value, key) if AMOUNT_FILTERS.include?(key)
|
|
29
|
+
next if value.nil? || value == ''
|
|
30
|
+
|
|
31
|
+
query[key] = filter_value(key, value)
|
|
32
|
+
free_text = PHYSICAL_POS_FREE_TEXT_FILTERS.include?(key)
|
|
33
|
+
raise PhysicalPosCardData.card_data_rejected(key) if free_text && PhysicalPosCardNumber.contains_pan_like_value?(query[key])
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def filter_value(key, value)
|
|
38
|
+
case key
|
|
39
|
+
when 'limit'
|
|
40
|
+
unless value.is_a?(Integer) && value.between?(1, PHYSICAL_POS_MAX_LIMIT)
|
|
41
|
+
raise ConfigurationError, "'limit' must be an integer between 1 and #{PHYSICAL_POS_MAX_LIMIT}."
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
value.to_s
|
|
45
|
+
when 'includeTotal' then PhysicalPosValue.boolean!(value, key) ? 'true' : 'false'
|
|
46
|
+
else time_filter(key, value)
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def time_filter(key, value)
|
|
51
|
+
return value.strftime('%Y-%m-%d') if CALENDAR_DAY_FILTERS.include?(key) && (value.is_a?(Time) || value.is_a?(Date))
|
|
52
|
+
return value.getutc.strftime('%Y-%m-%dT%H:%M:%S.%LZ') if value.is_a?(Time)
|
|
53
|
+
raise ConfigurationError, "'#{key}' must be a string." unless value.is_a?(String)
|
|
54
|
+
|
|
55
|
+
value
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Lunixi
|
|
4
|
+
# Sends the physical POS requests of PhysicalPos and PhysicalPosManagement through Client#request
|
|
5
|
+
# (signed, bearer token), checks the declared money of every answer and maps the errors. Payment
|
|
6
|
+
# writes run their own attempt loop so an uncertain outcome is never lost. Not a public API.
|
|
7
|
+
class PhysicalPosGateway
|
|
8
|
+
AMBIGUOUS = :ambiguous
|
|
9
|
+
NOT_STARTED = :not_started
|
|
10
|
+
DEFINITE = :definite
|
|
11
|
+
OUTCOME_UNKNOWN_MESSAGE = 'The outcome of the physical POS payment request is unknown: the payment may exist. Call again ' \
|
|
12
|
+
'with the same idempotency_key (an existing payment comes back with replayed: true) or look ' \
|
|
13
|
+
'it up; never use a new key for it.'
|
|
14
|
+
|
|
15
|
+
def initialize(client, max_retries:, backoff:)
|
|
16
|
+
@client = client
|
|
17
|
+
@max_retries = max_retries
|
|
18
|
+
@backoff = backoff
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# One signed request (reads and management writes); answers are money-checked, errors mapped.
|
|
22
|
+
def perform(method, path, body: nil, query: {}, idempotency_key: nil)
|
|
23
|
+
response = @client.request(method, PhysicalPosRequest::BASE + path, body: body, query: query, idempotency_key: idempotency_key)
|
|
24
|
+
PhysicalPosMoney.validate(response)
|
|
25
|
+
response
|
|
26
|
+
rescue ApiError => e
|
|
27
|
+
mapped = PhysicalPosResponses.translate(e, idempotency_key)
|
|
28
|
+
raise if mapped.equal?(e)
|
|
29
|
+
|
|
30
|
+
raise mapped
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def data(method, path, body: nil, query: {})
|
|
34
|
+
PhysicalPosResponses.unwrap(perform(method, path, body: body, query: query))
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# data[name] of a single-record answer (or data when the wrapper is missing).
|
|
38
|
+
def record(method, path, name, body: nil, query: {})
|
|
39
|
+
PhysicalPosResponses.member(perform(method, path, body: body, query: query), name)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def page(path, query)
|
|
43
|
+
PhysicalPosResponses.page(perform('GET', path, query: query))
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# A management or end-of-day write with an Idempotency-Key: the caller's key, or a new UUID for nil.
|
|
47
|
+
def keyed_write(path, body, idempotency_key, fallback)
|
|
48
|
+
key = PhysicalPosIdentifiers.idempotency_key_or_new(idempotency_key)
|
|
49
|
+
PhysicalPosResponses.write_result(perform('POST', path, body: body, idempotency_key: key), key, fallback)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Payment start, reversal or cancel: 1 + max_retries attempts with the same key and body (the
|
|
53
|
+
# client's own retries are off for each attempt).
|
|
54
|
+
#
|
|
55
|
+
# Success is only a 2xx carrying a payment. A 2xx without a readable payment, no HTTP answer, or a
|
|
56
|
+
# 5xx that does not say "not started" leaves the outcome unknown; it is retried while attempts
|
|
57
|
+
# remain. A 4xx stops at once. When any attempt was ambiguous the call raises
|
|
58
|
+
# PhysicalPosOutcomeUnknownError whatever the last answer was (a later 429 or 409 included),
|
|
59
|
+
# because the key may already hold a payment.
|
|
60
|
+
def payment_write(path, body, key, fallback)
|
|
61
|
+
attempts = 1 + @max_retries
|
|
62
|
+
ambiguous = false
|
|
63
|
+
last_error = nil
|
|
64
|
+
(1..attempts).each do |attempt|
|
|
65
|
+
response, error, outcome = attempt_payment(path, body, key)
|
|
66
|
+
if response
|
|
67
|
+
result = written_payment(response, key, fallback)
|
|
68
|
+
return result if result
|
|
69
|
+
|
|
70
|
+
error = missing_payment(response)
|
|
71
|
+
outcome = AMBIGUOUS
|
|
72
|
+
end
|
|
73
|
+
local_error!(error, ambiguous, key, attempt) if outcome.nil?
|
|
74
|
+
last_error = error
|
|
75
|
+
ambiguous ||= outcome == AMBIGUOUS
|
|
76
|
+
if outcome == DEFINITE || attempt == attempts
|
|
77
|
+
raise outcome_unknown(last_error, key, attempt), cause: last_error if ambiguous
|
|
78
|
+
|
|
79
|
+
break
|
|
80
|
+
end
|
|
81
|
+
@backoff.call(attempt - 1)
|
|
82
|
+
end
|
|
83
|
+
definite!(last_error, key)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
private
|
|
87
|
+
|
|
88
|
+
# [response, nil, nil] for an answer, [nil, error, outcome] for a failed attempt; outcome nil marks
|
|
89
|
+
# an error raised before anything was sent.
|
|
90
|
+
def attempt_payment(path, body, key)
|
|
91
|
+
response = @client.request('POST', PhysicalPosRequest::BASE + path, body: body, idempotency_key: key, max_retries: 0)
|
|
92
|
+
[response, nil, nil]
|
|
93
|
+
rescue ApiError => e
|
|
94
|
+
[nil, e, attempt_outcome(e)]
|
|
95
|
+
rescue StandardError => e
|
|
96
|
+
[nil, e, raised_before_sending?(e) ? nil : AMBIGUOUS]
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# An SDK error other than a transport or redirect failure (a local check) means nothing was sent.
|
|
100
|
+
def raised_before_sending?(error)
|
|
101
|
+
error.is_a?(Error) && !error.is_a?(TransportError) && !error.is_a?(RedirectError)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# - ambiguous: no HTTP answer, an unreadable 2xx, or a 5xx that does not say "not started".
|
|
105
|
+
# - not_started: a 5xx with a code in PHYSICAL_POS_NOT_STARTED_CODES.
|
|
106
|
+
# - definite: any other answer (4xx, 429 and 409 included).
|
|
107
|
+
def attempt_outcome(error)
|
|
108
|
+
return AMBIGUOUS if error.status.to_i.zero? || error.status.to_i.between?(200, 299)
|
|
109
|
+
return DEFINITE if error.status.to_i < 500
|
|
110
|
+
|
|
111
|
+
PHYSICAL_POS_NOT_STARTED_CODES.include?(error.code) ? NOT_STARTED : AMBIGUOUS
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# A local refusal (nothing sent) after an earlier uncertain attempt still leaves the outcome unknown.
|
|
115
|
+
def local_error!(error, ambiguous, key, attempt)
|
|
116
|
+
raise error unless ambiguous
|
|
117
|
+
|
|
118
|
+
raise outcome_unknown(error, key, attempt - 1), cause: error
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def definite!(error, key)
|
|
122
|
+
mapped = PhysicalPosResponses.translate(error, key)
|
|
123
|
+
raise mapped if mapped.equal?(error)
|
|
124
|
+
|
|
125
|
+
raise mapped, cause: error
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def missing_payment(response)
|
|
129
|
+
status = response.is_a?(Hash) && response['statusCode'].is_a?(Integer) ? response['statusCode'] : 0
|
|
130
|
+
ApiError.new(status: status, message: 'The gateway accepted the payment request but the answer carries no payment.')
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def written_payment(response, key, fallback)
|
|
134
|
+
PhysicalPosMoney.validate(response)
|
|
135
|
+
data = PhysicalPosResponses.unwrap(response)
|
|
136
|
+
payment = data.is_a?(Hash) ? data['payment'] : nil
|
|
137
|
+
return nil unless payment.is_a?(Hash) && payment['paymentId'].is_a?(String) && !payment['paymentId'].empty?
|
|
138
|
+
|
|
139
|
+
PhysicalPosResponses.write_result(response, key, fallback)
|
|
140
|
+
rescue ConfigurationError, SystemStackError
|
|
141
|
+
nil
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def outcome_unknown(last_error, key, attempts)
|
|
145
|
+
answered = last_error.is_a?(ApiError) ? last_error : nil
|
|
146
|
+
PhysicalPosOutcomeUnknownError.new(
|
|
147
|
+
status: answered ? answered.status : 0, code: answered&.code, request_id: answered&.request_id,
|
|
148
|
+
details: answered&.details, retry_after: answered ? PhysicalPosResponses.retry_after_seconds(answered) : nil,
|
|
149
|
+
idempotency_key: key, attempts: attempts, message: OUTCOME_UNKNOWN_MESSAGE
|
|
150
|
+
)
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|