paygate_pk 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b06b7bfef5146c0fffbe72c7f1c173b08abb1873ec492a25b7b6e2366ebfbd45
4
+ data.tar.gz: d44d8b3169b624f1a0aa2b2e06c4754fc90136b4d055aad1b90121cc6d2faee1
5
+ SHA512:
6
+ metadata.gz: f7f8bb5aea01aac11d7579b384e9c7d4e63a03d367e77bc05d9ff48aed3959255f4f3aa54119a39cbe04be82d86ea80e2d3e5c8dfb842e697d31f1bd4fba91c0
7
+ data.tar.gz: 23131a34e78b2fb40bfe1ae582276766cccd997b3bcdbbef95b4d5021340c7dc28e59d6ce7f48b8049add3950082d13590b658f0b80ff5d47aca4151f1706369
data/.rubocop.yml ADDED
@@ -0,0 +1,24 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
14
+
15
+ Metrics/MethodLength:
16
+ Max: 20 # Example: Set maximum method length to 15 lines
17
+ CountAsOne:
18
+ - array
19
+ - hash
20
+ - heredoc
21
+ - method_call
22
+
23
+ Metrics/AbcSize:
24
+ Max: 20
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2025-10-01
4
+
5
+ - Initial release.
6
+ - PayFast: GetAccessToken + Checkout (HTML redirect parsing).
7
+ - Config, errors, HTTP client, tests, CI scaffolding.
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at talhajunaid65@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in paygate_pk.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,92 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ paygate_pk (0.1.0)
5
+ faraday (>= 2.7)
6
+ faraday-retry (>= 2.0)
7
+ json
8
+ nokogiri (>= 1.16, < 2.0)
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ addressable (2.8.7)
14
+ public_suffix (>= 2.0.2, < 7.0)
15
+ ast (2.4.3)
16
+ bigdecimal (3.2.3)
17
+ crack (1.0.0)
18
+ bigdecimal
19
+ rexml
20
+ docile (1.4.1)
21
+ faraday (2.13.1)
22
+ faraday-net_http (>= 2.0, < 3.5)
23
+ json
24
+ logger
25
+ faraday-net_http (3.4.1)
26
+ net-http (>= 0.5.0)
27
+ faraday-retry (2.3.2)
28
+ faraday (~> 2.0)
29
+ hashdiff (1.2.1)
30
+ json (2.12.2)
31
+ language_server-protocol (3.17.0.5)
32
+ lint_roller (1.1.0)
33
+ logger (1.7.0)
34
+ minitest (5.25.5)
35
+ net-http (0.6.0)
36
+ uri
37
+ nokogiri (1.18.9-x86_64-darwin)
38
+ racc (~> 1.4)
39
+ parallel (1.27.0)
40
+ parser (3.3.8.0)
41
+ ast (~> 2.4.1)
42
+ racc
43
+ prism (1.5.1)
44
+ public_suffix (6.0.2)
45
+ racc (1.8.1)
46
+ rainbow (3.1.1)
47
+ rake (13.3.0)
48
+ regexp_parser (2.10.0)
49
+ rexml (3.4.4)
50
+ rubocop (1.78.0)
51
+ json (~> 2.3)
52
+ language_server-protocol (~> 3.17.0.2)
53
+ lint_roller (~> 1.1.0)
54
+ parallel (~> 1.10)
55
+ parser (>= 3.3.0.2)
56
+ rainbow (>= 2.2.2, < 4.0)
57
+ regexp_parser (>= 2.9.3, < 3.0)
58
+ rubocop-ast (>= 1.45.1, < 2.0)
59
+ ruby-progressbar (~> 1.7)
60
+ unicode-display_width (>= 2.4.0, < 4.0)
61
+ rubocop-ast (1.46.0)
62
+ parser (>= 3.3.7.2)
63
+ prism (~> 1.4)
64
+ ruby-progressbar (1.13.0)
65
+ simplecov (0.22.0)
66
+ docile (~> 1.1)
67
+ simplecov-html (~> 0.11)
68
+ simplecov_json_formatter (~> 0.1)
69
+ simplecov-html (0.13.2)
70
+ simplecov_json_formatter (0.1.4)
71
+ unicode-display_width (3.1.4)
72
+ unicode-emoji (~> 4.0, >= 4.0.4)
73
+ unicode-emoji (4.0.4)
74
+ uri (1.0.3)
75
+ webmock (3.25.1)
76
+ addressable (>= 2.8.0)
77
+ crack (>= 0.3.2)
78
+ hashdiff (>= 0.4.0, < 2.0.0)
79
+
80
+ PLATFORMS
81
+ x86_64-darwin-24
82
+
83
+ DEPENDENCIES
84
+ minitest (~> 5.0)
85
+ paygate_pk!
86
+ rake (~> 13.0)
87
+ rubocop (~> 1.21)
88
+ simplecov (>= 0.22)
89
+ webmock
90
+
91
+ BUNDLED WITH
92
+ 2.4.8
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Talha Junaid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # PaygatePk
2
+
3
+ Unified Ruby wrapper for PayFast (and soon Easypaisa) payments in Pakistan.
4
+
5
+ This gem provides a clean, provider-agnostic interface to obtain access tokens and create hosted checkouts with PayFast. It wraps HTTP details, validates required fields, and exposes simple, Ruby-friendly objects. Rails-friendly configuration is included; IPN verification and recurring/tokenized flows are on the roadmap.
6
+
7
+ ## Requirements
8
+
9
+ - Ruby ≥ 3.1
10
+ - Faraday (runtime, included by gemspec)
11
+ - Nokogiri (runtime, for HTML redirect parsing, included)
12
+ - (Dev) Byebug, SimpleCov, RuboCop — optional
13
+
14
+ ## Installation
15
+
16
+ Install the gem and add to the application's Gemfile by executing:
17
+
18
+ $ bundle add "paygate_pk", "~> 0.1.0"
19
+
20
+ If bundler is not being used to manage dependencies, install the gem by executing:
21
+
22
+ $ gem install "paygate_pk", "~> 0.1.0"
23
+
24
+ ## Usage
25
+
26
+ # Initializer
27
+
28
+ ```ruby
29
+ # config/initializers/paygate_pk.rb
30
+
31
+ PaygatePk.configure do |c|
32
+ c.default_currency = "PKR"
33
+ c.user_agent = "paygate_pk/#{PaygatePk::VERSION}"
34
+
35
+ # PayFast base host only; endpoints include /Ecommerce/api internally
36
+
37
+ c.payfast.base_url = "https://ipguat.apps.net.pk"
38
+ c.payfast.merchant_id = ENV.fetch("PAYFAST_MERCHANT_ID")
39
+ c.payfast.secured_key = ENV.fetch("PAYFAST_SECURED_KEY")
40
+ c.payfast.checkout_mode = :immediate # or :delayed
41
+
42
+ # Optional: tune timeouts & retries
43
+
44
+ c.timeouts = { open_timeout: 5, read_timeout: 10 }
45
+ c.retry = { max: 2, interval: 0.2, backoff_factor: 2.0, retry_statuses: [429, 500, 502, 503, 504] }
46
+ end
47
+ ```
48
+
49
+ ## QuickStart
50
+
51
+ # 1) Get Access Token (PayFast)
52
+
53
+ ```ruby
54
+ auth = PaygatePk::Providers::PayFast::Auth.new(config: PaygatePk.config.payfast)
55
+
56
+ token_obj = auth.get_access_token(
57
+ basket_id: "B-1001",
58
+ amount: 1500
59
+
60
+ # currency: "PKR", # optional; defaults to PaygatePk.config.default_currency
61
+
62
+ # endpoint: "/Ecommerce/api/Transaction/GetAccessToken" # optional override
63
+
64
+ )
65
+
66
+ puts token_obj.token # => "ACCESS_TOKEN_STRING"
67
+
68
+ ```
69
+
70
+ # 2) Create Hosted Checkout (PayFast)
71
+
72
+ ```ruby
73
+ checkout = PaygatePk::Providers::PayFast::Checkout.new(config: PaygatePk.config.payfast)
74
+
75
+ hc = checkout.create!(opts: {
76
+ token: token_obj.token,
77
+ basket_id: "B-1001",
78
+ amount: 1500, # paisa (Rs 15.00)
79
+ customer: { mobile: "03001234567", email: "buyer@example.com" },
80
+ success_url: "https://your-app.example.com/payments/success",
81
+ failure_url: "https://your-app.example.com/payments/failure",
82
+ description: "Order #1001"
83
+ # checkout_mode: :immediate, # optional; default from config
84
+ # endpoint: "/Ecommerce/api/Transaction/PostTransaction" # optional override
85
+ })
86
+
87
+ hc.url # => "https://gateway.payfast/redirect/ABC123"
88
+ # Redirect the buyer to hc.url
89
+ ```
90
+
91
+ # Error handling
92
+
93
+ All errors inherit from PaygatePk::Error:
94
+
95
+ - PaygatePk::ConfigurationError — missing/invalid configuration (e.g., merchant_id, secured_key, or base_url).
96
+ - PaygatePk::ValidationError — missing required method arguments or required form fields.
97
+ - PaygatePk::HTTPError — network/HTTP failure (wraps response status & body).
98
+ - PaygatePk::AuthError — auth call succeeded at HTTP level but token missing/invalid in body.
99
+ - PaygatePk::SignatureError — reserved for webhook/IPN verification (upcoming).
100
+ - PaygatePk::ProviderError — reserved for provider business-rule failures.
101
+
102
+ ## Development
103
+
104
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
105
+
106
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
107
+
108
+ ## Contributing
109
+
110
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/paygate_pk. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/paygate_pk/blob/master/CODE_OF_CONDUCT.md).
111
+
112
+ ## License
113
+
114
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
115
+
116
+ ## Code of Conduct
117
+
118
+ Everyone interacting in the PaygatePk project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/paygate_pk/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaygatePk
4
+ # Global configuration for PaygatePk
5
+ class Config
6
+ attr_accessor :logger, :default_currency, :timeouts, :retry, :user_agent
7
+ attr_reader :pay_fast
8
+
9
+ def initialize
10
+ @logger = nil
11
+ @default_currency = "PKR"
12
+ @timeouts = { open_timeout: 5, read_timeout: 10 }
13
+ @retry = { max: 2, interval: 0.2, backoff_factor: 2.0, retry_statuses: [429, 500, 502, 503, 504] }
14
+ @user_agent = "paygate_pk/#{PaygatePk::VERSION}"
15
+
16
+ @pay_fast = ProviderConfig.new
17
+ @frozen = false
18
+ end
19
+
20
+ def freeze!
21
+ @frozen = true
22
+ self
23
+ end
24
+
25
+ def frozen?
26
+ @frozen
27
+ end
28
+
29
+ # Provider-specific configuration
30
+ class ProviderConfig
31
+ attr_accessor :base_url, :merchant_id, :secured_key, :checkout_mode, :username, :password, :store_id
32
+
33
+ def initialize
34
+ @base_url = nil
35
+ @merchant_id = nil
36
+ @secured_key = nil
37
+ @checkout_mode = :immediate
38
+ @username = nil
39
+ @password = nil
40
+ @store_id = nil
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,8 @@
1
+ # lib/paygate_pk/contracts/access_token.rb
2
+ # frozen_string_literal: true
3
+
4
+ module PaygatePk
5
+ module Contracts
6
+ AccessToken = Struct.new(:token, :raw, keyword_init: true)
7
+ end
8
+ end
@@ -0,0 +1,8 @@
1
+ # lib/paygate_pk/contracts/access_token.rb
2
+ # frozen_string_literal: true
3
+
4
+ module PaygatePk
5
+ module Contracts
6
+ HostedCheckout = Struct.new(:provider, :basket_id, :amount, :url, :raw, :form, keyword_init: true)
7
+ end
8
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaygatePk
4
+ class Error < StandardError; end
5
+ class ConfigurationError < Error; end
6
+
7
+ # Raised when a request validation fails.
8
+ class ValidationError < Error
9
+ attr_reader :details
10
+
11
+ def initialize(msg = "validation failed", details: {})
12
+ @details = details
13
+ super(msg)
14
+ end
15
+ end
16
+
17
+ # Raised for HTTP errors, e.g. non-2xx responses.
18
+ class HTTPError < Error
19
+ attr_reader :status, :body
20
+
21
+ def initialize(message = "http error", status: nil, body: nil)
22
+ @status = status
23
+ @body = body
24
+ super(message)
25
+ end
26
+ end
27
+
28
+ class AuthError < Error; end
29
+ class SignatureError < Error; end
30
+ class ProviderError < Error; end
31
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+ require "faraday/retry"
5
+ require "json"
6
+ require "securerandom"
7
+
8
+ module PaygatePk
9
+ module HTTP
10
+ # Simple HTTP client using Faraday
11
+ class Client
12
+ def initialize(base_url:, headers: {}, timeouts: {}, retry_conf: {}, logger: nil)
13
+ @conn = Faraday.new(url: base_url) do |f|
14
+ f.request :retry,
15
+ max: retry_conf[:max] || 2,
16
+ interval: retry_conf[:interval] || 0.2,
17
+ backoff_factor: retry_conf[:backoff_factor] || 2.0,
18
+ retry_statuses: retry_conf[:retry_statuses] || [429, 500, 502, 503, 504]
19
+
20
+ f.request :url_encoded
21
+ f.response :raise_error
22
+ f.adapter Faraday.default_adapter
23
+ end
24
+
25
+ @headers = headers
26
+ @timeouts = timeouts
27
+ @logger = logger
28
+ end
29
+
30
+ def post(path, json: nil, form: nil, headers: {})
31
+ request(:post, path, json: json, form: form, headers: headers)
32
+ end
33
+
34
+ def get(path, params: {}, headers: {})
35
+ request(:get, path, params: params, headers: headers)
36
+ end
37
+
38
+ private
39
+
40
+ # rubocop:disable Metrics/ParameterLists
41
+ def request(method, path, json: nil, form: nil, params: nil, headers: {})
42
+ resp = execute_request(method, path, params, headers) do |req|
43
+ configure_timeouts(req)
44
+ set_request_body(req, json, form)
45
+ end
46
+
47
+ log_response(resp)
48
+ parse_body(resp)
49
+ rescue Faraday::ClientError => e
50
+ handle_client_error(e)
51
+ end
52
+ # rubocop:enable Metrics/ParameterLists
53
+
54
+ def execute_request(method, path, params, headers)
55
+ @conn.run_request(method, path, nil, merged_headers(headers)) do |req|
56
+ req.params.update(params) if params
57
+ yield req if block_given?
58
+ end
59
+ end
60
+
61
+ def merged_headers(headers)
62
+ base_headers.merge(headers)
63
+ end
64
+
65
+ def configure_timeouts(req)
66
+ req.options.timeout = @timeouts[:read_timeout] if @timeouts[:read_timeout]
67
+ req.options.open_timeout = @timeouts[:open_timeout] if @timeouts[:open_timeout]
68
+ end
69
+
70
+ def set_request_body(req, json, form)
71
+ if json
72
+ set_json_body(req, json)
73
+ elsif form
74
+ set_form_body(req, form)
75
+ end
76
+ end
77
+
78
+ def set_json_body(req, json)
79
+ req.headers["Content-Type"] = "application/json"
80
+ req.body = JSON.generate(json)
81
+ end
82
+
83
+ def set_form_body(req, form)
84
+ req.headers["Content-Type"] = "application/x-www-form-urlencoded"
85
+ req.body = URI.encode_www_form(form)
86
+ end
87
+
88
+ def handle_client_error(error)
89
+ body = error.response&.dig(:body)
90
+ status = error.response&.dig(:status)
91
+
92
+ raise PaygatePk::HTTPError.new(
93
+ error.message,
94
+ status: status,
95
+ body: body
96
+ )
97
+ end
98
+
99
+ def base_headers
100
+ {
101
+ "User-Agent" => PaygatePk.config.user_agent || "paygate_pk",
102
+ "X-Request-Id" => SecureRandom.uuid
103
+ }.merge(@headers)
104
+ end
105
+
106
+ def parse_body(resp)
107
+ b = resp.body
108
+ if b.is_a?(String) && !b.empty?
109
+ begin
110
+ JSON.parse(b)
111
+ rescue StandardError
112
+ b
113
+ end
114
+ else
115
+ b
116
+ end
117
+ end
118
+
119
+ def log_response(resp)
120
+ return unless @logger
121
+
122
+ @logger.info("paygate_pk http #{resp.env.method.upcase} #{resp.env.url} -> #{resp.status}")
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module PaygatePk
6
+ module Providers
7
+ module PayFast
8
+ # Auth client for PayFast API
9
+ class Auth < Client
10
+ ENDPOINT = "/Ecommerce/api/Transaction/GetAccessToken"
11
+
12
+ # Returns Contracts::AccessToken
13
+ # Required by PayFast: MERCHANT_ID, SECURED_KEY, BASKET_ID, TXNAMT, CURRENCY_CODE
14
+ #
15
+ def get_access_token(basket_id:, amount:, currency: PaygatePk.config.default_currency, endpoint: ENDPOINT)
16
+ ensure_config!
17
+ ensure_args!(basket_id: basket_id, amount: amount, currency: currency)
18
+
19
+ # Guide endpoint: .../Ecommerce/api/Transaction/GetAccessToken
20
+ resp = http.post(endpoint,
21
+ form: payload(basket_id, amount, currency))
22
+ token = resp.is_a?(Hash) ? (resp["ACCESS_TOKEN"] || resp["access_token"]) : nil
23
+ raise AuthError, "missing ACCESS_TOKEN in response" unless token
24
+
25
+ Contracts::AccessToken.new(token: token, raw: resp)
26
+ end
27
+
28
+ private
29
+
30
+ def ensure_config!
31
+ missing = []
32
+ missing << :merchant_id if @config.merchant_id.to_s.strip.empty?
33
+ missing << :secured_key if @config.secured_key.to_s.strip.empty?
34
+ raise ConfigurationError, "PayFast config missing: #{missing.join(", ")}" unless missing.empty?
35
+ end
36
+
37
+ def ensure_args!(basket_id:, amount:, currency:)
38
+ missing = []
39
+ missing << :basket_id if basket_id.to_s.strip.empty?
40
+ missing << :amount if amount.nil?
41
+ missing << :currency if currency.to_s.strip.empty?
42
+ raise ValidationError, "missing required args: #{missing.join(", ")}" unless missing.empty?
43
+ end
44
+
45
+ def payload(basket_id, amount, currency)
46
+ {
47
+ "MERCHANT_ID" => @config.merchant_id,
48
+ "SECURED_KEY" => @config.secured_key,
49
+ "BASKET_ID" => basket_id,
50
+ "TXNAMT" => amount.to_s,
51
+ "CURRENCY_CODE" => currency
52
+ }
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,153 @@
1
+ # lib/paygate_pk/providers/pay_fast/checkout.rb
2
+ # frozen_string_literal: true
3
+
4
+ require "securerandom"
5
+ require "date"
6
+ require "nokogiri"
7
+
8
+ module PaygatePk
9
+ module Providers
10
+ module PayFast
11
+ # Builds and submits a hosted checkout request to PayFast.
12
+ #
13
+ # Usage:
14
+ # client = PaygatePk::Providers::PayFast::Checkout.new(config: PaygatePk.config.payfast)
15
+ # checkout = client.create!(
16
+ # token: token.token,
17
+ # basket_id: "B-1001",
18
+ # amount: 1500,
19
+ # customer: { mobile: "03xxxxxxxxx", email: "buyer@example.com" },
20
+ # success_url: "...",
21
+ # failure_url: "...",
22
+ # description: "Order #1001",
23
+ # checkout_mode: :immediate
24
+ # )
25
+ class Checkout < Client
26
+ ENDPOINT = "/Ecommerce/api/Transaction/PostTransaction"
27
+
28
+ REQUIRED_ROOT_KEYS = %i[token basket_id amount success_url failure_url description].freeze
29
+ REQUIRED_CUSTOMER_KEYS = %i[mobile email].freeze
30
+
31
+ # Creates a hosted checkout via PayFast.
32
+ #
33
+ # @param token [String] ACCESS_TOKEN from GetAccessToken
34
+ # @param basket_id [String]
35
+ # @param amount [Integer, Float] rupees
36
+ # @param customer [Hash] keys: :mobile, :email
37
+ # @param success_url [String]
38
+ # @param failure_url [String]
39
+ # @param description [String] TXNDESC
40
+ # @param order_date [Date] defaults: Date.today
41
+ # @param checkout_mode [Symbol] :immediate or :delayed (defaults from config)
42
+ # @param endpoint [Symbol] default to ENDPOINT constant
43
+
44
+ # @return [PaygatePk::Contracts::HostedCheckout]
45
+ def create!(opts: {})
46
+ validate_config!
47
+ validate_args!(opts)
48
+
49
+ form = build_form(opts)
50
+
51
+ response = http.post(opts[:endpoint] || ENDPOINT, form: form)
52
+
53
+ PaygatePk::Contracts::HostedCheckout.new(
54
+ provider: :payfast,
55
+ basket_id: opts[:basket_id],
56
+ amount: opts[:amount],
57
+ url: PaygatePk::Util::Html.first_anchor_href(response),
58
+ form: PaygatePk::Util::Html.extract_form(response),
59
+ raw: response
60
+ )
61
+ end
62
+
63
+ private
64
+
65
+ # -- Validation ---------------------------------------------------------
66
+
67
+ def validate_config!
68
+ missing = []
69
+ missing << :merchant_id if blank?(config.merchant_id)
70
+ missing << :secured_key if blank?(config.secured_key)
71
+ raise PaygatePk::ConfigurationError, "PayFast config missing: #{missing.join(", ")}" unless missing.empty?
72
+ end
73
+
74
+ def validate_args!(opts)
75
+ missing = []
76
+ REQUIRED_ROOT_KEYS.each do |k|
77
+ v = opts[k]
78
+ missing << k if k == :amount ? opts[:amount].nil? : blank?(v)
79
+ end
80
+ REQUIRED_CUSTOMER_KEYS.each { |k| missing << :"customer.#{k}" if blank?(opts[:customer][k]) }
81
+ raise PaygatePk::ValidationError, "missing required args: #{missing.join(", ")}" unless missing.empty?
82
+ end
83
+
84
+ # -- Builders -----------------------------------------------------------
85
+
86
+ def merchant_params
87
+ {
88
+ "MERCHANT_ID" => config.merchant_id,
89
+ "MERCHANT_NAME" => merchant_name_default
90
+ }
91
+ end
92
+
93
+ def order_params(opts)
94
+ {
95
+ "BASKET_ID" => opts[:basket_id],
96
+ "TXNDESC" => opts[:description],
97
+ "TXNAMT" => opts[:amount].to_s,
98
+ "CURRENCY_CODE" => PaygatePk.config.default_currency,
99
+ "ORDER_DATE" => (opts[:order_date] || Date.today).to_s,
100
+ "SUCCESS_URL" => opts[:success_url],
101
+ "FAILURE_URL" => opts[:failure_url],
102
+ "CHECKOUT_URL" => normalize_checkout_mode(opts[:checkout_mode] || config.checkout_mode)
103
+ }
104
+ end
105
+
106
+ def customer_params(opts)
107
+ {
108
+ "CUSTOMER_MOBILE_NO" => opts[:customer][:mobile],
109
+ "CUSTOMER_EMAIL_ADDRESS" => opts[:customer][:email]
110
+ }
111
+ end
112
+
113
+ def generic_params(opts)
114
+ {
115
+ "TOKEN" => opts[:token],
116
+ "PROCCODE" => "00",
117
+ "SIGNATURE" => SecureRandom.hex(16),
118
+ "VERSION" => PaygatePk::VERSION
119
+ }
120
+ end
121
+
122
+ def build_form(opts)
123
+ merchant_params
124
+ .merge(order_params(opts))
125
+ .merge(customer_params(opts))
126
+ .merge(generic_params(opts))
127
+ end
128
+
129
+ # -- Helpers ------------------------------------------------------------
130
+
131
+ def normalize_checkout_mode(mode)
132
+ case mode&.to_sym
133
+ when :delayed then "DELAYED"
134
+ when :immediate, nil then "IMMEDIATE"
135
+ else
136
+ # Be lenient but explicit: unknown symbols fall back to IMMEDIATE
137
+ "IMMEDIATE"
138
+ end
139
+ end
140
+
141
+ def merchant_name_default
142
+ # Kept blank as many integrations treat it as optional; override here
143
+ # later if you decide to expose it via config.
144
+ ""
145
+ end
146
+
147
+ def blank?(value)
148
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
149
+ end
150
+ end
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../http/client"
4
+ require_relative "../../version"
5
+
6
+ module PaygatePk
7
+ module Providers
8
+ module PayFast
9
+ # HTTP client for PayFast API
10
+ class Client
11
+ def initialize(config: PaygatePk.config.pay_fast)
12
+ @config = config
13
+ end
14
+
15
+ private
16
+
17
+ attr_reader :config
18
+
19
+ def http
20
+ raise ConfigurationError, "PayFast base_url not set" unless config.base_url
21
+
22
+ PaygatePk::HTTP::Client.new(
23
+ base_url: config.base_url,
24
+ headers: { "Accept" => "application/json" },
25
+ timeouts: PaygatePk.config.timeouts,
26
+ retry_conf: PaygatePk.config.retry,
27
+ logger: PaygatePk.config.logger
28
+ )
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nokogiri"
4
+
5
+ module PaygatePk
6
+ module Util
7
+ # HTML parsing utilities
8
+ module Html
9
+ module_function
10
+
11
+ # Extract a specific <form> (default: first) into a hash of action/method/inputs
12
+ def extract_form(html, index: 0)
13
+ doc = parse(html)
14
+ form = doc.css("form")[index]
15
+ return nil unless form
16
+
17
+ {
18
+ action: form["action"],
19
+ method: (form["method"] || "GET").upcase,
20
+ inputs: form.css("input[name]").to_h { |i| [i["name"], i["value"]] }
21
+ }
22
+ end
23
+
24
+ # NEW: Return the first anchor href (or nil) – handy for redirect pages
25
+ # Optionally pass a CSS selector (e.g., "a.pay-button") if you need a specific link.
26
+ def first_anchor_href(html, selector: "a")
27
+ doc = parse(html)
28
+ a = doc.at(selector)
29
+ a ? a["href"] : nil
30
+ end
31
+
32
+ # --- internals ----------------------------------------------------------
33
+
34
+ def parse(html)
35
+ Nokogiri::HTML5(html)
36
+ rescue NoMethodError
37
+ # Fallback for environments without HTML5 parser
38
+ Nokogiri::HTML(html)
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaygatePk
4
+ VERSION = "0.1.0"
5
+ end
data/lib/paygate_pk.rb ADDED
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "paygate_pk/version"
4
+ require_relative "paygate_pk/errors"
5
+ require_relative "paygate_pk/config"
6
+ require_relative "paygate_pk/http/client"
7
+
8
+ # Contracts used by the endpoint
9
+ require_relative "paygate_pk/contracts/access_token"
10
+ require_relative "paygate_pk/contracts/hosted_checkout"
11
+
12
+ # PayFast
13
+ require_relative "paygate_pk/providers/pay_fast/client"
14
+ require_relative "paygate_pk/providers/pay_fast/auth"
15
+ require_relative "paygate_pk/providers/pay_fast/checkout"
16
+
17
+ require_relative "paygate_pk/util/html"
18
+
19
+ # Main module for PaygatePk
20
+ module PaygatePk
21
+ class << self
22
+ def configure
23
+ yield(config)
24
+ config.freeze!
25
+ end
26
+
27
+ def config
28
+ @config ||= PaygatePk::Config.new
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/paygate_pk/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "paygate_pk"
7
+ spec.version = PaygatePk::VERSION
8
+ spec.authors = ["Talha Junaid"]
9
+ spec.email = ["talhajunaid65@gmail.com"]
10
+ spec.summary = "Unified Ruby wrapper for PayFast"
11
+ spec.description = "Provider-agnostic Ruby/Rails client for PayFast: checkout, webhooks/IPN verification,
12
+ tokenized & recurring payments."
13
+ spec.license = "MIT"
14
+ spec.homepage = "https://github.com/qbitechs/paygate_pk"
15
+ spec.metadata = {
16
+ "source_code_uri" => "https://github.com/qbitechs/paygate_pk",
17
+ "changelog_uri" => "https://github.com/qbitechs/paygate_pk/blob/main/CHANGELOG.md",
18
+ "homepage_url" => spec.homepage
19
+ }
20
+
21
+ spec.required_ruby_version = ">= 2.6.0"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (File.expand_path(f) == __FILE__) || f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor])
28
+ end
29
+ end
30
+ spec.bindir = "exe"
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = %w[lib test]
33
+
34
+ # Runtime deps
35
+ spec.add_dependency "faraday", ">= 2.7"
36
+ spec.add_dependency "faraday-retry", ">= 2.0"
37
+ spec.add_dependency "json"
38
+
39
+ # spec.add_development_dependency "byebug"
40
+ spec.add_development_dependency "minitest", "~> 5.0"
41
+ spec.add_dependency "nokogiri", ">= 1.16", "< 2.0"
42
+ spec.add_development_dependency "rake", "~> 13.0"
43
+ spec.add_development_dependency "rubocop", "~> 1.21"
44
+ spec.add_development_dependency "simplecov", ">= 0.22"
45
+ spec.add_development_dependency "webmock"
46
+ end
@@ -0,0 +1,4 @@
1
+ module PaygatePk
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,202 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: paygate_pk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Talha Junaid
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-10-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.7'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday-retry
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: json
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: nokogiri
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '1.16'
76
+ - - "<"
77
+ - !ruby/object:Gem::Version
78
+ version: '2.0'
79
+ type: :runtime
80
+ prerelease: false
81
+ version_requirements: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '1.16'
86
+ - - "<"
87
+ - !ruby/object:Gem::Version
88
+ version: '2.0'
89
+ - !ruby/object:Gem::Dependency
90
+ name: rake
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '13.0'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '13.0'
103
+ - !ruby/object:Gem::Dependency
104
+ name: rubocop
105
+ requirement: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '1.21'
110
+ type: :development
111
+ prerelease: false
112
+ version_requirements: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - "~>"
115
+ - !ruby/object:Gem::Version
116
+ version: '1.21'
117
+ - !ruby/object:Gem::Dependency
118
+ name: simplecov
119
+ requirement: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0.22'
124
+ type: :development
125
+ prerelease: false
126
+ version_requirements: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - ">="
129
+ - !ruby/object:Gem::Version
130
+ version: '0.22'
131
+ - !ruby/object:Gem::Dependency
132
+ name: webmock
133
+ requirement: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - ">="
136
+ - !ruby/object:Gem::Version
137
+ version: '0'
138
+ type: :development
139
+ prerelease: false
140
+ version_requirements: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ description: |-
146
+ Provider-agnostic Ruby/Rails client for PayFast: checkout, webhooks/IPN verification,
147
+ tokenized & recurring payments.
148
+ email:
149
+ - talhajunaid65@gmail.com
150
+ executables: []
151
+ extensions: []
152
+ extra_rdoc_files: []
153
+ files:
154
+ - ".rubocop.yml"
155
+ - CHANGELOG.md
156
+ - CODE_OF_CONDUCT.md
157
+ - Gemfile
158
+ - Gemfile.lock
159
+ - LICENSE.txt
160
+ - README.md
161
+ - Rakefile
162
+ - lib/paygate_pk.rb
163
+ - lib/paygate_pk/config.rb
164
+ - lib/paygate_pk/contracts/access_token.rb
165
+ - lib/paygate_pk/contracts/hosted_checkout.rb
166
+ - lib/paygate_pk/errors.rb
167
+ - lib/paygate_pk/http/client.rb
168
+ - lib/paygate_pk/providers/pay_fast/auth.rb
169
+ - lib/paygate_pk/providers/pay_fast/checkout.rb
170
+ - lib/paygate_pk/providers/pay_fast/client.rb
171
+ - lib/paygate_pk/util/html.rb
172
+ - lib/paygate_pk/version.rb
173
+ - paygate_pk.gemspec
174
+ - sig/paygate_pk.rbs
175
+ homepage: https://github.com/qbitechs/paygate_pk
176
+ licenses:
177
+ - MIT
178
+ metadata:
179
+ source_code_uri: https://github.com/qbitechs/paygate_pk
180
+ changelog_uri: https://github.com/qbitechs/paygate_pk/blob/main/CHANGELOG.md
181
+ homepage_url: https://github.com/qbitechs/paygate_pk
182
+ post_install_message:
183
+ rdoc_options: []
184
+ require_paths:
185
+ - lib
186
+ - test
187
+ required_ruby_version: !ruby/object:Gem::Requirement
188
+ requirements:
189
+ - - ">="
190
+ - !ruby/object:Gem::Version
191
+ version: 2.6.0
192
+ required_rubygems_version: !ruby/object:Gem::Requirement
193
+ requirements:
194
+ - - ">="
195
+ - !ruby/object:Gem::Version
196
+ version: '0'
197
+ requirements: []
198
+ rubygems_version: 3.4.3
199
+ signing_key:
200
+ specification_version: 4
201
+ summary: Unified Ruby wrapper for PayFast
202
+ test_files: []