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.
Files changed (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +62 -0
  3. data/README.md +278 -10
  4. data/README.tr.md +282 -8
  5. data/docs/ruby.en.md +11 -1
  6. data/docs/ruby.tr.md +11 -1
  7. data/lib/lunixi/bank_connect.rb +340 -0
  8. data/lib/lunixi/bank_connect_filters.rb +114 -0
  9. data/lib/lunixi/bank_connect_values.rb +205 -0
  10. data/lib/lunixi/bank_transfer.rb +106 -0
  11. data/lib/lunixi/card_requests.rb +171 -0
  12. data/lib/lunixi/client.rb +57 -16
  13. data/lib/lunixi/direct_method_payment_request.rb +245 -0
  14. data/lib/lunixi/enabled_installments.rb +28 -0
  15. data/lib/lunixi/errors.rb +69 -3
  16. data/lib/lunixi/fraud.rb +81 -5
  17. data/lib/lunixi/identity.rb +94 -0
  18. data/lib/lunixi/identity_values.rb +28 -0
  19. data/lib/lunixi/insurance.rb +294 -0
  20. data/lib/lunixi/insurance_request.rb +134 -0
  21. data/lib/lunixi/insurance_values.rb +200 -0
  22. data/lib/lunixi/kyc.rb +189 -0
  23. data/lib/lunixi/kyc_values.rb +158 -0
  24. data/lib/lunixi/marketplace.rb +268 -0
  25. data/lib/lunixi/marketplace_values.rb +86 -0
  26. data/lib/lunixi/method_fields.rb +142 -0
  27. data/lib/lunixi/money.rb +7 -4
  28. data/lib/lunixi/order_details.rb +115 -0
  29. data/lib/lunixi/payment_link_filters.rb +32 -0
  30. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  31. data/lib/lunixi/payment_link_rules.rb +132 -0
  32. data/lib/lunixi/payment_link_values.rb +136 -0
  33. data/lib/lunixi/payment_links.rb +152 -0
  34. data/lib/lunixi/payment_values.rb +86 -0
  35. data/lib/lunixi/payments.rb +170 -8
  36. data/lib/lunixi/physical_pos.rb +183 -0
  37. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  38. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  39. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  40. data/lib/lunixi/physical_pos_filters.rb +58 -0
  41. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  42. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  43. data/lib/lunixi/physical_pos_management.rb +326 -0
  44. data/lib/lunixi/physical_pos_money.rb +46 -0
  45. data/lib/lunixi/physical_pos_request.rb +126 -0
  46. data/lib/lunixi/physical_pos_responses.rb +102 -0
  47. data/lib/lunixi/physical_pos_results.rb +52 -0
  48. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  49. data/lib/lunixi/physical_pos_value.rb +43 -0
  50. data/lib/lunixi/physical_pos_values.rb +203 -0
  51. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  52. data/lib/lunixi/product_webhooks.rb +106 -0
  53. data/lib/lunixi/promissory_note.rb +155 -0
  54. data/lib/lunixi/reference.rb +41 -0
  55. data/lib/lunixi/route_request.rb +121 -0
  56. data/lib/lunixi/route_response.rb +101 -0
  57. data/lib/lunixi/route_table.rb +128 -0
  58. data/lib/lunixi/route_value.rb +60 -0
  59. data/lib/lunixi/sanction.rb +244 -0
  60. data/lib/lunixi/sanction_values.rb +132 -0
  61. data/lib/lunixi/split_payment.rb +150 -0
  62. data/lib/lunixi/subscription_resources.rb +357 -0
  63. data/lib/lunixi/subscription_values.rb +233 -0
  64. data/lib/lunixi/subscriptions.rb +202 -0
  65. data/lib/lunixi/version.rb +1 -1
  66. data/lib/lunixi/wallet.rb +153 -0
  67. data/lib/lunixi/wallet_resources.rb +407 -0
  68. data/lib/lunixi/wallet_routes.rb +126 -0
  69. data/lib/lunixi/wallet_values.rb +71 -0
  70. data/lib/lunixi/wire_money.rb +67 -0
  71. data/lib/lunixi.rb +58 -0
  72. metadata +59 -1
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # KYC / KYB / evidence values and routes (/api/v1/kyc). The same codes as the Node and PHP SDKs. The
5
+ # browser bootstraps its own SDK token with the publishable key (/kyc/sdk/init); that route is not
6
+ # reachable from a server key and is not here.
7
+
8
+ # Session types. EVIDENCE is proof-of-X (address, funds, card ownership ...), not only onboarding.
9
+ module KycSessionType
10
+ # A person's identity.
11
+ KYC = 'KYC'
12
+ # A company and its beneficial owners.
13
+ KYB = 'KYB'
14
+ EVIDENCE = 'EVIDENCE'
15
+ ALL = [KYC, KYB, EVIDENCE].freeze
16
+ end
17
+
18
+ # Session status.
19
+ module KycSessionStatus
20
+ CREATED = 'CREATED'
21
+ INITIATED = 'INITIATED'
22
+ DOCUMENT_SUBMITTED = 'DOCUMENT_SUBMITTED'
23
+ PROCESSING = 'PROCESSING'
24
+ AWAITING_PROVIDER_CALLBACK = 'AWAITING_PROVIDER_CALLBACK'
25
+ AWAITING_ADDITIONAL_DOCUMENT = 'AWAITING_ADDITIONAL_DOCUMENT'
26
+ AWAITING_USER_ACTION = 'AWAITING_USER_ACTION'
27
+ UNDER_REVIEW = 'UNDER_REVIEW'
28
+ PENDING_ADDITIONAL_INFO = 'PENDING_ADDITIONAL_INFO'
29
+ RESCREEN_REQUIRED = 'RESCREEN_REQUIRED'
30
+ REOPENED = 'REOPENED'
31
+ APPROVED = 'APPROVED'
32
+ REJECTED = 'REJECTED'
33
+ MANUAL_REVIEW = 'MANUAL_REVIEW'
34
+ EXPIRED = 'EXPIRED'
35
+ ABANDONED = 'ABANDONED'
36
+ CANCELLED = 'CANCELLED'
37
+ ALL = [CREATED, INITIATED, DOCUMENT_SUBMITTED, PROCESSING, AWAITING_PROVIDER_CALLBACK, AWAITING_ADDITIONAL_DOCUMENT, AWAITING_USER_ACTION,
38
+ UNDER_REVIEW, PENDING_ADDITIONAL_INFO, RESCREEN_REQUIRED, REOPENED, APPROVED, REJECTED, MANUAL_REVIEW, EXPIRED, ABANDONED,
39
+ CANCELLED].freeze
40
+ TERMINAL_STATES = [APPROVED, REJECTED, MANUAL_REVIEW, EXPIRED, ABANDONED, CANCELLED].freeze
41
+ end
42
+
43
+ KYC_SESSION_TERMINAL_STATES = KycSessionStatus::TERMINAL_STATES
44
+
45
+ # evidencePurpose of an EVIDENCE session.
46
+ module KycEvidencePurpose
47
+ IDENTITY_VERIFICATION = 'IDENTITY_VERIFICATION'
48
+ BUSINESS_VERIFICATION = 'BUSINESS_VERIFICATION'
49
+ PROOF_OF_FUNDS = 'PROOF_OF_FUNDS'
50
+ PROOF_OF_ADDRESS = 'PROOF_OF_ADDRESS'
51
+ SOURCE_OF_FUNDS = 'SOURCE_OF_FUNDS'
52
+ SOURCE_OF_WEALTH = 'SOURCE_OF_WEALTH'
53
+ TRANSACTION_EVIDENCE = 'TRANSACTION_EVIDENCE'
54
+ CARD_OWNERSHIP = 'CARD_OWNERSHIP'
55
+ PAYMENT_METHOD_OWNERSHIP = 'PAYMENT_METHOD_OWNERSHIP'
56
+ PAYOUT_EVIDENCE = 'PAYOUT_EVIDENCE'
57
+ MERCHANT_ONBOARDING = 'MERCHANT_ONBOARDING'
58
+ ALL = [IDENTITY_VERIFICATION, BUSINESS_VERIFICATION, PROOF_OF_FUNDS, PROOF_OF_ADDRESS, SOURCE_OF_FUNDS, SOURCE_OF_WEALTH, TRANSACTION_EVIDENCE,
59
+ CARD_OWNERSHIP, PAYMENT_METHOD_OWNERSHIP, PAYOUT_EVIDENCE, MERCHANT_ONBOARDING].freeze
60
+ end
61
+
62
+ # Assurance ladder (rank-aligned with NIST 800-63 IAL / eIDAS LoA). A gate passes when achieved >=
63
+ # required (Lunixi::Kyc.assurance_meets?).
64
+ module KycAssuranceLevel
65
+ NONE = 'NONE'
66
+ NOT_PERFORMED = 'NOT_PERFORMED'
67
+ LOW = 'LOW'
68
+ SUBSTANTIAL = 'SUBSTANTIAL'
69
+ HIGH = 'HIGH'
70
+ ALL = [NONE, NOT_PERFORMED, LOW, SUBSTANTIAL, HIGH].freeze
71
+ end
72
+
73
+ # Domains of the achieved assurance snapshot (session.decision.assuranceSnapshot.achieved), each an
74
+ # assurance level.
75
+ module KycAssuranceDomain
76
+ IDENTITY = 'identity_evidence_strength'
77
+ DOCUMENT = 'document_authenticity_level'
78
+ BIOMETRIC = 'possession_biometric_binding'
79
+ AUTHORITATIVE = 'authoritative_source_level'
80
+ ADDRESS = 'address_assurance'
81
+ AML = 'aml_freshness'
82
+ HUMAN_REVIEW = 'human_review_level'
83
+ ALL = [IDENTITY, DOCUMENT, BIOMETRIC, AUTHORITATIVE, ADDRESS, AML, HUMAN_REVIEW].freeze
84
+ end
85
+
86
+ # Webhook event types (the same signed envelope as payment events). data always carries sessionId and
87
+ # externalCustomerId; terminal events carry the decision. A rescreen or a screening hit on an approved
88
+ # session must revoke access.
89
+ module KycEvents
90
+ SESSION_CREATED = 'kyc.session.created'
91
+ SESSION_INITIATED = 'kyc.session.initiated'
92
+ SESSION_EXPIRED = 'kyc.session.expired'
93
+ SESSION_ABANDONED = 'kyc.session.abandoned'
94
+ SESSION_CANCELLED = 'kyc.session.cancelled'
95
+ DOCUMENT_RECEIVED = 'kyc.document.received'
96
+ DOCUMENT_REJECTED = 'kyc.document.rejected'
97
+ LIVENESS_COMPLETED = 'kyc.liveness.completed'
98
+ PROCESSING_STARTED = 'kyc.processing.started'
99
+ MANUAL_REVIEW_REQUIRED = 'kyc.manual_review.required'
100
+ APPROVED = 'kyc.approved'
101
+ REJECTED = 'kyc.rejected'
102
+ RESCREEN_REQUIRED = 'kyc.rescreen.required'
103
+ KYB_SESSION_CREATED = 'kyb.session.created'
104
+ KYB_COMPANY_VERIFIED = 'kyb.company.verified'
105
+ KYB_COMPANY_NOT_FOUND = 'kyb.company.not_found'
106
+ KYB_UBO_PENDING = 'kyb.ubo.pending'
107
+ KYB_RELATED_KYC_REQUIRED = 'kyb.related_kyc.required'
108
+ KYB_RELATED_KYC_COMPLETED = 'kyb.related_kyc.completed'
109
+ KYB_MANUAL_REVIEW_REQUIRED = 'kyb.manual_review.required'
110
+ KYB_APPROVED = 'kyb.approved'
111
+ KYB_REJECTED = 'kyb.rejected'
112
+ SCREENING_MATCH_DETECTED = 'screening.match.detected'
113
+ SCREENING_FALSE_POSITIVE_CLEARED = 'screening.false_positive.cleared'
114
+ MONITORING_ALERT_CREATED = 'ongoing_monitoring.alert.created'
115
+ ALL = [SESSION_CREATED, SESSION_INITIATED, SESSION_EXPIRED, SESSION_ABANDONED, SESSION_CANCELLED, DOCUMENT_RECEIVED, DOCUMENT_REJECTED,
116
+ LIVENESS_COMPLETED, PROCESSING_STARTED, MANUAL_REVIEW_REQUIRED, APPROVED, REJECTED, RESCREEN_REQUIRED, KYB_SESSION_CREATED,
117
+ KYB_COMPANY_VERIFIED, KYB_COMPANY_NOT_FOUND, KYB_UBO_PENDING, KYB_RELATED_KYC_REQUIRED, KYB_RELATED_KYC_COMPLETED,
118
+ KYB_MANUAL_REVIEW_REQUIRED, KYB_APPROVED, KYB_REJECTED, SCREENING_MATCH_DETECTED, SCREENING_FALSE_POSITIVE_CLEARED,
119
+ MONITORING_ALERT_CREATED].freeze
120
+ end
121
+
122
+ KYC_EVENT_TYPES = KycEvents::ALL
123
+
124
+ # Longest session lifetime ttlMinutes accepts (one day).
125
+ KYC_SESSION_TTL_MAX_MINUTES = 1440
126
+
127
+ kyc_base = '/api/v1/kyc'
128
+ session_fields = %w[externalCustomerId customerMode customer jurisdiction requiredDocumentTypes primaryDocumentType evidencePurpose ttlMinutes
129
+ idempotencyKey evidenceContextJson].freeze
130
+ route = lambda do |method, path, **extra|
131
+ RouteRequest.route(method, path, step_up: false, idempotency_key: 'none', **extra)
132
+ end
133
+
134
+ # Every KYC route the SDK calls (access token only). The same table as the Node SDK's KYC_ROUTES; the
135
+ # parity test compares it with the shared catalog.
136
+ KYC_ROUTES = {
137
+ 'createSession' => route.call('POST', "#{kyc_base}/sessions", idempotency_key: 'optional', required: %w[subjectId sessionType],
138
+ optional: session_fields),
139
+ 'getSession' => route.call('GET', "#{kyc_base}/sessions/:sessionId"),
140
+ # The merchant list takes only these two; an unknown filter is a 400 on the gateway.
141
+ 'listSessions' => route.call('GET', "#{kyc_base}/sessions", query: %w[limit cursor]),
142
+ 'setJurisdiction' => route.call('POST', "#{kyc_base}/sessions/:sessionId/jurisdiction", required: %w[jurisdiction]),
143
+ 'setPrimaryDocument' => route.call('POST', "#{kyc_base}/sessions/:sessionId/primary-document", required: %w[documentType]),
144
+ 'uploadDocument' => route.call('POST', "#{kyc_base}/sessions/:sessionId/documents", required: %w[documentType fileBase64 mimeType],
145
+ optional: %w[side jurisdiction metadataJson idempotencyKey]),
146
+ 'timeline' => route.call('GET', "#{kyc_base}/sessions/:sessionId/timeline"),
147
+ 'submit' => route.call('POST', "#{kyc_base}/sessions/:sessionId/submit"),
148
+ 'manualReview' => route.call('POST', "#{kyc_base}/sessions/:sessionId/manual-review", optional: %w[reasonCode reasonDetail], optional_body: true),
149
+ 'evidenceRequest' => route.call('POST', "#{kyc_base}/evidence-requests", idempotency_key: 'optional', required: %w[subjectId sessionType],
150
+ optional: session_fields),
151
+ 'merchantPolicy' => route.call('GET', "#{kyc_base}/admin/merchant-policy"),
152
+ 'updateMerchantPolicy' => route.call('POST', "#{kyc_base}/admin/merchant-policy", free: true),
153
+ 'rotateWebhookSecret' => route.call('POST', "#{kyc_base}/admin/merchant-policy/webhook-secret/rotate"),
154
+ 'webhookOutbox' => route.call('GET', "#{kyc_base}/admin/webhook-outbox", query: %w[limit status]),
155
+ 'retryWebhookEvent' => route.call('POST', "#{kyc_base}/admin/webhook-outbox/:eventId/retry"),
156
+ 'erasureRequests' => route.call('GET', "#{kyc_base}/admin/erasure-requests", query: %w[limit status])
157
+ }.freeze
158
+ end
@@ -0,0 +1,268 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Marketplace (client.marketplace): split charges across sub-dealers, the sub-dealer lifecycle,
5
+ # commissions, payouts and the audit log.
6
+ #
7
+ # Split charges (/api/v1/payments/marketplace) are signed per request and take an optional
8
+ # Idempotency-Key (the payment key rule: 16–128 printable ASCII). A split is aggregate per seller: group
9
+ # the basket by vendor and pass one leg per sub-dealer, { subDealerId, amountMinor, scenario? }; the legs
10
+ # must add up to amount. Dealer, commission, payout and audit routes (/api/v1/marketplace) carry the
11
+ # access token only.
12
+ #
13
+ # Card data (card number, expiry, security code) is sent as given and never logged or put in an error
14
+ # message; a direct card charge is PCI DSS SAQ-D scope, so most marketplaces use create_checkout_intent
15
+ # (hosted form).
16
+ #
17
+ # Amounts are canonical minor-unit strings. Entity calls return the envelope's data; lists return a
18
+ # Lunixi::ListPage.
19
+ class Marketplace
20
+ REMOVED_AMOUNT_FIELDS = %w[price paidPrice].freeze
21
+
22
+ # Onboarding URL of an onboarding_token answer: its url, else the hosted wizard with its token.
23
+ def self.onboarding_url(link, base = MARKETPLACE_DEALER_ONBOARDING_HOSTED_BASE)
24
+ return link['url'] if link.is_a?(Hash) && link['url'].is_a?(String) && !link['url'].empty?
25
+
26
+ token = link.is_a?(Hash) && link['token'].is_a?(String) ? link['token'] : ''
27
+ "#{base.to_s.sub(%r{/+\z}, '')}/m/#{URI.encode_www_form_component(token).gsub('+', '%20')}"
28
+ end
29
+
30
+ def initialize(client)
31
+ @routes = RouteTable.new(client, MARKETPLACE_ROUTES)
32
+ end
33
+
34
+ # Hosted-form split checkout (POST /payments/marketplace/intents): the intent body (amount, currency,
35
+ # orderId, callbackUrl, basketItems ...) plus the seller legs. Returns the answer as it came (token,
36
+ # checkoutFormContent, paymentId ...); an answer without a token or a form (a seller not eligible
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. 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).
41
+ def create_checkout_intent(request, sellers, multi_seller_policy: MarketplaceMultiSellerPolicy::ALL_OR_NOTHING, idempotency_key: nil)
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
+ response = @routes.call('createCheckoutIntent', body: body, idempotency_key: idempotency_key)
45
+ intent = RouteResponse.merge_root(response)
46
+ return response if RouteResponse.text(intent['token']) || RouteResponse.text(intent['checkoutFormContent'])
47
+
48
+ raise ApiError.new(status: intent['statusCode'].is_a?(Integer) ? intent['statusCode'] : 0, code: intent['code'],
49
+ request_id: intent['requestId'], message: 'The marketplace checkout intent did not return a token or a checkout form.')
50
+ end
51
+
52
+ # Direct split card charge from a raw body (amount, currency, orderId, card, buyer, billingAddress,
53
+ # basketItems, sellers, multiSellerPolicy, preauth? ...): POST /payments/marketplace/3d with
54
+ # three_ds: true, /2d otherwise. Prefer charge_marketplace_card2d / charge_marketplace_card3d, which
55
+ # check the body and the legs. The order details are checked before sending (OrderDetails).
56
+ def charge_marketplace_card(payload, three_ds: false, idempotency_key: nil)
57
+ raise ConfigurationError, "'three_ds' must be true or false." unless [true, false].include?(three_ds)
58
+
59
+ body = payload!(payload, 'charge_marketplace_card payload')
60
+ charge_amount!(body)
61
+ OrderDetails.check!(body, 'A marketplace card charge')
62
+ @routes.call(three_ds ? 'chargeMarketplaceCard3d' : 'chargeMarketplaceCard2d', body: body, idempotency_key: idempotency_key)
63
+ end
64
+
65
+ # Split card charge without 3-D Secure: the card payment body plus the seller legs.
66
+ def charge_marketplace_card2d(request, sellers, multi_seller_policy: MarketplaceMultiSellerPolicy::ALL_OR_NOTHING, idempotency_key: nil)
67
+ charge_marketplace_card(charge_body(request, sellers, multi_seller_policy), three_ds: false, idempotency_key: idempotency_key)
68
+ end
69
+
70
+ # Split card charge with 3-D Secure: the card payment body plus the seller legs.
71
+ def charge_marketplace_card3d(request, sellers, multi_seller_policy: MarketplaceMultiSellerPolicy::ALL_OR_NOTHING, idempotency_key: nil)
72
+ charge_marketplace_card(charge_body(request, sellers, multi_seller_policy), three_ds: true, idempotency_key: idempotency_key)
73
+ end
74
+
75
+ # { legalName, taxId?, dealerType?, categoryCode?, email?, externalRef? }. The dealer then onboards
76
+ # itself (KYC, IBAN, contract) before it is ACTIVE.
77
+ def create_dealer(request)
78
+ body = RouteRequest.wire_hash!(request, 'createDealer request')
79
+ RouteValue.one_of!(body['dealerType'], MarketplaceDealerType::ALL, 'dealerType') if body.key?('dealerType')
80
+ @routes.data('createDealer', body: body)
81
+ end
82
+
83
+ # Several dealers at once (an import); each row as in create_dealer.
84
+ def bulk_create_dealers(dealers)
85
+ raise ConfigurationError, 'bulk_create_dealers needs a non-empty array of dealers.' unless dealers.is_a?(Array) && !dealers.empty?
86
+
87
+ rows = dealers.each_with_index.map { |dealer, index| RouteRequest.wire_hash!(dealer, "dealers[#{index}]") }
88
+ @routes.data('bulkCreateDealers', body: { 'dealers' => rows })
89
+ end
90
+
91
+ # Filters: status, search, limit, offset.
92
+ def list_dealers(**filters)
93
+ @routes.page('listDealers', query: filters)
94
+ end
95
+
96
+ def get_dealer(dealer_id)
97
+ @routes.data('getDealer', params: { 'dealerId' => dealer_id })
98
+ end
99
+
100
+ def update_dealer_status(dealer_id, status)
101
+ RouteValue.one_of!(status, MarketplaceDealerStatus::ALL, 'status')
102
+ @routes.data('updateDealerStatus', params: { 'dealerId' => dealer_id }, body: { 'status' => status })
103
+ end
104
+
105
+ # Self-onboarding link: { token, url, ... } (token also starts the embedded onboarding SDK).
106
+ # Lunixi::Marketplace.onboarding_url(link) gives the URL.
107
+ def onboarding_token(dealer_id)
108
+ RouteResponse.merge_root(@routes.call('onboardingToken', params: { 'dealerId' => dealer_id }))
109
+ end
110
+
111
+ # Onboarding / application status.
112
+ def dealer_application(dealer_id)
113
+ @routes.data('dealerApplication', params: { 'dealerId' => dealer_id })
114
+ end
115
+
116
+ def submit_dealer_application(dealer_id, payload = {})
117
+ @routes.data('submitDealerApplication', params: { 'dealerId' => dealer_id }, body: payload)
118
+ end
119
+
120
+ # Commission / terms definition.
121
+ def set_dealer_terms(dealer_id, payload)
122
+ @routes.data('setDealerTerms', params: { 'dealerId' => dealer_id }, body: payload)
123
+ end
124
+
125
+ # Signature / contract acceptance.
126
+ def sign_dealer_contract(dealer_id, payload = {})
127
+ @routes.data('signDealerContract', params: { 'dealerId' => dealer_id }, body: payload)
128
+ end
129
+
130
+ def activate_dealer(dealer_id)
131
+ @routes.data('activateDealer', params: { 'dealerId' => dealer_id })
132
+ end
133
+
134
+ # A KYC outcome, when you run the dealer's KYC yourself.
135
+ def record_dealer_kyc_result(dealer_id, payload)
136
+ @routes.data('recordDealerKycResult', params: { 'dealerId' => dealer_id }, body: payload)
137
+ end
138
+
139
+ # Filters: status, subDealerId, days, limit.
140
+ def payout_ledger(**filters)
141
+ @routes.page('payoutLedger', query: filters)
142
+ end
143
+
144
+ # Filters: status, subDealerId, limit.
145
+ def transactions(**filters)
146
+ @routes.page('transactions', query: filters)
147
+ end
148
+
149
+ # Filter: limit.
150
+ def commission_rules(**filters)
151
+ @routes.page('commissionRules', query: filters)
152
+ end
153
+
154
+ def upsert_commission_rule(rule)
155
+ @routes.data('upsertCommissionRule', body: rule)
156
+ end
157
+
158
+ # A dry run of a rule's effect.
159
+ def preview_commission_rule(rule)
160
+ @routes.data('previewCommissionRule', body: rule)
161
+ end
162
+
163
+ # The effective commission of a dealer (and category) at a month-to-date volume (mtd_volume_minor, a
164
+ # minor-unit string).
165
+ def resolve_commission(sub_dealer_id, category_code: nil, mtd_volume_minor: nil)
166
+ query = RouteRequest.compact('subDealerId' => RouteValue.text!(sub_dealer_id, 'subDealerId'),
167
+ 'categoryCode' => RouteValue.optional_text(category_code, 'categoryCode'), 'mtdVolumeMinor' => mtd_volume_minor)
168
+ @routes.data('resolveCommission', query: query)
169
+ end
170
+
171
+ # A manual payout: { subDealerId, amountMinor, currency, reference?, ... }.
172
+ def create_payout(payload)
173
+ body = RouteRequest.wire_hash!(payload, 'createPayout payload')
174
+ WireMoney.wire_minor!(body['amountMinor'], 'amountMinor') if body.key?('amountMinor')
175
+ @routes.data('createPayout', body: body)
176
+ end
177
+
178
+ # { paidAt?, reference?, ... }.
179
+ def mark_payout_paid(payout_id, payload = {})
180
+ @routes.data('markPayoutPaid', params: { 'payoutId' => payout_id }, body: payload)
181
+ end
182
+
183
+ def bulk_mark_payouts_paid(payout_ids, extra = {})
184
+ raise ConfigurationError, 'bulk_mark_payouts_paid needs a non-empty array of payout ids.' unless payout_ids.is_a?(Array) && !payout_ids.empty?
185
+
186
+ ids = payout_ids.each_with_index.map { |id, index| RouteValue.text!(id, "payoutIds[#{index}]") }
187
+ @routes.data('bulkMarkPayoutsPaid', body: RouteRequest.wire_hash!(extra, 'bulk_mark_payouts_paid extra').merge('payoutIds' => ids))
188
+ end
189
+
190
+ # The append-only, hash-chained audit log; filters limit, type.
191
+ def audit_log(**filters)
192
+ @routes.page('auditLog', query: filters)
193
+ end
194
+
195
+ # Verifies the integrity of the hash chain.
196
+ def verify_audit_log
197
+ @routes.data('verifyAuditLog')
198
+ end
199
+
200
+ def inspect
201
+ '#<Lunixi::Marketplace>'
202
+ end
203
+
204
+ private
205
+
206
+ # A request Hash (or an object with to_h) as plain JSON data with String keys at every level.
207
+ def payload!(value, label)
208
+ value = value.to_h if !value.is_a?(Hash) && !value.is_a?(Array) && !value.nil? && value.respond_to?(:to_h)
209
+ raise ConfigurationError, "#{label} must be a Hash." unless value.is_a?(Hash)
210
+
211
+ JSON.parse(JsonBody.dump(value))
212
+ end
213
+
214
+ # The charge body of charge_marketplace_card2d / 3d: the commercial context is required.
215
+ def charge_body(request, sellers, multi_seller_policy)
216
+ body = payload!(request, 'marketplace charge request')
217
+ missing = MARKETPLACE_CHARGE_REQUIRED_FIELDS.reject { |field| RouteRequest.present?(body[field]) }
218
+ raise ConfigurationError, "A marketplace card charge requires #{missing.join(', ')}." unless missing.empty?
219
+ raise ConfigurationError, 'A marketplace card charge requires at least one basket item.' unless body['basketItems'].is_a?(Array)
220
+
221
+ split_body(body, sellers, multi_seller_policy)
222
+ end
223
+
224
+ # Adds the seller legs and the policy; the legs must add up to amount.
225
+ def split_body(body, sellers, multi_seller_policy)
226
+ if body.key?('sellers') || body.key?('multiSellerPolicy')
227
+ raise ConfigurationError, 'Pass the seller legs and multi_seller_policy as arguments, not in the request body.'
228
+ end
229
+
230
+ charge_amount!(body)
231
+ RouteValue.one_of!(multi_seller_policy, MarketplaceMultiSellerPolicy::ALL, 'multiSellerPolicy')
232
+ raise ConfigurationError, 'A marketplace split requires at least one seller leg.' unless sellers.is_a?(Array) && !sellers.empty?
233
+
234
+ legs = sellers.each_with_index.map { |seller, index| seller_leg(seller, index) }
235
+ total = legs.sum { |leg| Integer(leg['amountMinor'], 10) }
236
+ unless total == Integer(body['amount'], 10)
237
+ raise ConfigurationError, "The seller legs add up to #{total}, not to amount #{body['amount']}; the gateway refuses any other total."
238
+ end
239
+
240
+ body.merge('sellers' => legs, 'multiSellerPolicy' => multi_seller_policy)
241
+ end
242
+
243
+ def seller_leg(seller, index)
244
+ label = "sellers[#{index}]"
245
+ leg = RouteRequest.wire_keys!(seller.is_a?(Hash) ? seller : payload!(seller, label), MARKETPLACE_SELLER_FIELDS, label)
246
+ out = { 'subDealerId' => RouteValue.text!(leg['subDealerId'], "#{label}.subDealerId"),
247
+ 'amountMinor' => WireMoney.wire_minor!(leg['amountMinor'], "#{label}.amountMinor") }
248
+ if leg.key?('scenario')
249
+ raise ConfigurationError, "'#{label}.scenario' must be a Hash." unless leg['scenario'].is_a?(Hash)
250
+
251
+ out['scenario'] = leg['scenario']
252
+ end
253
+ out
254
+ end
255
+
256
+ # amount (the basket total) is a positive minor-unit string; price / paidPrice are removed fields;
257
+ # preauth is a boolean; the other money members are canonical.
258
+ def charge_amount!(body)
259
+ sent = REMOVED_AMOUNT_FIELDS.select { |field| body.key?(field) }
260
+ raise ConfigurationError, "#{sent.join(', ')}: removed from the payment body; send the amount only in 'amount' (minor units)." unless sent.empty?
261
+
262
+ WireMoney.wire_minor!(body['amount'], 'amount')
263
+ raise ConfigurationError, "'preauth' must be true or false." if body.key?('preauth') && ![true, false].include?(body['preauth'])
264
+
265
+ Money.validate_fields(body)
266
+ end
267
+ end
268
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Marketplace (sub-dealer split) values and routes: /api/v1/marketplace for dealers, commissions,
5
+ # payouts and the audit log (access token only), and the split charges under
6
+ # /api/v1/payments/marketplace (signed per request). The same codes as the Node and PHP SDKs.
7
+
8
+ # Sub-dealer lifecycle. Only ACTIVE dealers can receive a split.
9
+ module MarketplaceDealerStatus
10
+ DRAFT = 'DRAFT'
11
+ PENDING_KYC = 'PENDING_KYC'
12
+ ACTIVE = 'ACTIVE'
13
+ SUSPENDED = 'SUSPENDED'
14
+ HOLD = 'HOLD'
15
+ CLOSED = 'CLOSED'
16
+ ALL = [DRAFT, PENDING_KYC, ACTIVE, SUSPENDED, HOLD, CLOSED].freeze
17
+ end
18
+
19
+ # dealerType of a sub-dealer.
20
+ module MarketplaceDealerType
21
+ LEGAL_ENTITY = 'LEGAL_ENTITY'
22
+ INDIVIDUAL = 'INDIVIDUAL'
23
+ ALL = [LEGAL_ENTITY, INDIVIDUAL].freeze
24
+ end
25
+
26
+ # multiSellerPolicy of a split charge: every seller leg must be eligible, or the eligible legs may go
27
+ # through without the others.
28
+ module MarketplaceMultiSellerPolicy
29
+ ALL_OR_NOTHING = 'ALL_OR_NOTHING'
30
+ PARTIAL_ALLOWED = 'PARTIAL_ALLOWED'
31
+ ALL = [ALL_OR_NOTHING, PARTIAL_ALLOWED].freeze
32
+ end
33
+
34
+ # Hosted dealer onboarding wizard (Lunixi::Marketplace.onboarding_url when the answer carries no url).
35
+ MARKETPLACE_DEALER_ONBOARDING_HOSTED_BASE = 'https://altbayi.lunixi.com'
36
+
37
+ # Fields of a seller leg: the aggregate amount of one sub-dealer.
38
+ MARKETPLACE_SELLER_FIELDS = %w[subDealerId amountMinor scenario].freeze
39
+
40
+ # Fields a split card charge (charge_marketplace_card2d / 3d) needs besides the seller legs: the
41
+ # commercial context of a traceable card payment.
42
+ MARKETPLACE_CHARGE_REQUIRED_FIELDS = %w[amount currency orderId card buyer billingAddress basketItems].freeze
43
+
44
+ marketplace_base = '/api/v1/marketplace'
45
+ split_base = '/api/v1/payments/marketplace'
46
+ route = lambda do |method, path, **extra|
47
+ RouteRequest.route(method, path, step_up: false, idempotency_key: 'none', **extra)
48
+ end
49
+ charge = ->(path) { route.call('POST', path, step_up: true, idempotency_key: 'optional', free: true) }
50
+
51
+ # Every marketplace route the SDK calls. The same table as the Node SDK's MARKETPLACE_ROUTES; the
52
+ # parity test compares it with the shared catalog.
53
+ MARKETPLACE_ROUTES = {
54
+ 'createCheckoutIntent' => charge.call("#{split_base}/intents"),
55
+ 'chargeMarketplaceCard2d' => charge.call("#{split_base}/2d"),
56
+ 'chargeMarketplaceCard3d' => charge.call("#{split_base}/3d"),
57
+
58
+ 'createDealer' => route.call('POST', "#{marketplace_base}/dealers", required: %w[legalName],
59
+ optional: %w[taxId dealerType categoryCode email externalRef]),
60
+ 'bulkCreateDealers' => route.call('POST', "#{marketplace_base}/dealers/bulk", required: %w[dealers]),
61
+ 'listDealers' => route.call('GET', "#{marketplace_base}/dealers", query: %w[status search limit offset]),
62
+ 'getDealer' => route.call('GET', "#{marketplace_base}/dealers/:dealerId"),
63
+ 'updateDealerStatus' => route.call('PUT', "#{marketplace_base}/dealers/:dealerId/status", required: %w[status]),
64
+ 'onboardingToken' => route.call('POST', "#{marketplace_base}/dealers/:dealerId/onboarding-token"),
65
+ 'dealerApplication' => route.call('GET', "#{marketplace_base}/dealers/:dealerId/application"),
66
+ 'submitDealerApplication' => route.call('POST', "#{marketplace_base}/dealers/:dealerId/submit", free: true),
67
+ 'setDealerTerms' => route.call('POST', "#{marketplace_base}/dealers/:dealerId/terms", free: true),
68
+ 'signDealerContract' => route.call('POST', "#{marketplace_base}/dealers/:dealerId/sign", free: true),
69
+ 'activateDealer' => route.call('POST', "#{marketplace_base}/dealers/:dealerId/activate"),
70
+ 'recordDealerKycResult' => route.call('POST', "#{marketplace_base}/dealers/:dealerId/kyc-result", free: true),
71
+
72
+ 'payoutLedger' => route.call('GET', "#{marketplace_base}/payout-ledger", query: %w[status subDealerId days limit]),
73
+ 'transactions' => route.call('GET', "#{marketplace_base}/transactions", query: %w[status subDealerId limit]),
74
+ 'commissionRules' => route.call('GET', "#{marketplace_base}/commission-rules", query: %w[limit]),
75
+ 'upsertCommissionRule' => route.call('POST', "#{marketplace_base}/commission-rules", free: true),
76
+ 'previewCommissionRule' => route.call('POST', "#{marketplace_base}/commission-rules/preview", free: true),
77
+ 'resolveCommission' => route.call('GET', "#{marketplace_base}/commission/resolve", query: %w[subDealerId categoryCode mtdVolumeMinor]),
78
+
79
+ 'createPayout' => route.call('POST', "#{marketplace_base}/payouts", free: true),
80
+ 'markPayoutPaid' => route.call('POST', "#{marketplace_base}/payouts/:payoutId/mark-paid", free: true),
81
+ 'bulkMarkPayoutsPaid' => route.call('POST', "#{marketplace_base}/payouts/bulk-mark-paid", free: true),
82
+
83
+ 'auditLog' => route.call('GET', "#{marketplace_base}/audit-log", query: %w[limit type]),
84
+ 'verifyAuditLog' => route.call('GET', "#{marketplace_base}/audit-log/verify")
85
+ }.freeze
86
+ end
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Request rules of the payment-method endpoints, checked before anything is sent. The fields inside
5
+ # a method block are the provider's declaration (inputFields) and are validated by the gateway; these
6
+ # rules stop a body the gateway would reject for its shape alone.
7
+ module MethodFields
8
+ METHOD_CODE_PATTERN = /\A[A-Z][A-Z0-9_]{0,31}\z/
9
+ PROVIDER_CODE_PATTERN = /\A[A-Za-z0-9_-]{1,64}\z/
10
+ FIELD_KEY_PATTERN = /\A[A-Za-z][A-Za-z0-9]{0,63}\z/
11
+ RESERVED_FIELD_KEYS = %w[__proto__ constructor prototype].freeze
12
+ MAX_KEYS = 32
13
+ MAX_NESTED_KEYS = 16
14
+ MAX_GROUP_ITEMS = 10
15
+ MAX_VALUE_LENGTH = 1024
16
+ OTP_PATTERN = /\A[0-9]{1,16}\z/
17
+
18
+ module_function
19
+
20
+ # Canonical method code; QR becomes QR_CODE.
21
+ def normalize_payment_method(value)
22
+ unless value.is_a?(String) && value.match?(METHOD_CODE_PATTERN)
23
+ raise ConfigurationError, 'paymentMethod must be a payment method code such as MOBILE_BILLING'
24
+ end
25
+
26
+ PaymentMethod::ALIASES.fetch(value, value)
27
+ end
28
+
29
+ # Name of the method's block in the body: the camelCase method code (BANK_TRANSFER -> bankTransfer).
30
+ def block_name_of(payment_method)
31
+ normalize_payment_method(payment_method).downcase.gsub(/_([a-z0-9])/) { Regexp.last_match(1).upcase }
32
+ end
33
+
34
+ def provider_code!(value)
35
+ unless value.is_a?(String) && value.match?(PROVIDER_CODE_PATTERN)
36
+ raise ConfigurationError, 'providerCode must be a provider code from payments.list_payment_methods (letters, digits, _ and -)'
37
+ end
38
+
39
+ value
40
+ end
41
+
42
+ # A method block or confirm fields: at most 32 fields; a value is a string (at most 1024 characters),
43
+ # a finite number, a boolean, an object of such values (ADDRESS, at most 16 fields) or a list of at
44
+ # most 10 objects (GROUP). providerCode is never part of the fields.
45
+ def method_fields!(value, path)
46
+ raise ConfigurationError, "#{path} must be an object of field values" unless value.is_a?(Hash)
47
+ raise ConfigurationError, "#{path} can carry at most #{MAX_KEYS} fields" if value.size > MAX_KEYS
48
+
49
+ value.each do |key, field|
50
+ raise ConfigurationError, "#{path} must not carry providerCode; pass it as its own argument" if key == 'providerCode'
51
+
52
+ field_key!(key, path)
53
+ field_value!(field, "#{path}.#{key}", allow_list: true)
54
+ end
55
+ value
56
+ end
57
+
58
+ # A SHOPPING_LOAN payment needs the basket (1 to 100 items): the bank sets the loan term from it.
59
+ def shopping_loan_basket!(payment_method, basket_items)
60
+ return unless payment_method == PaymentMethod::SHOPPING_LOAN
61
+ unless basket_items.is_a?(Array) && !basket_items.empty?
62
+ raise ConfigurationError, 'paymentMethod SHOPPING_LOAN requires basketItems: the bank sets the loan term from the basket'
63
+ end
64
+ return if basket_items.size <= SHOPPING_LOAN_MAX_BASKET_ITEMS
65
+
66
+ raise ConfigurationError, "paymentMethod SHOPPING_LOAN takes at most #{SHOPPING_LOAN_MAX_BASKET_ITEMS} basket items"
67
+ end
68
+
69
+ # Body of POST /payments/{paymentId}/actions/{actionId}/confirm: otp, consentAccepted and fields only.
70
+ def confirm_body!(input)
71
+ raise ConfigurationError, 'Confirm input must be an object: { otp:, consentAccepted:, fields: }' unless input.is_a?(Hash)
72
+
73
+ data = JSON.parse(JsonBody.dump(input))
74
+ unknown = data.keys - PAYMENT_ACTION_CONFIRM_FIELDS
75
+ unless unknown.empty?
76
+ raise ConfigurationError, "Unknown confirm field(s): #{unknown.join(', ')}; a merchant server sends only #{PAYMENT_ACTION_CONFIRM_FIELDS.join(', ')}"
77
+ end
78
+
79
+ body = {}
80
+ unless data['otp'].nil?
81
+ raise ConfigurationError, 'otp must be the code the buyer entered, as digits' unless data['otp'].is_a?(String) && data['otp'].match?(OTP_PATTERN)
82
+
83
+ body['otp'] = data['otp']
84
+ end
85
+ unless data['consentAccepted'].nil?
86
+ raise ConfigurationError, 'consentAccepted must be a boolean' unless [true, false].include?(data['consentAccepted'])
87
+
88
+ body['consentAccepted'] = data['consentAccepted']
89
+ end
90
+ body['fields'] = method_fields!(data['fields'], 'fields') unless data['fields'].nil?
91
+ raise ConfigurationError, 'confirm_payment_action needs otp, consentAccepted or fields' if body.empty?
92
+
93
+ body
94
+ end
95
+
96
+ def field_key!(key, path)
97
+ return if key.is_a?(String) && key.match?(FIELD_KEY_PATTERN) && !RESERVED_FIELD_KEYS.include?(key)
98
+
99
+ raise ConfigurationError, "#{path} has an invalid field name: names start with a letter and contain only letters and digits"
100
+ end
101
+
102
+ def scalar?(value)
103
+ (value.is_a?(String) && value.length <= MAX_VALUE_LENGTH) ||
104
+ (value.is_a?(Integer) || (value.is_a?(Float) && value.finite?)) ||
105
+ [true, false].include?(value)
106
+ end
107
+
108
+ def field_value!(value, path, allow_list:)
109
+ return if scalar?(value)
110
+ return nested_object!(value, path) if value.is_a?(Hash)
111
+ return group!(value, path) if allow_list && value.is_a?(Array)
112
+
113
+ raise ConfigurationError, "#{path} must be a string (at most #{MAX_VALUE_LENGTH} characters), a number, a boolean, an object or a list of objects"
114
+ end
115
+
116
+ def nested_object!(value, path)
117
+ raise ConfigurationError, "#{path} can carry at most #{MAX_NESTED_KEYS} fields" if value.size > MAX_NESTED_KEYS
118
+
119
+ value.each do |key, field|
120
+ field_key!(key, path)
121
+ raise ConfigurationError, "#{path}.#{key} must be a string, a number or a boolean" unless scalar?(field)
122
+ end
123
+ end
124
+
125
+ def group!(items, path)
126
+ raise ConfigurationError, "#{path} can carry at most #{MAX_GROUP_ITEMS} items" if items.size > MAX_GROUP_ITEMS
127
+
128
+ items.each_with_index do |item, index|
129
+ item_path = "#{path}[#{index}]"
130
+ raise ConfigurationError, "#{item_path} must be an object" unless item.is_a?(Hash)
131
+ raise ConfigurationError, "#{item_path} can carry at most #{MAX_KEYS} fields" if item.size > MAX_KEYS
132
+
133
+ item.each do |key, field|
134
+ field_key!(key, item_path)
135
+ field_value!(field, "#{item_path}.#{key}", allow_list: false)
136
+ end
137
+ end
138
+ end
139
+
140
+ private_class_method :field_key!, :scalar?, :field_value!, :nested_object!, :group!
141
+ end
142
+ end