kkhay 1.0.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: ede43e8b5ffcadeb0e7530a569edad2b57f3bb323f30bdec176d392aadbf9247
4
+ data.tar.gz: 18122defec338469717ffadc0aa4e4bef274c2755878d713311dd24d0c1298f8
5
+ SHA512:
6
+ metadata.gz: 0c46a4d00454e5cab9a627b7e4a6d324ae77e9ef1615490202b15f82d2de621cce1711795f84889a70a7113ac39164347919723ddd5f02fe27fb4473c201fe43
7
+ data.tar.gz: e7695e1e945d988b207b13a308d6598393b12a9665285a147231473d6ed14a4a096d0f7123d195f07289834fd2c921c8dd9c665c71ce1d4328af46f2c77fe8cb
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 K Khay (https://kkhay.com)
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 all
13
+ 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 THE
21
+ SOFTWARE.
22
+
data/README.md ADDED
@@ -0,0 +1,108 @@
1
+ # K Khay Ruby Gem 💎
2
+
3
+ Official Ruby gem for the **[K Khay Sovereign Crypto Payment Gateway](https://kkhay.com)**.
4
+
5
+ Accept non-custodial and custodial crypto payments (USDT, USDC, BNB, ETH across BSC, Polygon, Arbitrum, Base, and Ethereum) directly in **Ruby on Rails**, Sinatra, Hanami, or standalone Ruby backends with **zero external dependencies**.
6
+
7
+ ---
8
+
9
+ ## 📦 Installation
10
+
11
+ Add to your application's `Gemfile`:
12
+
13
+ ```ruby
14
+ gem "kkhay"
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ ```bash
20
+ bundle install
21
+ ```
22
+
23
+ Or install it directly:
24
+
25
+ ```bash
26
+ gem install kkhay
27
+ ```
28
+
29
+ ---
30
+
31
+ ## ⚡ Quick Start
32
+
33
+ ### 1. Global Rails Initializer (`config/initializers/kkhay.rb`)
34
+
35
+ ```ruby
36
+ Kkhay.configure do |config|
37
+ config.api_key = ENV["KKHAY_API_KEY"]
38
+ # config.base_url = "https://api.kkhay.com" # default
39
+ # config.timeout = 30 # default in seconds
40
+ end
41
+ ```
42
+
43
+ ### 2. Create an Invoice
44
+
45
+ ```ruby
46
+ client = Kkhay.client
47
+
48
+ response = client.create_invoice(
49
+ price_amount: 49.99,
50
+ price_currency: "USD",
51
+ pay_network: "bsc",
52
+ pay_token: "USDT",
53
+ order_id: "ORDER-7721",
54
+ title: "Pro Membership",
55
+ customer_email: "buyer@example.com",
56
+ redirect_url: "https://myshop.com/orders/success",
57
+ cancel_url: "https://myshop.com/cart"
58
+ )
59
+
60
+ invoice = response[:invoice]
61
+ puts "Invoice ID: #{invoice[:id]}"
62
+ puts "Hosted Checkout URL: #{invoice[:hostedUrl]}"
63
+ ```
64
+
65
+ ### 3. Check Invoice Status
66
+
67
+ ```ruby
68
+ data = client.get_invoice("inv_9f81a7b2")
69
+ puts "Status: #{data[:invoice][:status]}"
70
+
71
+ data[:payments].each do |payment|
72
+ puts "Tx: #{payment[:txHash]} (#{payment[:confirmations]} confirmations)"
73
+ end
74
+ ```
75
+
76
+ ---
77
+
78
+ ## 🔐 Webhook / IPN Verification (Rails Controller)
79
+
80
+ ```ruby
81
+ class KkhayWebhooksController < ApplicationController
82
+ skip_before_action :verify_authenticity_token
83
+
84
+ def create
85
+ payload = request.raw_post
86
+ signature = request.headers["x-kkhay-signature"]
87
+ secret = ENV["KKHAY_IPN_SECRET"]
88
+
89
+ event = Kkhay::Webhook.parse_event(payload, signature, secret)
90
+
91
+ if event[:event] == "payment.finished"
92
+ order = Order.find_by(id: event[:order_id])
93
+ order&.update!(status: "paid", tx_hash: event[:tx_hash])
94
+ end
95
+
96
+ head :ok
97
+ rescue Kkhay::SignatureVerificationError => e
98
+ render json: { error: e.message }, status: :bad_request
99
+ end
100
+ end
101
+ ```
102
+
103
+ ---
104
+
105
+ ## 📄 License
106
+
107
+ MIT © [K Khay](https://kkhay.com)
108
+
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module Kkhay
8
+ class Client
9
+ attr_reader :api_key, :base_url, :timeout
10
+
11
+ # Initializes the K Khay Client
12
+ #
13
+ # @param api_key [String] Your merchant API key
14
+ # @param base_url [String] Custom gateway URL (defaults to https://api.kkhay.com)
15
+ # @param timeout [Integer] Timeout in seconds (defaults to 30)
16
+ def initialize(api_key: nil, base_url: "https://api.kkhay.com", timeout: 30)
17
+ @api_key = (api_key || Kkhay.configuration&.api_key).to_s.strip
18
+ raise ArgumentError, "Kkhay::Client: A valid 'api_key' is required." if @api_key.empty?
19
+
20
+ @base_url = (base_url || "https://api.kkhay.com").sub(%r{/+\z}, "")
21
+ @timeout = timeout.to_i
22
+ end
23
+
24
+ # Creates a new crypto payment invoice
25
+ #
26
+ # @param params [Hash] Invoice parameters (:price_amount, :pay_network, :pay_token, etc.)
27
+ # @return [Hash] Parsed response containing invoice details and hosted_url
28
+ def create_invoice(params)
29
+ price = params[:price_amount] || params["priceAmount"]
30
+ network = params[:pay_network] || params["payNetwork"]
31
+ token = params[:pay_token] || params["payToken"]
32
+
33
+ raise ArgumentError, "create_invoice: :price_amount must be greater than 0" if price.to_f <= 0
34
+ raise ArgumentError, "create_invoice: :pay_network is required (e.g. 'bsc', 'polygon')" if network.to_s.empty?
35
+ raise ArgumentError, "create_invoice: :pay_token is required (e.g. 'USDT', 'USDC')" if token.to_s.empty?
36
+
37
+ payload = {
38
+ priceAmount: price.to_f,
39
+ payNetwork: network.to_s,
40
+ payToken: token.to_s,
41
+ priceCurrency: (params[:price_currency] || params["priceCurrency"] || "USD").to_s,
42
+ }
43
+
44
+ payload[:orderId] = (params[:order_id] || params["orderId"]).to_s if params[:order_id] || params["orderId"]
45
+ payload[:title] = (params[:title] || params["title"]).to_s if params[:title] || params["title"]
46
+ payload[:customerName] = (params[:customer_name] || params["customerName"]).to_s if params[:customer_name] || params["customerName"]
47
+ payload[:customerEmail] = (params[:customer_email] || params["customerEmail"]).to_s if params[:customer_email] || params["customerEmail"]
48
+ payload[:redirectUrl] = (params[:redirect_url] || params["redirectUrl"]).to_s if params[:redirect_url] || params["redirectUrl"]
49
+ payload[:cancelUrl] = (params[:cancel_url] || params["cancelUrl"]).to_s if params[:cancel_url] || params["cancelUrl"]
50
+ payload[:ipnCallbackUrl] = (params[:ipn_callback_url] || params["ipnCallbackUrl"]).to_s if params[:ipn_callback_url] || params["ipnCallbackUrl"]
51
+ payload[:metadata] = params[:metadata] if params[:metadata]
52
+
53
+ request("/v1/merchant/invoices", method: :post, body: payload)
54
+ end
55
+
56
+ # Retrieves an invoice by UUID
57
+ #
58
+ # @param invoice_id [String] The unique invoice ID
59
+ # @return [Hash] Invoice details and blockchain confirmations
60
+ def get_invoice(invoice_id)
61
+ raise ArgumentError, "get_invoice: invoice_id is required" if invoice_id.to_s.strip.empty?
62
+
63
+ request("/v1/merchant/invoices/#{URI.encode_www_form_component(invoice_id.to_s.strip)}", method: :get)
64
+ end
65
+
66
+ # Lists and paginates merchant invoices
67
+ #
68
+ # @param query [Hash] Filtering and pagination options (:page, :limit, :status, :search)
69
+ # @return [Hash] Paginated invoice records
70
+ def list_invoices(query = {})
71
+ query_params = {}
72
+ query_params["page"] = query[:page] || query["page"] if query[:page] || query["page"]
73
+ query_params["limit"] = query[:limit] || query["limit"] if query[:limit] || query["limit"]
74
+ query_params["status"] = query[:status] || query["status"] if query[:status] || query["status"]
75
+ query_params["search"] = query[:search] || query["search"] if query[:search] || query["search"]
76
+
77
+ query_str = query_params.empty? ? "" : "?#{URI.encode_www_form(query_params)}"
78
+ request("/v1/merchant/invoices#{query_str}", method: :get)
79
+ end
80
+
81
+ # Checks the health of the gateway
82
+ def check_health
83
+ request("/health", method: :get)
84
+ end
85
+
86
+ private
87
+
88
+ def build_url(path)
89
+ clean = path.start_with?("/") ? path : "/#{path}"
90
+ if @base_url.end_with?("/api") || @base_url.include?("api.")
91
+ "#{@base_url}#{clean}"
92
+ else
93
+ "#{@base_url}/api#{clean}"
94
+ end
95
+ end
96
+
97
+ def request(path, method: :get, body: nil)
98
+ uri = URI.parse(build_url(path))
99
+ http = Net::HTTP.new(uri.host, uri.port)
100
+ http.use_ssl = (uri.scheme == "https")
101
+ http.read_timeout = @timeout
102
+ http.open_timeout = @timeout
103
+
104
+ req = case method
105
+ when :post then Net::HTTP::Post.new(uri.request_uri)
106
+ else Net::HTTP::Get.new(uri.request_uri)
107
+ end
108
+
109
+ req["Accept"] = "application/json"
110
+ req["x-api-key"] = @api_key
111
+ req["User-Agent"] = "kkhay-ruby/#{Kkhay::VERSION}"
112
+
113
+ if body
114
+ req["Content-Type"] = "application/json"
115
+ req.body = JSON.generate(body)
116
+ end
117
+
118
+ response = http.request(req)
119
+ parsed = JSON.parse(response.body, symbolize_names: true) rescue {}
120
+
121
+ status_code = response.code.to_i
122
+ if status_code >= 400
123
+ msg = parsed[:message] || parsed[:error] || "HTTP #{status_code} Error"
124
+ raise ApiError.new(status_code, msg, parsed[:code], parsed[:details])
125
+ end
126
+
127
+ parsed
128
+ rescue Net::OpenTimeout, Net::ReadTimeout => e
129
+ raise ApiError.new(408, "Request timed out after #{@timeout}s")
130
+ rescue ApiError
131
+ raise
132
+ rescue StandardError => e
133
+ raise ApiError.new(500, "Network error: #{e.message}")
134
+ end
135
+ end
136
+ end
137
+
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kkhay
4
+ class Error < StandardError; end
5
+
6
+ class ApiError < Error
7
+ attr_reader :status, :code, :details
8
+
9
+ def __initialize__(status, message, code = nil, details = nil)
10
+ @status = status
11
+ @code = code
12
+ @details = details
13
+ super("Kkhay::ApiError [HTTP #{status}]: #{message}")
14
+ end
15
+
16
+ def initialize(status, message, code = nil, details = nil)
17
+ @status = status
18
+ @code = code
19
+ @details = details
20
+ super("Kkhay::ApiError [HTTP #{status}]: #{message}")
21
+ end
22
+ end
23
+
24
+ class SignatureVerificationError < Error; end
25
+ end
26
+
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kkhay
4
+ VERSION = "1.0.0"
5
+ end
6
+
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "json"
5
+
6
+ module Kkhay
7
+ module Webhook
8
+ class << self
9
+ # Verifies the cryptographic HMAC-SHA256 signature sent with incoming K Khay IPN webhooks.
10
+ #
11
+ # @param payload [String, Hash] The raw request body or hash
12
+ # @param signature [String] The x-kkhay-signature header value
13
+ # @param ipn_secret [String] Your merchant IPN Secret Key
14
+ # @return [Boolean] true if signature matches
15
+ def verify_signature(payload, signature, ipn_secret)
16
+ return false if signature.nil? || signature.to_s.strip.empty? || ipn_secret.nil? || ipn_secret.to_s.strip.empty?
17
+
18
+ raw_body = payload.is_a?(String) ? payload : JSON.generate(payload)
19
+ expected = OpenSSL::HMAC.hexdigest("SHA256", ipn_secret.to_s, raw_body)
20
+
21
+ secure_compare(expected, signature.to_s.strip)
22
+ rescue StandardError
23
+ false
24
+ end
25
+
26
+ # Validates and parses incoming webhook payload into a Ruby Hash with symbolize_names.
27
+ #
28
+ # @raise [SignatureVerificationError] if signature is invalid
29
+ def parse_event(raw_body, signature, ipn_secret)
30
+ unless verify_signature(raw_body, signature, ipn_secret)
31
+ raise SignatureVerificationError, "Invalid K Khay webhook signature: Request rejected."
32
+ end
33
+
34
+ JSON.parse(raw_body, symbolize_names: true)
35
+ rescue JSON::ParserError => e
36
+ raise ArgumentError, "Failed to parse webhook JSON payload: #{e.message}"
37
+ end
38
+
39
+ private
40
+
41
+ def secure_compare(a, b)
42
+ return false unless a.bytesize == b.bytesize
43
+
44
+ l = a.unpack("C*")
45
+ r = b.unpack("C*")
46
+ res = 0
47
+ l.each_with_index do |byte, i|
48
+ res |= byte ^ r[i]
49
+ end
50
+ res.zero?
51
+ end
52
+ end
53
+ end
54
+ end
55
+
data/lib/kkhay.rb ADDED
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "kkhay/version"
4
+ require_relative "kkhay/errors"
5
+ require_relative "kkhay/webhook"
6
+ require_relative "kkhay/client"
7
+
8
+ module Kkhay
9
+ class Configuration
10
+ attr_accessor :api_key, :base_url, :timeout
11
+
12
+ def initialize
13
+ @api_key = nil
14
+ @base_url = "https://api.kkhay.com"
15
+ @timeout = 30
16
+ end
17
+ end
18
+
19
+ class << self
20
+ attr_writer :configuration
21
+
22
+ def configuration
23
+ @configuration ||= Configuration.new
24
+ end
25
+
26
+ def configure
27
+ yield(configuration)
28
+ end
29
+
30
+ def reset_configuration!
31
+ @configuration = Configuration.new
32
+ end
33
+
34
+ # Convenience method to instantiate a new client
35
+ def client(api_key: nil, base_url: nil, timeout: nil)
36
+ Client.new(
37
+ api_key: api_key || configuration.api_key,
38
+ base_url: base_url || configuration.base_url,
39
+ timeout: timeout || configuration.timeout
40
+ )
41
+ end
42
+ end
43
+ end
44
+
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: kkhay
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - K Khay
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-10-06 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Accept non-custodial and custodial crypto payments (USDT, USDC, BNB,
14
+ ETH on BSC, Polygon, Arbitrum, Base, Ethereum) in Ruby on Rails applications.
15
+ email:
16
+ - dev@kkhay.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - LICENSE
22
+ - README.md
23
+ - lib/kkhay.rb
24
+ - lib/kkhay/client.rb
25
+ - lib/kkhay/errors.rb
26
+ - lib/kkhay/version.rb
27
+ - lib/kkhay/webhook.rb
28
+ homepage: https://kkhay.com
29
+ licenses:
30
+ - MIT
31
+ metadata:
32
+ homepage_uri: https://kkhay.com
33
+ source_code_uri: https://github.com/boboaungdev/kkhay-ruby
34
+ changelog_uri: https://github.com/boboaungdev/kkhay-ruby/blob/main/CHANGELOG.md
35
+ bug_tracker_uri: https://github.com/boboaungdev/kkhay-ruby/issues
36
+ post_install_message:
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 3.0.0
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 3.4.19
52
+ signing_key:
53
+ specification_version: 4
54
+ summary: Official Ruby Gem for K Khay Sovereign Crypto Payment Gateway
55
+ test_files: []