paysafe-tz 0.1.0

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.
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaySafe
4
+ module Resources
5
+ class Transfers < Base
6
+ # Moves money from this project's available balance to another PaySafe project (201).
7
+ def create(params, opts = {})
8
+ p = Util.stringify(params)
9
+ Validate.required(p["to"], "to")
10
+ Validate.string(p["to"], "to", 3, 31)
11
+ Validate.amount(p["amount"], 1, 2**62, "amount")
12
+ Validate.enum(p["currency"], "currency", %w[TZS])
13
+ Validate.string(p["note"], "note", 0, 140)
14
+ decode(send("POST", path("transfers"), body: encode(p), opts: RequestOptions.with_key(opts)), Transfer)
15
+ end
16
+
17
+ def list(params = {}, opts = {})
18
+ p = Util.stringify(params)
19
+ Page.from_response(send("GET", path("transfers"), query: query(p), opts: opts), Transfer) { |cursor| list(p.merge("cursor" => cursor), opts) }
20
+ end
21
+
22
+ def get(id, opts = {})
23
+ decode(send("GET", path("transfers", Validate.id(id)), opts: opts), Transfer)
24
+ end
25
+
26
+ def wait_for_terminal(id, interval: nil, timeout: nil, on_update: nil, should_stop: nil)
27
+ Validate.id(id)
28
+ poll(fetch: -> { get(id) }, terminal: lambda(&:terminal?), default_interval: 2.0, default_timeout: 120.0, what: "transfer #{id}",
29
+ interval: interval, timeout: timeout, on_update: on_update, should_stop: should_stop)
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaySafe
4
+ module Resources
5
+ class WebhookEndpoints < Base
6
+ # Every endpoint of the project; the API does not paginate this resource.
7
+ def list(opts = {})
8
+ response = send("GET", path("webhook-endpoints"), opts: opts)
9
+ Array(response.json&.dig("data")).grep(Hash).map { |e| WebhookEndpoint.from(e, response) }
10
+ end
11
+
12
+ # Registers an endpoint. The signing secret is only returned here; store it immediately.
13
+ def create(params, opts = {})
14
+ p = Util.stringify(params)
15
+ Validate.required(p["url"], "url")
16
+ Validate.url(p["url"], "url", 500)
17
+ Validate.string(p["description"], "description", 0, 255)
18
+ validate_events(p["events"])
19
+ decode(send("POST", path("webhook-endpoints"), body: encode(p), opts: opts), WebhookEndpoint)
20
+ end
21
+
22
+ def get(id, opts = {})
23
+ decode(send("GET", path("webhook-endpoints", Validate.id(id)), opts: opts), WebhookEndpoint)
24
+ end
25
+
26
+ def update(id, params, opts = {})
27
+ p = Util.stringify(params)
28
+ Validate.url(p["url"], "url", 500)
29
+ Validate.string(p["description"], "description", 0, 255)
30
+ Validate.enum(p["status"], "status", %w[ENABLED DISABLED])
31
+ validate_events(p["events"])
32
+ decode(send("PATCH", path("webhook-endpoints", Validate.id(id)), body: encode(p), opts: opts), WebhookEndpoint)
33
+ end
34
+
35
+ def delete(id, opts = {})
36
+ send("DELETE", path("webhook-endpoints", Validate.id(id)), opts: opts)
37
+ nil
38
+ end
39
+
40
+ private
41
+
42
+ def validate_events(events)
43
+ return if events.nil?
44
+ unless events.is_a?(Array) && !events.empty?
45
+ raise InvalidRequestError.new('events must be a non-empty list of event types or ["*"]',
46
+ "events")
47
+ end
48
+
49
+ events.each do |e|
50
+ raise InvalidRequestError.new("Unknown event type #{e}", "events") unless e == "*" || Event::TYPES.include?(e)
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaySafe
4
+ module Util
5
+ module_function
6
+
7
+ def encode(value)
8
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
9
+ end
10
+
11
+ # Symbol keys become strings recursively; nil values are dropped at the top level.
12
+ def stringify(params)
13
+ raise InvalidRequestError, "params must be a Hash" unless params.is_a?(Hash)
14
+
15
+ deep = lambda { |v|
16
+ if v.is_a?(Hash)
17
+ v.to_h { |k, x| [k.to_s, deep.call(x)] }
18
+ else
19
+ (v.is_a?(Array) ? v.map { |x| deep.call(x) } : v)
20
+ end
21
+ }
22
+ deep.call(params).compact
23
+ end
24
+
25
+ def parse_json(text)
26
+ JSON.parse(text, max_nesting: 32)
27
+ rescue JSON::ParserError
28
+ nil
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaySafe
4
+ module Validate
5
+ MAX_BODY_BYTES = 65_536
6
+ MAX_METADATA_BYTES = 8192
7
+ ID = /\A[A-Za-z0-9_-]{1,64}\z/
8
+ HEADER_NAME = /\A[A-Za-z0-9-]{1,100}\z/
9
+ REQUEST_ID = /\A[A-Za-z0-9._-]{8,64}\z/
10
+ PHONE = /\A\+255[0-9]{9}\z/
11
+ QUERY_KEY = /\A[A-Za-z0-9_]{1,40}\z/
12
+ DATE_TIME = /\A\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2}))?\z/
13
+ API_KEY = /\A[A-Za-z0-9_]+\z/
14
+ PROTECTED_HEADERS = %w[authorization host content-length transfer-encoding connection].freeze
15
+ LOOPBACK = %w[localhost 127.0.0.1 ::1 [::1] host.docker.internal].freeze
16
+
17
+ module_function
18
+
19
+ def control?(value, allow_tab)
20
+ value.each_char.any? { |c| c == "\u007F" || (c.ord < 32 && !(allow_tab && c == "\t")) }
21
+ end
22
+
23
+ def idempotency_key(key)
24
+ return if key.is_a?(String) && key.length.between?(1, 255) && key.each_char.all? { |c| c.ord.between?(32, 126) }
25
+
26
+ raise InvalidRequestError, "Idempotency-Key must be 1 to 255 printable ASCII characters"
27
+ end
28
+
29
+ def request_id(value)
30
+ raise InvalidRequestError, "X-Request-ID must be 8 to 64 characters of A-Z a-z 0-9 . _ -" unless value.is_a?(String) && REQUEST_ID.match?(value)
31
+ end
32
+
33
+ # Identifiers go into URL paths; anything outside the id alphabet is rejected.
34
+ def id(value, name = "id")
35
+ raise InvalidRequestError.new("#{name} must be 1 to 64 characters of A-Z a-z 0-9 _ -", name) unless value.is_a?(String) && ID.match?(value)
36
+
37
+ value
38
+ end
39
+
40
+ def headers(headers)
41
+ raise InvalidRequestError, "headers must be a Hash" unless headers.is_a?(Hash)
42
+
43
+ headers.each do |name, value|
44
+ name = name.to_s
45
+ raise InvalidRequestError, "Header names may only contain letters, digits and dashes" unless HEADER_NAME.match?(name)
46
+ raise InvalidRequestError, "The #{name} header cannot be overridden" if PROTECTED_HEADERS.include?(name.downcase)
47
+ raise InvalidRequestError, "Header #{name} has an invalid value" unless value.is_a?(String) && value.length <= 4096 && !control?(value, true)
48
+ end
49
+ end
50
+
51
+ def required(value, field)
52
+ raise InvalidRequestError.new("#{field} is required", field) if value.nil? || (value.is_a?(String) && value.empty?)
53
+ end
54
+
55
+ def phone(value, field)
56
+ return if value.is_a?(String) && PHONE.match?(value)
57
+
58
+ raise InvalidRequestError.new("#{field} must be an E.164 Tanzanian number (+255 followed by nine digits)",
59
+ field)
60
+ end
61
+
62
+ def amount(value, min, max, field)
63
+ return if value.is_a?(Integer) && value.between?(min, max)
64
+
65
+ raise InvalidRequestError.new("#{field} must be an integer between #{min} and #{max}", field)
66
+ end
67
+
68
+ def optional_amount(value, min, max, field)
69
+ amount(value, min, max, field) unless value.nil?
70
+ end
71
+
72
+ def enum(value, field, allowed)
73
+ return if value.nil? || allowed.include?(value)
74
+
75
+ raise InvalidRequestError.new("#{field} must be one of #{allowed.join(", ")}", field)
76
+ end
77
+
78
+ def string(value, field, min, max)
79
+ return if value.nil?
80
+ return if value.is_a?(String) && value.length.between?(min, max) && !control?(value, true) && value.valid_encoding?
81
+
82
+ raise InvalidRequestError.new("#{field} must be a string of #{min} to #{max} characters", field)
83
+ end
84
+
85
+ def metadata(value, field = "metadata")
86
+ return if value.nil?
87
+ raise InvalidRequestError.new("#{field} must be a Hash", field) unless value.is_a?(Hash)
88
+ return unless JSON.generate(value).bytesize > MAX_METADATA_BYTES
89
+
90
+ raise InvalidRequestError.new("#{field} must encode to at most #{MAX_METADATA_BYTES} bytes of JSON",
91
+ field)
92
+ end
93
+
94
+ def loopback?(host)
95
+ !host.nil? && LOOPBACK.include?(host.downcase)
96
+ end
97
+
98
+ def url(value, field, max_length)
99
+ return if value.nil?
100
+ if !value.is_a?(String) || value.length > max_length || value.match?(/\s/) || control?(value, false)
101
+ raise InvalidRequestError.new("#{field} must be a URL of at most #{max_length} characters", field)
102
+ end
103
+
104
+ uri = begin
105
+ URI.parse(value)
106
+ rescue URI::InvalidURIError
107
+ raise InvalidRequestError.new("#{field} must be an absolute URL", field)
108
+ end
109
+ raise InvalidRequestError.new("#{field} must be an absolute URL", field) unless uri.is_a?(URI::HTTP) && uri.host
110
+ raise InvalidRequestError.new("#{field} must use https", field) unless uri.scheme == "https" || (uri.scheme == "http" && loopback?(uri.host))
111
+ end
112
+
113
+ def limit(limit)
114
+ return if limit.nil? || (limit.is_a?(Integer) && limit.between?(1, 100))
115
+
116
+ raise InvalidRequestError.new("limit must be an integer between 1 and 100", "limit")
117
+ end
118
+
119
+ def cursor(cursor)
120
+ return if cursor.nil?
121
+ return if cursor.is_a?(String) && cursor.length.between?(1, 200) && cursor.each_char.all? { |c| c.ord.between?(33, 126) }
122
+
123
+ raise InvalidRequestError.new("cursor must be an opaque value returned by a previous list call", "cursor")
124
+ end
125
+
126
+ def query_value(key, value)
127
+ raise InvalidRequestError, "Query parameter names must be alphanumeric" unless QUERY_KEY.match?(key)
128
+ raise InvalidRequestError.new("#{key} has an invalid value", key) if value.length > 500 || control?(value, false)
129
+ end
130
+
131
+ def body_size(body)
132
+ raise InvalidRequestError, "Request body exceeds the #{MAX_BODY_BYTES} byte limit" if body.bytesize > MAX_BODY_BYTES
133
+ end
134
+
135
+ def date_string(value, field)
136
+ return if value.nil? || (value.is_a?(String) && DATE_TIME.match?(value))
137
+
138
+ raise InvalidRequestError.new("#{field} must be an RFC 3339 timestamp or a YYYY-MM-DD date", field)
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaySafe
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaySafe
4
+ # Webhook signature verification: HMAC-SHA256 over "timestamp.rawBody", constant-time comparison.
5
+ module Webhooks
6
+ SIGNATURE_HEADER = "PaySafe-Signature"
7
+ DEFAULT_TOLERANCE_SECONDS = 300
8
+ MAX_HEADER_BYTES = 4096
9
+ MAX_PAYLOAD_BYTES = 1024 * 1024
10
+
11
+ module_function
12
+
13
+ # Builds a PaySafe-Signature value. Intended for tests.
14
+ def sign(secret, payload, timestamp)
15
+ "t=#{timestamp},v1=#{hmac_hex(secret, timestamp, payload)}"
16
+ end
17
+
18
+ # True when the raw payload was signed by the secret (or one of the secrets) within the tolerance window. Never raises.
19
+ def verify_signature(secret, payload, header, tolerance: DEFAULT_TOLERANCE_SECONDS, now: nil)
20
+ check(Array(secret), payload, header, tolerance, now)
21
+ true
22
+ rescue SignatureVerificationError
23
+ false
24
+ end
25
+
26
+ # Verifies the delivery and returns the typed Event. Raises SignatureVerificationError with a reason.
27
+ def construct_event(secret, payload, header, tolerance: DEFAULT_TOLERANCE_SECONDS, now: nil)
28
+ check(Array(secret), payload, header, tolerance, now)
29
+ parsed = Util.parse_json(payload.to_s)
30
+ unless parsed.is_a?(Hash) && parsed["id"].is_a?(String) && parsed["type"].is_a?(String)
31
+ raise SignatureVerificationError.new(SignatureVerificationError::INVALID_PAYLOAD, "Webhook payload is not an event object")
32
+ end
33
+
34
+ Event.from(parsed)
35
+ end
36
+
37
+ def check(secrets, payload, header, tolerance, now)
38
+ payload = payload.to_s
39
+ if header.nil? || header.strip.empty?
40
+ raise SignatureVerificationError.new(SignatureVerificationError::MISSING_HEADER,
41
+ "PaySafe-Signature header is missing")
42
+ end
43
+ if header.bytesize > MAX_HEADER_BYTES || payload.bytesize > MAX_PAYLOAD_BYTES
44
+ raise SignatureVerificationError.new(SignatureVerificationError::MALFORMED_HEADER, "Webhook header or payload is too large")
45
+ end
46
+
47
+ timestamp = nil
48
+ signatures = []
49
+ header.split(",").each do |part|
50
+ key, value = part.split("=", 2)
51
+ next if value.nil?
52
+
53
+ key = key.strip
54
+ value = value.strip
55
+ timestamp = value if key == "t"
56
+ signatures << value.downcase if key == "v1"
57
+ end
58
+ if timestamp.nil? || !timestamp.match?(/\A\d+\z/) || signatures.empty?
59
+ raise SignatureVerificationError.new(SignatureVerificationError::MALFORMED_HEADER, "PaySafe-Signature header is malformed")
60
+ end
61
+
62
+ t = timestamp.to_i
63
+ current = now || Time.now.to_i
64
+ if (current - t).abs > tolerance
65
+ raise SignatureVerificationError.new(SignatureVerificationError::TIMESTAMP_OUTSIDE_TOLERANCE,
66
+ "Webhook timestamp is outside the tolerance window")
67
+ end
68
+
69
+ secrets.each do |s|
70
+ expected = hmac_hex(s, t, payload)
71
+ signatures.each do |sig|
72
+ return true if sig.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(expected, sig)
73
+ end
74
+ end
75
+ raise SignatureVerificationError.new(SignatureVerificationError::SIGNATURE_MISMATCH, "Webhook signature does not match")
76
+ end
77
+ private_class_method :check
78
+
79
+ def hmac_hex(secret, timestamp, payload)
80
+ OpenSSL::HMAC.hexdigest("SHA256", secret.to_s, "#{timestamp}.#{payload}")
81
+ end
82
+ private_class_method :hmac_hex
83
+ end
84
+ end
data/lib/paysafe.rb ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "securerandom"
7
+ require "time"
8
+ require "uri"
9
+
10
+ require_relative "paysafe/version"
11
+ require_relative "paysafe/errors"
12
+ require_relative "paysafe/util"
13
+ require_relative "paysafe/validate"
14
+ require_relative "paysafe/api_response"
15
+ require_relative "paysafe/request_options"
16
+ require_relative "paysafe/models"
17
+ require_relative "paysafe/page"
18
+ require_relative "paysafe/webhooks"
19
+ require_relative "paysafe/client"
20
+ require_relative "paysafe/resources/base"
21
+ require_relative "paysafe/resources/payments"
22
+ require_relative "paysafe/resources/payment_links"
23
+ require_relative "paysafe/resources/control_numbers"
24
+ require_relative "paysafe/resources/refunds"
25
+ require_relative "paysafe/resources/topups"
26
+ require_relative "paysafe/resources/balance"
27
+ require_relative "paysafe/resources/customers"
28
+ require_relative "paysafe/resources/transfers"
29
+ require_relative "paysafe/resources/webhook_endpoints"
30
+ require_relative "paysafe/resources/events"
31
+
32
+ # Official PaySafe SDK. Start with PaySafe::Client.new(api_key: "paysafe_test_...").
33
+ module PaySafe
34
+ def self.new(**options)
35
+ Client.new(**options)
36
+ end
37
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: paysafe-tz
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - PaySafe
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-05 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Mobile-money payments in Tanzania, refunds, control numbers, payment
14
+ links, transfers and signed webhooks.
15
+ email:
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - CHANGELOG.md
21
+ - LICENSE
22
+ - README.md
23
+ - lib/paysafe.rb
24
+ - lib/paysafe/api_response.rb
25
+ - lib/paysafe/client.rb
26
+ - lib/paysafe/errors.rb
27
+ - lib/paysafe/models.rb
28
+ - lib/paysafe/page.rb
29
+ - lib/paysafe/request_options.rb
30
+ - lib/paysafe/resources/balance.rb
31
+ - lib/paysafe/resources/base.rb
32
+ - lib/paysafe/resources/control_numbers.rb
33
+ - lib/paysafe/resources/customers.rb
34
+ - lib/paysafe/resources/events.rb
35
+ - lib/paysafe/resources/payment_links.rb
36
+ - lib/paysafe/resources/payments.rb
37
+ - lib/paysafe/resources/refunds.rb
38
+ - lib/paysafe/resources/topups.rb
39
+ - lib/paysafe/resources/transfers.rb
40
+ - lib/paysafe/resources/webhook_endpoints.rb
41
+ - lib/paysafe/util.rb
42
+ - lib/paysafe/validate.rb
43
+ - lib/paysafe/version.rb
44
+ - lib/paysafe/webhooks.rb
45
+ homepage: https://github.com/AmDev255/paysafe-ruby
46
+ licenses:
47
+ - MIT
48
+ metadata:
49
+ homepage_uri: https://github.com/AmDev255/paysafe-ruby
50
+ source_code_uri: https://github.com/AmDev255/paysafe-ruby
51
+ changelog_uri: https://github.com/AmDev255/paysafe-ruby/blob/main/CHANGELOG.md
52
+ documentation_uri: https://paysafe.co.tz/docs
53
+ bug_tracker_uri: https://github.com/AmDev255/paysafe-ruby/issues
54
+ rubygems_mfa_required: 'true'
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '3.1'
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.3.27
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: Official PaySafe Ruby SDK
74
+ test_files: []