lunixi-sdk 1.2.2 → 1.3.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 (69) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -0
  3. data/README.md +262 -9
  4. data/README.tr.md +266 -7
  5. data/lib/lunixi/bank_connect.rb +340 -0
  6. data/lib/lunixi/bank_connect_filters.rb +114 -0
  7. data/lib/lunixi/bank_connect_values.rb +205 -0
  8. data/lib/lunixi/bank_transfer.rb +106 -0
  9. data/lib/lunixi/card_requests.rb +150 -0
  10. data/lib/lunixi/client.rb +57 -16
  11. data/lib/lunixi/direct_method_payment_request.rb +243 -0
  12. data/lib/lunixi/enabled_installments.rb +28 -0
  13. data/lib/lunixi/errors.rb +69 -3
  14. data/lib/lunixi/fraud.rb +81 -5
  15. data/lib/lunixi/identity.rb +94 -0
  16. data/lib/lunixi/identity_values.rb +28 -0
  17. data/lib/lunixi/insurance.rb +294 -0
  18. data/lib/lunixi/insurance_request.rb +134 -0
  19. data/lib/lunixi/insurance_values.rb +200 -0
  20. data/lib/lunixi/kyc.rb +189 -0
  21. data/lib/lunixi/kyc_values.rb +158 -0
  22. data/lib/lunixi/marketplace.rb +264 -0
  23. data/lib/lunixi/marketplace_values.rb +86 -0
  24. data/lib/lunixi/method_fields.rb +142 -0
  25. data/lib/lunixi/money.rb +7 -4
  26. data/lib/lunixi/payment_link_filters.rb +32 -0
  27. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  28. data/lib/lunixi/payment_link_rules.rb +132 -0
  29. data/lib/lunixi/payment_link_values.rb +134 -0
  30. data/lib/lunixi/payment_links.rb +152 -0
  31. data/lib/lunixi/payment_values.rb +86 -0
  32. data/lib/lunixi/payments.rb +154 -5
  33. data/lib/lunixi/physical_pos.rb +183 -0
  34. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  35. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  36. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  37. data/lib/lunixi/physical_pos_filters.rb +58 -0
  38. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  39. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  40. data/lib/lunixi/physical_pos_management.rb +326 -0
  41. data/lib/lunixi/physical_pos_money.rb +46 -0
  42. data/lib/lunixi/physical_pos_request.rb +126 -0
  43. data/lib/lunixi/physical_pos_responses.rb +102 -0
  44. data/lib/lunixi/physical_pos_results.rb +52 -0
  45. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  46. data/lib/lunixi/physical_pos_value.rb +43 -0
  47. data/lib/lunixi/physical_pos_values.rb +203 -0
  48. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  49. data/lib/lunixi/product_webhooks.rb +106 -0
  50. data/lib/lunixi/promissory_note.rb +155 -0
  51. data/lib/lunixi/reference.rb +41 -0
  52. data/lib/lunixi/route_request.rb +121 -0
  53. data/lib/lunixi/route_response.rb +101 -0
  54. data/lib/lunixi/route_table.rb +128 -0
  55. data/lib/lunixi/route_value.rb +60 -0
  56. data/lib/lunixi/sanction.rb +244 -0
  57. data/lib/lunixi/sanction_values.rb +132 -0
  58. data/lib/lunixi/split_payment.rb +145 -0
  59. data/lib/lunixi/subscription_resources.rb +355 -0
  60. data/lib/lunixi/subscription_values.rb +220 -0
  61. data/lib/lunixi/subscriptions.rb +202 -0
  62. data/lib/lunixi/version.rb +1 -1
  63. data/lib/lunixi/wallet.rb +153 -0
  64. data/lib/lunixi/wallet_resources.rb +402 -0
  65. data/lib/lunixi/wallet_routes.rb +123 -0
  66. data/lib/lunixi/wallet_values.rb +71 -0
  67. data/lib/lunixi/wire_money.rb +67 -0
  68. data/lib/lunixi.rb +57 -0
  69. metadata +58 -1
data/lib/lunixi/money.rb CHANGED
@@ -5,6 +5,7 @@ module Lunixi
5
5
  module Money
6
6
  MAX = 9_223_372_036_854_775_807
7
7
  EXPONENTS = %w[TRY USD EUR GBP RUB AED SAR QAR CHF CAD AUD CNY AZN].to_h { |c| [c, 2] }.merge('JPY' => 0, 'KWD' => 3).freeze
8
+
8
9
  module_function
9
10
 
10
11
  def fiat_route?(path)
@@ -53,19 +54,21 @@ module Lunixi
53
54
  next if entry.nil? || %w[metadata fields inputFields insuranceData].include?(key)
54
55
 
55
56
  if %w[
56
- amount amountMinor authorizedAmount availableBalance balanceMinor buyerTotalCharge cancelledPremiumAmount
57
+ amount amountMinor authorizedAmount availableBalance availableMinor availableWithoutOverdraftMinor balanceAfterMinor
58
+ balanceMinor blockedMinor buyerTotalCharge cancelledPremiumAmount
57
59
  capturedAmount capturedAmountMinor chargeAmount collectedAmountMinor collectedPremiumAmount compensatedAmount
58
60
  disputedAmount feeTotal fixedFee inForcePremiumAmount insuranceValueAmount legAmount legsAmount lineTotalMinor
59
- maxAmount maxAmountMinor minAmount minAmountMinor nonRefundableAmount paidAmount paidPrice pendingBalance
61
+ maxAmount maxAmountMinor minAmount minAmountMinor nonRefundableAmount overdraftAvailableMinor paidAmount paidPrice pendingBalance
60
62
  premiumAmount price refundAmount refundOpenPremiumAmount refundableAmount refundedAmount refundedAmountMinor
61
- refundedPremiumAmount requestedAmount reservedBalance sourceAmountMinor targetAmountMinor taxAmountMinor taxTotal
63
+ refundedPremiumAmount requestedAmount reservedBalance sourceAmountMinor sourceBalanceAfterMinor targetAmountMinor
64
+ targetBalanceAfterMinor taxAmountMinor taxTotal
62
65
  totalAmount unitPriceMinor
63
66
  ].include?(key)
64
67
  minor(entry, positive: !response && %w[amount price totalAmount].include?(key), signed: key.downcase.include?('balance'))
65
68
  elsif %w[
66
69
  data details items rows results payments operations balances wallets legs aggregate refund refunds totals
67
70
  charge fees fee balance splits sellers basketItems promissoryNote schedule notes lines offers policies
68
- reconciliation quotes payment transactions accounts settlements payouts limits
71
+ reconciliation quotes payment transactions accounts settlements payouts limits options quote
69
72
  ].include?(key)
70
73
  validate_fields(entry, response: response)
71
74
  end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'time'
4
+
5
+ module Lunixi
6
+ # Local checks of the payment-link list filters (links, attempts and payments of a link).
7
+ module PaymentLinkFilters
8
+ LINK_LIST_FILTERS = %w[limit cursor includeTotal state usage amountMode environment tag branchCode createdById query
9
+ createdFrom createdTo].freeze
10
+ ATTEMPT_LIST_FILTERS = %w[limit cursor includeTotal state].freeze
11
+ PAYMENT_LIST_FILTERS = %w[limit cursor includeTotal].freeze
12
+
13
+ module_function
14
+
15
+ # Lists accept an Array for state, usage and amountMode (sent as a comma list) and a Time for the
16
+ # createdFrom / createdTo window.
17
+ def list_query!(filters, allowed, operation)
18
+ data = filters.transform_keys(&:to_s)
19
+ unknown = data.keys - allowed
20
+ raise ConfigurationError, "#{operation} does not take #{unknown.join(', ')}; filters: #{allowed.join(', ')}" unless unknown.empty?
21
+
22
+ allowed.each_with_object({}) do |key, query|
23
+ value = data[key]
24
+ next if value.nil? || value == ''
25
+
26
+ value = value.join(',') if value.is_a?(Array)
27
+ value = value.getutc.iso8601(3) if value.is_a?(Time)
28
+ query[key] = value unless value == ''
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'uri'
4
+
5
+ module Lunixi
6
+ # Local checks of the payment-link image uploads: the create body, the bytes, the upload target the
7
+ # gateway hands back and the confirmed image.
8
+ module PaymentLinkImageRules
9
+ FILE_NAME_MAX_LENGTH = 255
10
+ UPLOAD_HEADER_NAME = /\A[A-Za-z0-9-]{1,64}\z/
11
+ UPLOAD_HEADER_VALUE_MAX = 1024
12
+
13
+ module_function
14
+
15
+ def asset_id!(value)
16
+ raise ConfigurationError, "asset_id must be the image's asset id (UUID)" unless value.is_a?(String) && value.match?(PAYMENT_LINK_ASSET_ID_PATTERN)
17
+
18
+ value
19
+ end
20
+
21
+ def image_body!(file_name, content_type, size_bytes)
22
+ unless file_name.is_a?(String) && !file_name.strip.empty? && file_name.length <= FILE_NAME_MAX_LENGTH
23
+ raise ConfigurationError, "file_name must be 1–#{FILE_NAME_MAX_LENGTH} characters"
24
+ end
25
+ unless PaymentLinkImageContentType::ALL.include?(content_type)
26
+ raise ConfigurationError, "Image content_type must be one of #{PaymentLinkImageContentType::ALL.join(', ')} (SVG is not accepted)"
27
+ end
28
+ unless size_bytes.is_a?(Integer) && size_bytes.between?(1, JsonBody::MAX_SAFE_INTEGER)
29
+ raise ConfigurationError, 'Image size_bytes must be the file size in bytes (a positive integer)'
30
+ end
31
+
32
+ { 'fileName' => file_name, 'contentType' => content_type, 'sizeBytes' => size_bytes }
33
+ end
34
+
35
+ def image_content!(content)
36
+ raise ConfigurationError, 'Image content must be a nonempty binary String' unless content.is_a?(String) && !content.empty?
37
+
38
+ content.b
39
+ end
40
+
41
+ # An upload target is used only if the SDK can PUT to it as documented: an asset id, an HTTPS URL
42
+ # without credentials, the PUT method and string headers. Anything else fails before a byte is sent.
43
+ def upload_target!(envelope)
44
+ target = envelope.is_a?(Hash) ? envelope['data'] : nil
45
+ usable = target.is_a?(Hash) && target['assetId'].is_a?(String) && target['assetId'].match?(PAYMENT_LINK_ASSET_ID_PATTERN) &&
46
+ upload_url?(target['uploadUrl']) && target['uploadMethod'] == 'PUT' && upload_headers?(target['uploadHeaders'])
47
+ raise ApiError.new(status: 502, code: 'invalid_image_upload_target') unless usable
48
+
49
+ target
50
+ end
51
+
52
+ def published_image!(envelope)
53
+ image = envelope.is_a?(Hash) ? envelope['data'] : nil
54
+ return if image.is_a?(Hash) && image['assetId'].is_a?(String) && image['state'] == 'PUBLISHED'
55
+
56
+ raise ApiError.new(status: 502, code: 'image_not_published')
57
+ end
58
+
59
+ # S3-compatible storage answers errors as XML: <Error><Code>AccessDenied</Code>…
60
+ def storage_error_code(body)
61
+ match = body.to_s.b.match(%r{<Code>([A-Za-z0-9.]{1,64})</Code>})
62
+ match && match[1]
63
+ end
64
+
65
+ def upload_url?(value)
66
+ uri = URI.parse(value)
67
+ uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.userinfo.nil? && uri.fragment.nil? && value.bytesize <= 8192
68
+ rescue URI::InvalidURIError, TypeError
69
+ false
70
+ end
71
+
72
+ def upload_headers?(headers)
73
+ return false unless headers.is_a?(Hash) && headers.size <= 32
74
+
75
+ headers.all? { |name, value| upload_header?(name, value) }
76
+ end
77
+
78
+ def upload_header?(name, value)
79
+ name.is_a?(String) && name.match?(UPLOAD_HEADER_NAME) && value.is_a?(String) &&
80
+ value.bytesize <= UPLOAD_HEADER_VALUE_MAX && !value.match?(/[\x00-\x1f\x7f]/)
81
+ end
82
+
83
+ private_class_method :upload_url?, :upload_headers?, :upload_header?
84
+ end
85
+ end
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'time'
4
+
5
+ module Lunixi
6
+ # Local checks of the payment-link bodies (list filters: PaymentLinkFilters; image uploads:
7
+ # PaymentLinkImageRules).
8
+ module PaymentLinkRules
9
+ CREATE_FIELDS = (['environment'] + PAYMENT_LINK_SPEC_FIELDS).freeze
10
+ UPDATE_FIELDS = PAYMENT_LINK_SPEC_FIELDS
11
+ TIME_FIELDS = %w[startsAt expiresAt eventAt].freeze
12
+ LINK_ACTIONS = %w[pause resume deactivate].freeze
13
+ QR_MIN_SIZE = 128
14
+ QR_MAX_SIZE = 2048
15
+
16
+ module_function
17
+
18
+ def create_body!(body)
19
+ data = root!(body, 'Payment link request')
20
+ known!(data, CREATE_FIELDS, 'create')
21
+ times(data)
22
+ end
23
+
24
+ # Only the given keys are updated; nil clears a field.
25
+ def update_body!(changes)
26
+ data = root!(changes, 'Payment link changes')
27
+ raise ConfigurationError, 'Payment link update needs at least one changed field' if data.empty?
28
+
29
+ fixed = data.keys.find { |key| PAYMENT_LINK_IMMUTABLE_FIELDS.include?(key) }
30
+ raise ConfigurationError, "'#{fixed}' is fixed when a payment link is created and cannot be updated; create a new link instead" if fixed
31
+
32
+ known!(data, UPDATE_FIELDS, 'update')
33
+ times(data)
34
+ end
35
+
36
+ # pause / resume / deactivate body: expectedRowVersion (optional) and reason.
37
+ def action_body!(action, expected_row_version, reason)
38
+ raise ConfigurationError, "Payment link action must be one of #{LINK_ACTIONS.join(', ')}" unless LINK_ACTIONS.include?(action.to_s)
39
+
40
+ body = {}
41
+ body['expectedRowVersion'] = row_version!(expected_row_version) unless expected_row_version.nil?
42
+ body['reason'] = reason.to_s unless reason.nil?
43
+ body
44
+ end
45
+
46
+ def send_body!(channel, recipient_email, recipient_phone, locale)
47
+ unless PaymentLinkDeliveryChannel::ALL.include?(channel)
48
+ raise ConfigurationError, "Send channel must be one of #{PaymentLinkDeliveryChannel::ALL.join(', ')}"
49
+ end
50
+
51
+ body = { 'channel' => channel }
52
+ body['recipientEmail'] = recipient_email.to_s unless recipient_email.nil?
53
+ body['recipientPhone'] = recipient_phone.to_s unless recipient_phone.nil?
54
+ unless locale.nil?
55
+ raise ConfigurationError, "Send locale must be one of #{PaymentLinkLocale::ALL.join(', ')}" unless PaymentLinkLocale::ALL.include?(locale)
56
+
57
+ body['locale'] = locale
58
+ end
59
+ body
60
+ end
61
+
62
+ def qr_query!(format, size)
63
+ raise ConfigurationError, "QR format must be one of #{PaymentLinkQrFormat::ALL.join(', ')}" unless PaymentLinkQrFormat::ALL.include?(format)
64
+
65
+ query = { 'format' => format }
66
+ return query if size.nil?
67
+ unless size.is_a?(Integer) && size.between?(QR_MIN_SIZE, QR_MAX_SIZE)
68
+ raise ConfigurationError, "QR size must be an integer in pixels, #{QR_MIN_SIZE}-#{QR_MAX_SIZE}"
69
+ end
70
+
71
+ query.merge('size' => size)
72
+ end
73
+
74
+ def row_version!(value)
75
+ unless value.is_a?(Integer) && value.between?(0, JsonBody::MAX_SAFE_INTEGER)
76
+ raise ConfigurationError, "expectedRowVersion must be the link's current rowVersion (a nonnegative integer)"
77
+ end
78
+
79
+ value
80
+ end
81
+
82
+ def link_id!(value)
83
+ raise ConfigurationError, 'link_id is required' unless value.is_a?(String) && value.match?(/\A[a-zA-Z0-9_-]{1,256}\z/)
84
+
85
+ value
86
+ end
87
+
88
+ def root!(body, name)
89
+ raise ConfigurationError, "#{name} must be an object" unless body.is_a?(Hash)
90
+
91
+ body.each_with_object({}) do |(key, value), data|
92
+ raise ConfigurationError, "#{name} keys must be strings or symbols" unless key.is_a?(String) || key.is_a?(Symbol)
93
+ raise ConfigurationError, "#{name} repeats the key #{key}" if data.key?(key.to_s)
94
+
95
+ data[key.to_s] = value
96
+ end
97
+ end
98
+
99
+ def known!(data, allowed, operation)
100
+ unknown = data.keys - allowed
101
+ return if unknown.empty?
102
+
103
+ raise ConfigurationError, "Unknown payment link #{operation} field(s): #{unknown.join(', ')}; the gateway rejects unknown fields with 400"
104
+ end
105
+
106
+ # A Time is sent as ISO 8601 (UTC, milliseconds); a String as given; nil clears the value.
107
+ def times(data)
108
+ TIME_FIELDS.each do |key|
109
+ next unless data.key?(key)
110
+
111
+ value = data[key]
112
+ next if value.nil?
113
+
114
+ data[key] = time_value!(value, key)
115
+ end
116
+ data
117
+ end
118
+
119
+ def time_value!(value, key)
120
+ return iso8601(value) if value.is_a?(Time)
121
+ return value if value.is_a?(String) && !value.strip.empty?
122
+
123
+ raise ConfigurationError, "#{key} must be a Time, an ISO 8601 string or nil"
124
+ end
125
+
126
+ def iso8601(time)
127
+ time.getutc.iso8601(3)
128
+ end
129
+
130
+ private_class_method :root!, :known!, :times, :time_value!, :iso8601
131
+ end
132
+ end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Closed value sets of the payment-link API (/api/v1/payments/links). The gateway answers an unknown
5
+ # value with 400.
6
+ module PaymentLinkUsage
7
+ # Can be paid once: an invoice or a personal payment request.
8
+ SINGLE_USE = 'SINGLE_USE'
9
+ # Can be paid many times: donations, tickets, a product page.
10
+ MULTI_USE = 'MULTI_USE'
11
+
12
+ ALL = [SINGLE_USE, MULTI_USE].freeze
13
+ end
14
+
15
+ module PaymentLinkAmountMode
16
+ # The merchant sets the amount (amountMinor).
17
+ FIXED = 'FIXED'
18
+ # The buyer enters the amount, bounded by minAmountMinor / maxAmountMinor.
19
+ OPEN = 'OPEN'
20
+ # The buyer picks quantities from items; the amount is the sum of the lines.
21
+ ITEMIZED = 'ITEMIZED'
22
+
23
+ ALL = [FIXED, OPEN, ITEMIZED].freeze
24
+ end
25
+
26
+ module PaymentLinkState
27
+ ACTIVE = 'ACTIVE'
28
+ PAUSED = 'PAUSED'
29
+ COMPLETED = 'COMPLETED'
30
+ EXPIRED = 'EXPIRED'
31
+ DEACTIVATED = 'DEACTIVATED'
32
+ # Removed by Lunixi. Every write on the link answers 409 payment_link.link.taken_down.
33
+ TAKEN_DOWN = 'TAKEN_DOWN'
34
+
35
+ ALL = [ACTIVE, PAUSED, COMPLETED, EXPIRED, DEACTIVATED, TAKEN_DOWN].freeze
36
+ end
37
+
38
+ module PaymentLinkAttemptState
39
+ OPEN = 'OPEN'
40
+ BOUND = 'BOUND'
41
+ SUCCEEDED = 'SUCCEEDED'
42
+ FAILED = 'FAILED'
43
+ EXPIRED = 'EXPIRED'
44
+ ABANDONED = 'ABANDONED'
45
+ NEEDS_REVIEW = 'NEEDS_REVIEW'
46
+
47
+ ALL = [OPEN, BOUND, SUCCEEDED, FAILED, EXPIRED, ABANDONED, NEEDS_REVIEW].freeze
48
+ end
49
+
50
+ module PaymentLinkEnvironment
51
+ TEST = 'TEST'
52
+ LIVE = 'LIVE'
53
+
54
+ ALL = [TEST, LIVE].freeze
55
+ end
56
+
57
+ module BuyerFieldRequirement
58
+ HIDDEN = 'HIDDEN'
59
+ OPTIONAL = 'OPTIONAL'
60
+ REQUIRED = 'REQUIRED'
61
+
62
+ ALL = [HIDDEN, OPTIONAL, REQUIRED].freeze
63
+ end
64
+
65
+ module CustomFieldType
66
+ TEXT = 'TEXT'
67
+ NUMBER = 'NUMBER'
68
+ EMAIL = 'EMAIL'
69
+ PHONE = 'PHONE'
70
+ DATE = 'DATE'
71
+ SELECT = 'SELECT'
72
+ CHECKBOX = 'CHECKBOX'
73
+ TCKN = 'TCKN'
74
+ VKN = 'VKN'
75
+
76
+ ALL = [TEXT, NUMBER, EMAIL, PHONE, DATE, SELECT, CHECKBOX, TCKN, VKN].freeze
77
+ end
78
+
79
+ module PaymentLinkButtonLabel
80
+ PAY = 'PAY'
81
+ DONATE = 'DONATE'
82
+ BUY = 'BUY'
83
+ BOOK = 'BOOK'
84
+
85
+ ALL = [PAY, DONATE, BUY, BOOK].freeze
86
+ end
87
+
88
+ module PaymentLinkDeliveryChannel
89
+ EMAIL = 'EMAIL'
90
+ SMS = 'SMS'
91
+
92
+ ALL = [EMAIL, SMS].freeze
93
+ end
94
+
95
+ module PaymentLinkQrFormat
96
+ SVG = 'svg'
97
+ PNG = 'png'
98
+
99
+ ALL = [SVG, PNG].freeze
100
+ end
101
+
102
+ module PaymentLinkLocale
103
+ TR = 'tr'
104
+ EN = 'en'
105
+
106
+ ALL = [TR, EN].freeze
107
+ end
108
+
109
+ # Types a payment-link image can be declared as. On confirmation the stored file's own bytes are
110
+ # checked against the declared type; SVG is never accepted.
111
+ module PaymentLinkImageContentType
112
+ PNG = 'image/png'
113
+ JPEG = 'image/jpeg'
114
+ WEBP = 'image/webp'
115
+
116
+ ALL = [PNG, JPEG, WEBP].freeze
117
+ end
118
+
119
+ # Every field of a payment-link definition in the gateway's spelling. Create and update bodies may
120
+ # carry only these keys (plus environment on create); the gateway rejects any other key with 400.
121
+ PAYMENT_LINK_SPEC_FIELDS = %w[
122
+ usage amountMode currency amountMinor minAmountMinor maxAmountMinor suggestedAmountsMinor quantityEnabled
123
+ minQuantity maxQuantity items capacity title description imageAssetId successMessage successRedirectUrl taxNote
124
+ locale startsAt expiresAt eventAt buttonLabelKey requireTermsAcceptance buyerFields customFields recipient prefill
125
+ verification reminders checkout reference tags branchCode salesChannel campaign agentCode merchantNotifyEmails
126
+ metadata
127
+ ].freeze
128
+
129
+ # Fixed when the link is created; an update that names one answers 422 payment_link.link.immutable_field.
130
+ PAYMENT_LINK_IMMUTABLE_FIELDS = %w[usage amountMode currency].freeze
131
+
132
+ # Shape of a media asset id (a UUID); ownership and state are checked by the gateway.
133
+ PAYMENT_LINK_ASSET_ID_PATTERN = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
134
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Payment links (/api/v1/payments/links). Every gateway call here is signed, reads included: the
5
+ # merchant and the environment come from the signing key, so a TEST key sees and changes only TEST
6
+ # links. The key needs the matching scope (payment-link:create, :view, :manage, :send).
7
+ #
8
+ # Responses are the gateway envelope. Lists carry data.items and the top-level pageInfo
9
+ # (hasMore, nextCursor, totalCount); pass pageInfo.nextCursor as cursor for the next page.
10
+ #
11
+ # The one request that is not sent to the gateway is the image PUT of upload_image: it goes to the
12
+ # storage host behind a presigned URL with only the uploadHeaders, never with the access token or the
13
+ # request signature.
14
+ class PaymentLinks
15
+ BASE = '/api/v1/payments/links'
16
+ IMAGES = "#{BASE}/images".freeze
17
+ QR_ACCEPT = 'image/svg+xml, image/png, application/json'
18
+ attr_reader :client
19
+
20
+ def initialize(client, storage_transport:)
21
+ @client = client
22
+ @storage_transport = storage_transport
23
+ end
24
+
25
+ # Create a link. The idempotency key is required: the same key with the same body returns the stored
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.
28
+ def create(body, idempotency_key: nil)
29
+ client.request('POST', BASE, body: PaymentLinkRules.create_body!(body), idempotency_key: Client.idempotency_key!(idempotency_key))
30
+ end
31
+
32
+ # One page of links, newest first. state, usage and amountMode take an Array; createdFrom /
33
+ # createdTo (a Time or ISO 8601 string) bound a half-open window; query matches a short code or a
34
+ # title/reference prefix.
35
+ def list(**filters)
36
+ client.request('GET', BASE, query: PaymentLinkFilters.list_query!(filters, PaymentLinkFilters::LINK_LIST_FILTERS, 'payment_links.list'))
37
+ end
38
+
39
+ def get(link_id)
40
+ client.request('GET', link_path(link_id))
41
+ end
42
+
43
+ # Change a link (a new version of it). expected_row_version is the link's current rowVersion; a
44
+ # concurrent change is 409 payment_link.link.version_conflict. Only the given keys change, nil clears
45
+ # a field and a nested object is replaced whole. usage, amountMode and currency are fixed.
46
+ def update(link_id, expected_row_version, changes, idempotency_key: nil)
47
+ body = { 'expectedRowVersion' => PaymentLinkRules.row_version!(expected_row_version) }.merge(PaymentLinkRules.update_body!(changes))
48
+ client.request('PATCH', link_path(link_id), body: body, idempotency_key: optional_key(idempotency_key))
49
+ end
50
+
51
+ # Stop accepting payments until resume.
52
+ def pause(link_id, expected_row_version: nil, reason: nil, idempotency_key: nil)
53
+ action(link_id, 'pause', expected_row_version: expected_row_version, reason: reason, idempotency_key: idempotency_key)
54
+ end
55
+
56
+ def resume(link_id, expected_row_version: nil, reason: nil, idempotency_key: nil)
57
+ action(link_id, 'resume', expected_row_version: expected_row_version, reason: reason, idempotency_key: idempotency_key)
58
+ end
59
+
60
+ # Close the link permanently; it cannot be reopened.
61
+ def deactivate(link_id, expected_row_version: nil, reason: nil, idempotency_key: nil)
62
+ action(link_id, 'deactivate', expected_row_version: expected_row_version, reason: reason, idempotency_key: idempotency_key)
63
+ end
64
+
65
+ # pause, resume or deactivate. Without expected_row_version there is no version check.
66
+ def action(link_id, action, expected_row_version: nil, reason: nil, idempotency_key: nil)
67
+ body = PaymentLinkRules.action_body!(action, expected_row_version, reason)
68
+ client.request('POST', "#{link_path(link_id)}/#{action}", body: body, idempotency_key: optional_key(idempotency_key))
69
+ end
70
+
71
+ # Send the link by e-mail or SMS (PaymentLinkDeliveryChannel); without a recipient the link's
72
+ # recipient is used. The idempotency key is required so a retry cannot send twice. An accepted
73
+ # delivery can still fail: read data.delivery.state and failureReason.
74
+ def send_link(link_id, channel: nil, recipient_email: nil, recipient_phone: nil, locale: nil, idempotency_key: nil)
75
+ body = PaymentLinkRules.send_body!(channel, recipient_email, recipient_phone, locale)
76
+ client.request('POST', "#{link_path(link_id)}/send", body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
77
+ end
78
+
79
+ # The link's QR code as frozen image bytes (SVG or PNG, PaymentLinkQrFormat); size is 128–2048 px.
80
+ def qr(link_id, format: PaymentLinkQrFormat::SVG, size: nil)
81
+ client.request('GET', "#{link_path(link_id)}/qr", query: PaymentLinkRules.qr_query!(format, size), binary: true, accept: QR_ACCEPT)
82
+ end
83
+
84
+ # Payment attempts on the link, newest first; state takes an Array.
85
+ def list_attempts(link_id, **filters)
86
+ query = PaymentLinkFilters.list_query!(filters, PaymentLinkFilters::ATTEMPT_LIST_FILTERS, 'payment_links.list_attempts')
87
+ client.request('GET', "#{link_path(link_id)}/attempts", query: query)
88
+ end
89
+
90
+ # Successful payments on the link, with refund totals.
91
+ def list_payments(link_id, **filters)
92
+ query = PaymentLinkFilters.list_query!(filters, PaymentLinkFilters::PAYMENT_LIST_FILTERS, 'payment_links.list_payments')
93
+ client.request('GET', "#{link_path(link_id)}/payments", query: query)
94
+ end
95
+
96
+ # Link image, step 1 of 3: an upload target for a PNG, JPEG or WebP image. data is { assetId,
97
+ # uploadUrl, uploadMethod: 'PUT', uploadHeaders, expiresAt }. Step 2 is a PUT of the bytes to
98
+ # uploadUrl with exactly uploadHeaders before expiresAt; step 3 is confirm_image_upload(assetId).
99
+ # A declared size over the image limit (2 MiB) is refused by the gateway before anything is uploaded.
100
+ def create_image_upload(file_name: nil, content_type: nil, size_bytes: nil)
101
+ body = PaymentLinkImageRules.image_body!(file_name, content_type, size_bytes)
102
+ envelope = client.request('POST', IMAGES, body: body)
103
+ PaymentLinkImageRules.upload_target!(envelope)
104
+ envelope
105
+ end
106
+
107
+ # Link image, step 3 of 3: publish the uploaded image. data is { assetId, url, state: 'PUBLISHED' };
108
+ # use assetId as the imageAssetId of a link or an item. Confirming before the PUT has landed is
109
+ # 400 media.confirm.object_missing and can be retried.
110
+ def confirm_image_upload(asset_id)
111
+ envelope = client.request('POST', "#{IMAGES}/#{PaymentLinkImageRules.asset_id!(asset_id)}/confirm", body: {})
112
+ PaymentLinkImageRules.published_image!(envelope)
113
+ envelope
114
+ end
115
+
116
+ # Upload a link image in one call: create_image_upload, the PUT of content to the storage host and
117
+ # confirm_image_upload. A failed PUT is not retried; it raises ApiError with the storage status (and
118
+ # its error code, e.g. AccessDenied once the URL has expired). Call upload_image again for a new URL.
119
+ def upload_image(file_name: nil, content_type: nil, content: nil)
120
+ bytes = PaymentLinkImageRules.image_content!(content)
121
+ target = PaymentLinkImageRules.upload_target!(create_image_upload(file_name: file_name, content_type: content_type, size_bytes: bytes.bytesize))
122
+ put_to_storage(target, bytes)
123
+ confirm_image_upload(target['assetId'])
124
+ end
125
+
126
+ def inspect
127
+ '#<Lunixi::PaymentLinks>'
128
+ end
129
+
130
+ private
131
+
132
+ # The PUT deliberately does not use Client#request: that adds the bearer token and the signature
133
+ # headers, which must never reach the storage host. Only the headers the URL was signed for are sent.
134
+ def put_to_storage(target, bytes)
135
+ response = @storage_transport.call(method: 'PUT', uri: URI.parse(target['uploadUrl']), headers: target['uploadHeaders'].dup.freeze, body: bytes)
136
+ raise TransportError, 'Image upload to storage returned an invalid response' unless response.is_a?(Response) && response.status.is_a?(Integer)
137
+ return if response.status.between?(200, 299)
138
+
139
+ raise ApiError.new(status: response.status, code: PaymentLinkImageRules.storage_error_code(response.body))
140
+ rescue TransportError
141
+ raise TransportError, 'Image upload to storage failed; call upload_image again for a new upload URL', cause: nil
142
+ end
143
+
144
+ def link_path(link_id)
145
+ "#{BASE}/#{PaymentLinkRules.link_id!(link_id)}"
146
+ end
147
+
148
+ def optional_key(key)
149
+ key.nil? ? nil : Client.idempotency_key!(key)
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Public payment method codes (paymentMethod). QR is accepted as an alias of QR_CODE.
5
+ module PaymentMethod
6
+ CARD = 'CARD'
7
+ BNPL = 'BNPL'
8
+ SHOPPING_LOAN = 'SHOPPING_LOAN'
9
+ PROMISSORY_NOTE = 'PROMISSORY_NOTE'
10
+ MEAL_CARD = 'MEAL_CARD'
11
+ GIFT_CARD = 'GIFT_CARD'
12
+ CASH = 'CASH'
13
+ CASH_ON_DELIVERY = 'CASH_ON_DELIVERY'
14
+ WALLET = 'WALLET'
15
+ BANK_TRANSFER = 'BANK_TRANSFER'
16
+ OPEN_BANKING = 'OPEN_BANKING'
17
+ # Charge to the buyer's mobile phone bill.
18
+ MOBILE_BILLING = 'MOBILE_BILLING'
19
+ QR_CODE = 'QR_CODE'
20
+ CRYPTO = 'CRYPTO'
21
+ OTHER = 'OTHER'
22
+
23
+ ALL = [CARD, BNPL, SHOPPING_LOAN, PROMISSORY_NOTE, MEAL_CARD, GIFT_CARD, CASH, CASH_ON_DELIVERY, WALLET,
24
+ BANK_TRANSFER, OPEN_BANKING, MOBILE_BILLING, QR_CODE, CRYPTO, OTHER].freeze
25
+ ALIASES = { 'QR' => QR_CODE }.freeze
26
+ end
27
+
28
+ # What the buyer must do when a payment response carries data.action (action.type).
29
+ module PaymentActionType
30
+ # Send the one-time code with payments.confirm_payment_action.
31
+ OTP = 'OTP'
32
+ # Send the buyer to action.redirect.url (for cards: the bank's 3D Secure page).
33
+ REDIRECT = 'REDIRECT'
34
+ # Show the buyer something to act on outside the page (transfer details, a code).
35
+ DISPLAY = 'DISPLAY'
36
+ # The buyer approves in the provider's app; the result arrives by webhook.
37
+ APP_APPROVAL = 'APP_APPROVAL'
38
+ # Send the fields listed in action.input.fields with payments.confirm_payment_action.
39
+ INPUT = 'INPUT'
40
+
41
+ ALL = [OTP, REDIRECT, DISPLAY, APP_APPROVAL, INPUT].freeze
42
+ end
43
+
44
+ # providerSelection of a method in payments.list_payment_methods.
45
+ module ProviderSelection
46
+ # Card: routing picks the provider; providerCode is not sent.
47
+ ROUTED = 'ROUTED'
48
+ # providerCode may be omitted: one provider is connected, or the platform picks it.
49
+ OPTIONAL = 'OPTIONAL'
50
+ # The buyer picks the brand and more than one provider is connected; providerCode must be sent.
51
+ REQUIRED = 'REQUIRED'
52
+
53
+ ALL = [ROUTED, OPTIONAL, REQUIRED].freeze
54
+ end
55
+
56
+ # providerSelectionMode of a method in payments.list_payment_methods: who picks the provider.
57
+ module ProviderSelectionMode
58
+ # The buyer picks the brand; with more than one provider connected providerCode is required.
59
+ BUYER = 'BUYER'
60
+ # The buyer does not pick a brand; without providerCode the platform picks a connected provider.
61
+ PLATFORM = 'PLATFORM'
62
+
63
+ ALL = [BUYER, PLATFORM].freeze
64
+ end
65
+
66
+ # Method blocks POST /payments/direct/payment accepts besides card. The block of the chosen
67
+ # method is required; a block for another method is rejected. A method without a block here
68
+ # cannot be paid through direct/payment yet.
69
+ METHOD_BLOCK_FIELDS = %w[mobileBilling wallet promissoryNote mealCard openBanking shoppingLoan bankTransfer].freeze
70
+
71
+ # Body fields of POST /payments/direct/payment.
72
+ DIRECT_METHOD_PAYMENT_FIELDS = (%w[
73
+ paymentMethod amount currency orderId paymentChannel paymentGroup callbackUrl locale description customerId
74
+ preauth buyer shippingAddress billingAddress basketItems card installment installmentQuoteToken force3D metadata
75
+ ] + METHOD_BLOCK_FIELDS).freeze
76
+
77
+ # Fields that belong to a card payment only (paymentMethod CARD).
78
+ CARD_ONLY_FIELDS = %w[card installment installmentQuoteToken force3D].freeze
79
+
80
+ # Body fields of POST /payments/{paymentId}/actions/{actionId}/confirm a merchant server sends.
81
+ # The hosted form's checkout token fields are never sent by this SDK.
82
+ PAYMENT_ACTION_CONFIRM_FIELDS = %w[otp consentAccepted fields].freeze
83
+
84
+ # Most basket items a SHOPPING_LOAN payment can carry; the basket is required for that method.
85
+ SHOPPING_LOAN_MAX_BASKET_ITEMS = 100
86
+ end