Mehmet Aydoğdu vor 2 Jahren
Commit
97c59c7c67

+ 27 - 0
.github/workflows/main.yml

@@ -0,0 +1,27 @@
+name: Ruby
+
+on:
+  push:
+    branches:
+      - master
+
+  pull_request:
+
+jobs:
+  build:
+    runs-on: ubuntu-latest
+    name: Ruby ${{ matrix.ruby }}
+    strategy:
+      matrix:
+        ruby:
+          - '3.1.2'
+
+    steps:
+    - uses: actions/checkout@v3
+    - name: Set up Ruby
+      uses: ruby/setup-ruby@v1
+      with:
+        ruby-version: ${{ matrix.ruby }}
+        bundler-cache: true
+    - name: Run the default task
+      run: bundle exec rake

+ 8 - 0
.gitignore

@@ -0,0 +1,8 @@
+/.bundle/
+/.yardoc
+/_yardoc/
+/coverage/
+/doc/
+/pkg/
+/spec/reports/
+/tmp/

+ 16 - 0
.rubocop.yml

@@ -0,0 +1,16 @@
+require:
+  - rubocop-rake
+  - rubocop-minitest
+AllCops:
+  TargetRubyVersion: 2.6
+
+Style/StringLiterals:
+  Enabled: true
+  EnforcedStyle: double_quotes
+
+Style/StringLiteralsInInterpolation:
+  Enabled: true
+  EnforcedStyle: double_quotes
+
+Layout/LineLength:
+  Max: 120

+ 5 - 0
CHANGELOG.md

@@ -0,0 +1,5 @@
+## [Unreleased]
+
+## [0.1.0] - 2022-10-06
+
+- Initial release

+ 84 - 0
CODE_OF_CONDUCT.md

@@ -0,0 +1,84 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+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.
+
+We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or
+  advances of any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email
+  address, without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+  professional setting
+
+## Enforcement Responsibilities
+
+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.
+
+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.
+
+## Scope
+
+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.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mehmet@akillibulut.net. All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
+
+**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.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of actions.
+
+**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.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
+
+**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.
+
+### 4. Permanent Ban
+
+**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.
+
+**Consequence**: A permanent ban from any sort of public interaction within the community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
+available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
+
+Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see the FAQ at
+https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.

+ 21 - 0
Gemfile

@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+source "https://rubygems.org"
+
+# Specify your gem's dependencies in paratika.gemspec
+gemspec
+
+gem 'appmap', :groups => [:development, :test]
+
+gem "rake", "~> 13.0"
+
+gem "minitest", "~> 5.0"
+gem 'minitest-reporters'
+gem 'minitest-focus'
+
+gem 'rubocop', require: false
+gem 'rubocop-rake', require: false
+gem 'rubocop-minitest', require: false
+
+gem "activesupport", ">= 7.0"
+gem 'paratika', path: "../paratika" # payment gateway

+ 108 - 0
Gemfile.lock

@@ -0,0 +1,108 @@
+PATH
+  remote: ../paratika
+  specs:
+    paratika (1.0.0)
+      activesupport (>= 7.0)
+
+PATH
+  remote: .
+  specs:
+    payment (1.0.0)
+      activesupport (>= 7.0)
+      paratika (~> 1.0)
+
+GEM
+  remote: https://rubygems.org/
+  specs:
+    activesupport (7.1.3.2)
+      base64
+      bigdecimal
+      concurrent-ruby (~> 1.0, >= 1.0.2)
+      connection_pool (>= 2.2.5)
+      drb
+      i18n (>= 1.6, < 2)
+      minitest (>= 5.1)
+      mutex_m
+      tzinfo (~> 2.0)
+    ansi (1.5.0)
+    appmap (1.0.0)
+      activesupport
+      method_source
+      rack
+      reverse_markdown
+    ast (2.4.2)
+    base64 (0.2.0)
+    bigdecimal (3.1.7)
+    builder (3.2.4)
+    concurrent-ruby (1.2.3)
+    connection_pool (2.4.1)
+    drb (2.2.1)
+    i18n (1.14.4)
+      concurrent-ruby (~> 1.0)
+    json (2.7.1)
+    language_server-protocol (3.17.0.3)
+    method_source (1.0.0)
+    minitest (5.22.3)
+    minitest-focus (1.4.0)
+      minitest (>= 4, < 6)
+    minitest-reporters (1.6.1)
+      ansi
+      builder
+      minitest (>= 5.0)
+      ruby-progressbar
+    mutex_m (0.2.0)
+    nokogiri (1.16.3-x86_64-linux)
+      racc (~> 1.4)
+    parallel (1.24.0)
+    parser (3.3.0.5)
+      ast (~> 2.4.1)
+      racc
+    racc (1.7.3)
+    rack (3.0.10)
+    rainbow (3.1.1)
+    rake (13.1.0)
+    regexp_parser (2.9.0)
+    reverse_markdown (2.1.1)
+      nokogiri
+    rexml (3.2.6)
+    rubocop (1.62.1)
+      json (~> 2.3)
+      language_server-protocol (>= 3.17.0)
+      parallel (~> 1.10)
+      parser (>= 3.3.0.2)
+      rainbow (>= 2.2.2, < 4.0)
+      regexp_parser (>= 1.8, < 3.0)
+      rexml (>= 3.2.5, < 4.0)
+      rubocop-ast (>= 1.31.1, < 2.0)
+      ruby-progressbar (~> 1.7)
+      unicode-display_width (>= 2.4.0, < 3.0)
+    rubocop-ast (1.31.2)
+      parser (>= 3.3.0.4)
+    rubocop-minitest (0.35.0)
+      rubocop (>= 1.61, < 2.0)
+      rubocop-ast (>= 1.31.1, < 2.0)
+    rubocop-rake (0.6.0)
+      rubocop (~> 1.0)
+    ruby-progressbar (1.13.0)
+    tzinfo (2.0.6)
+      concurrent-ruby (~> 1.0)
+    unicode-display_width (2.5.0)
+
+PLATFORMS
+  x86_64-linux
+
+DEPENDENCIES
+  activesupport (>= 7.0)
+  appmap
+  minitest (~> 5.0)
+  minitest-focus
+  minitest-reporters
+  paratika!
+  payment!
+  rake (~> 13.0)
+  rubocop
+  rubocop-minitest
+  rubocop-rake
+
+BUNDLED WITH
+   2.3.23

+ 21 - 0
LICENSE.txt

@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2022 Mehmet Aydoğdu
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 58 - 0
README.md

@@ -0,0 +1,58 @@
+[Unoffical] Paratika Ruby Gem for Payments
+
+Visitor Count: ![Visitor Count](https://profile-counter.glitch.me/paratika_ruby/count.svg)
+
+[Visit the gem at RubyGems.org](https://rubygems.org/gems/paratika)
+
+[See Paratika webpage](http://paratika.com.tr/)
+
+### Getting started
+
+Add the following line to your Gemfile:
+
+```ruby
+gem 'paratika'
+```
+
+or
+```cmd
+gem install paratika
+require 'paratika'
+```
+
+Here is a possible configuration for development `config/environments/development.rb`:
+
+```ruby
+paratika.configure  do |config|
+  config.merchant_id = YOUR_MERCHANT_ID
+  config.merchant_user = YOUR_MERCHANT_USER
+  config.merchant_password = YOUR_MERCHANT_PASSWORD
+end
+```
+This parameters are default but you can change it while using on the fly.
+
+Note: You must send the signed CSR file to Paratika BANK, otherwise you will get, certificate error.
+
+### Example Usages
+
+```
+# Check test/test_paratika.rb
+```
+
+### Testing
+
+```
+rake test
+```
+
+### Contributors
+[AKILLI BULUT](https://github.com/akillibulut/paratika)
+
+
+## License
+
+The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
+
+## Code of Conduct
+
+Everyone interacting in the Paratika project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/paratika/blob/master/CODE_OF_CONDUCT.md).

+ 18 - 0
Rakefile

@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+require "bundler/gem_tasks"
+require "rake/testtask"
+
+Rake::TestTask.new(:test) do |t|
+  t.libs << "test"
+  t.libs << "lib"
+  t.test_files = FileList["test/**/test_*.rb"]
+end
+
+require "rubocop/rake_task"
+
+RuboCop::RakeTask.new(:rubocop) do |t|
+  t.requires << "rubocop-rake"
+end
+
+task default: %i[test rubocop]

+ 5 - 0
appmap.yml

@@ -0,0 +1,5 @@
+name: payment
+packages:
+  - path: lib
+language: ruby
+appmap_dir: tmp/appmap

+ 15 - 0
bin/console

@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+# frozen_string_literal: true
+
+require "bundler/setup"
+require "payment"
+
+# You can add fixtures and/or initialization code here to make experimenting
+# with your gem easier. You can also use a different console, if you like.
+
+# (If you use this, don't forget to add pry to your Gemfile!)
+# require "pry"
+# Pry.start
+
+require "irb"
+IRB.start(__FILE__)

+ 8 - 0
bin/setup

@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -euo pipefail
+IFS=$'\n\t'
+set -vx
+
+bundle install
+
+# Do any other automated setup that you need to do here

+ 43 - 0
lib/payment.rb

@@ -0,0 +1,43 @@
+module Payment
+  require_relative "payment/version"
+  require_relative 'payment/errors'
+  require_relative 'payment/base'
+  require_relative 'payment/paratika_gateway'
+  require_relative 'payment/test_gateway'
+  require_relative 'payment/test_cards'
+  require 'active_support/all' unless defined?(Rails)
+  require 'csv'
+
+  def self.config
+    @config ||= OpenStruct.new
+  end
+
+  def self.configure
+    yield(config)
+  end
+
+  def self.active?
+    config.active
+  end
+
+  def self.adapter
+    raise "Payment Module is not set" if Payment.config.adapter.nil?
+    "Payment::#{config.adapter}".constantize
+  end
+
+  def self.print_log(msg)
+    if defined?(Rails) && Rails.respond_to?(:logger)
+      Rails.logger.error(msg)
+    else
+      require 'logger'
+      logger = Logger.new(STDOUT)
+      logger.error(msg)
+    end
+  end
+
+  def self.debug_message(*args)
+    self.print_log(args[2])
+    [(args[0] || { error: "Runtime error: Request failed" }), (args[1] || { error: "Runtime error: Response initializing failed", success: false })]
+  end
+
+end

+ 72 - 0
lib/payment/base.rb

@@ -0,0 +1,72 @@
+module Payment
+  class Base
+    def self.charge_from_card(payment, customer, card, pre_auth, saved_card = true)
+      amount = pre_auth ? 0 : payment[:amount]
+      event_type = pre_auth ? "pre_authorization" : "credit_card_payment"
+      id = {id: "c-#{Billing::WalletTransaction.id_generator}"}
+      payment.merge!(id)
+      request, response = default_gateway.charge_from_card(payment, customer, card, pre_auth, saved_card)
+      {event_type: event_type, amount: amount, currency: payment[:currency], metadata: {response: response, request: request, external_id: payment[:id], gateway: default_gateway.to_s, refunded: false}, success: response[:success]}
+    end
+
+    def self.cancel_transaction(refundable, pre_auth)
+      event_type = pre_auth ? "cancel_pre_auth" : "cancel_transaction"
+      amount = pre_auth ? 0 : -(refundable[:amount])
+      request, response = default_gateway.cancel_transaction(refundable)
+      request.merge!({amount: -refundable[:amount]}) if pre_auth
+      {event_type: event_type, amount: amount, currency: refundable[:currency], metadata: {"request" => request, "response" => response, external_id: refundable[:id] , gateway: default_gateway.to_s}, success: response[:success]}
+    end
+
+    def self.refund_money(refundable)
+      request, response = default_gateway.refund_money(refundable)
+      {event_type: "credit_card_refund", amount: -(refundable[:amount]), currency: refundable[:currency], metadata: {"request" => request, "response" => response, external_id: refundable[:id], gateway: default_gateway.to_s}, success: response[:success]}
+    end
+
+    def self.query_saved_cards(customer)
+      _, response = default_gateway.query_saved_cards(customer)
+      response
+    end
+
+    def self.delete_card(tokens)
+      success = true
+      tokens.each do |adapter, token|
+        _, response = adapter.constantize.delete_card(token)
+        success = success && response[:success] # rubocop:disable Style/SelfAssignment
+      end
+      success
+    end
+
+    def self.currency_exchange(from, to, amount)
+      _, response = default_gateway.currency_exchange(from, to, amount)
+      response
+    end
+
+    def self.query_bin_number(bin)
+      _, response = default_gateway.query_bin_number(bin)
+      response
+    end
+
+    def self.query_card_type_with_bin_number(bin)
+      _, response = default_gateway.query_bin_number(bin)
+      response[:success] ? (response[:bin]["cardBrand"] == "VISA" ? "visa" : "mastercard") : "other" # rubocop:disable Style/NestedTernaryOperator
+    end
+
+    def self.default_gateway(user = nil)
+      return Payment::TestGateway if Rails.env.test?
+      case user&.country
+      when "TR"
+        Payment::Paratika
+      when "US", "UK"
+        Payment::Stripe
+      when "CN"
+        Payment::AliPay
+      when "RU"
+        Payment::YandexPay
+      else
+        Payment.adapter
+      end
+    end
+
+
+  end
+end

+ 9 - 0
lib/payment/errors.rb

@@ -0,0 +1,9 @@
+module Payment::Errors
+  ERROR_CODES = %i[insufficient_funds retry_later].freeze
+
+  class PaymentErrorCodesMismatchError < StandardError; end
+
+  def self.included(base)
+    raise PaymentErrorCodesMismatchError.new("'#{ERROR_CODES.difference(base::ERROR_MAP.values).join(", ")}' method(s) are not included in #{base}") if ERROR_CODES.difference(base::ERROR_MAP.values).any?
+  end
+end

+ 80 - 0
lib/payment/paratika_gateway.rb

@@ -0,0 +1,80 @@
+require 'payment/errors'
+require_relative '../../../paratika/lib/paratika'
+
+class Payment::ParatikaGateway
+  include ::Paratika
+  ERROR_MAP = Paratika::ERROR_MAP
+
+  include Payment::Errors
+
+  def self.active?
+    Paratika.config.active
+  end
+
+  def self.connection
+    request =  yield
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.charge_from_card(payment, customer, card, pre_auth, saved_card)
+    klass = pre_auth ? Paratika::PreAuth : Paratika::Sale
+    card = saved_card ? { token: card } : card
+    request = klass.new(payment, customer, card)
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.cancel_transaction(payment)
+    request =  Paratika::Void.new(payment)
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.refund_money(payment)
+    request =  Paratika::Refund.new(payment)
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.query_saved_cards(customer)
+    request =  Paratika::QueryCard.new(customer[:id])
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.delete_card(token)
+    request =  Paratika::EWalletDeleteCard.new(token)
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.currency_exchange(from, to, amount)
+    request =  Paratika::CurrencyExchange.new(from, to, amount)
+    response = request.send
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.query_bin_number(bin_number)
+    request = Paratika::QueryBin.new(bin_number)
+    response = request.send
+
+    [request.data, response.data]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+end

+ 34 - 0
lib/payment/test_cards.rb

@@ -0,0 +1,34 @@
+class Payment::TestCards
+  attr_accessor :paratika, :test_gateway, :expired, :invalid
+
+  # CCV or CVV, typo problem
+
+  def join_path(*args)
+    if defined?(Rails) && defined?(Rails.root)
+      Rails.root.join(*args)
+    else
+      File.join(Dir.pwd, *args)
+    end
+  end
+
+  def initialize
+    paratika_csv = CSV.read(join_path("lib/payment/test_cards/paratika.csv"), headers: true)
+    @paratika = paratika_csv.map do |row|
+      { name: 'John Doe', number: row['Card Number'], month: row['Card Expiry'].split('/')[0], year: row['Card Expiry'].split('/')[1], ccv: row['CVV'] }
+    end
+    test_gateway_csv = CSV.read(join_path("lib/payment/test_cards/test_gateway.csv"), headers: true)
+    @test_gateway = test_gateway_csv.map do |row|
+      { name: 'John Doe', number: row['Card Number'], month: row['Card Expiry'].split('/')[0], year: row['Card Expiry'].split('/')[1], ccv: row['CVV'] }
+    end
+    @invalid = [
+      { name: 'John Doe', number: '0111111111111111', month: '12', year: '2026', ccv: '000' }
+    ]
+    @expired = [
+      { name: 'John Doe', number: '4546711234567894', month: '01', year: '2023', ccv: '123' }
+    ]
+  end
+
+  def self.get(gw)
+    new.send(gw)
+  end
+end

+ 40 - 0
lib/payment/test_cards/paratika.csv

@@ -0,0 +1,40 @@
+Bank,Card Number,Card Expiry,CVV,3D Secure Password
+Ziraat-VISA,4546711234567894,12/2026,000,a
+Ziraat-MASTER,5401341234567891,12/2026,000,a
+AKBANK-VISA,4355084355084358,12/2030,000,a
+AKBANK-MASTER,5571135571135575,12/2030,000,a
+TEB-VISA,4402934402934406,12/2030,000,a
+TEB-MASTER,5101385101385104,12/2030,000,a
+HALKBANK-VISA,4920244920244921,12/2030,001,a
+HALKBANK-MASTER,5404355404355405,12/2030,001,a
+FINANSBANK-VISA,4022774022774026,12/2030,000,a
+FINANSBANK-MASTER,5456165456165454,12/2030,000,a
+ISBANK-VISA,4508034508034509,12/2030,000,a
+ISBANK-MASTER,5406675406675403,12/2030,000,a
+ANADOLUBANK-VISA,4258464258464253,12/2030,000,a
+ANADOLUBANK-MASTER,5222405222405229,12/2030,000,a
+HSBC,5100051016005572,01/2020,742,a
+INGBANK-VISA,4555714555714556,12/2030,000,a
+INGBANK-MASTER,5400245400245409,12/2030,000,a
+QNBFINANS-TROY,9792350046201275,07/2027,993
+GARANTI-TROY,9792052565200010,01/2027,327
+YKB-TROY,6501617060023449,12/2026,000
+YKB-TROY,6501617025774490,12/2026,000
+YKB-TROY,6501617063597076,12/2026,000
+TURKIYE FINANS-TROY,9792182023832743,10/2028,878,a
+SEKERBANK-TROY,6501750104751517,12/2027,516,a
+AKBANK-TROY,9792072000017956,12/2027,000,a
+ABANK-TROY,36577312700094,12/2027,000,a
+YKB-VISA,4506344103118942,12/2025,000
+YKB-VISA,4506347023253988,12/2025,000
+YKB-VISA,4506347028991897,12/2025,000
+YKB-VISA,4506347026523718,12/2025,000
+YKB-MASTER,5400617004770430,12/2025,000
+YKB-MASTER,5400617020092306,12/2025,000
+YKB-MASTER,5400617030400291,12/2025,000
+GARANTI-VISA,4824892919057014,12/2025,067
+GARANTI-MASTER,5378297758742014,05/2025,467
+KUVEYTTURK-MASTER,5188961939192544,06/2025,929,123456
+VAKIFBANK-VISA,4938460158754205,01/2024,715,123456
+VAKIFBANK-VISA,4119790155203496,04/2024,579,123456
+VAKIFBANK-MASTER,5400617020092306,12/2025,Yok,123456

+ 5 - 0
lib/payment/test_cards/test_gateway.csv

@@ -0,0 +1,5 @@
+Bank,Card Number,Card Expiry,CVV,3D Secure Password
+TestBank-VISA,1111111111111111,11/2028,000,a
+AKBANK-VISA,4355084355084358,12/2030,000,a
+TEB-MASTER,5101385101385104,12/2030,000,a
+FINANSBANK-VISA,4022774022774026,12/2030,000,a

+ 94 - 0
lib/payment/test_gateway.rb

@@ -0,0 +1,94 @@
+require 'payment/errors'
+require 'payment/test_cards'
+class Payment::TestGateway
+
+  ERROR_MAP = { ERR20052: :insufficient_funds, ERR20051: :retry_later, ERR20011: :do_not_retry }.freeze
+
+  FAILED_RESPONSE_EXAMPLE = { response_code: "99",
+                              response_msg: "Declined",
+                              error_code: "ERR10048",
+                              error_msg: "Example error message",
+                              violator_param: "MERCHANTPAYMENTID",
+                              time: Time.now,
+                              success: false,
+                              amount: 10,
+                              currency: 'USD',
+                              error: nil }.freeze
+
+  include Payment::Errors
+
+  def self.active?
+    true
+  end
+
+  def self.request
+    {}
+  end
+
+  def self.dummy_api(amount, currency, from = nil, card = nil)
+    if card
+      success = card[:token] || Payment::TestCards.get(:test_gateway).map{ |c| c[:number] }.include?(card[:number])
+      card_token = card[:token] || rand(2).to_s + SecureRandom.urlsafe_base64(23)
+    end
+    h = success || from ? { success: true, amount: amount, currency: currency, card_token: card_token, pg_tran_date: Time.now.to_i } : FAILED_RESPONSE_EXAMPLE
+    h = h.merge({ from_currency: from, to_currency: currency, converted_amount: amount }) if from
+    h
+  end
+
+  def self.charge_from_card(payment, customer, card, pre_auth, saved_card)
+    request = self.request.merge({card_token: card}) if saved_card
+    card = saved_card ? { token: card } : card
+    response = dummy_api(payment[:amount], payment[:currency], nil, card)
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.cancel_transaction(payment)
+    request = self.request.merge({payment: payment})
+    response = dummy_api(payment[:amount], payment[:currency])
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.refund_money(payment)
+    request = self.request.merge({payment: payment})
+    response = dummy_api(payment[:amount], payment[:currency])
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.query_saved_cards(customer)
+    request = self.request.merge({customer: customer[:id]})
+    response = { success: true, card_list: [{ "cardToken" => SecureRandom.urlsafe_base64(24) }] }
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.delete_card(token)
+    request = self.request.merge({card_token: token})
+    response = {success: true}
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.currency_exchange(from, to, amount)
+    request = self.request.merge({from_currency: from, to_currency: to, amount: amount})
+    response = dummy_api(amount, to, from)
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+
+  def self.query_bin_number(bin_number)
+    request = self.request.merge({bin: bin_number})
+    response = { success: true, bin: { "cardBrand": %w[VISA MC].sample } }
+    [request, response]
+  rescue => e
+    Payment.debug_message(request, response, e)
+  end
+end

+ 5 - 0
lib/payment/version.rb

@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+module Payment
+  VERSION = "1.0.0"
+end

+ 40 - 0
payment.gemspec

@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+require_relative "lib/payment/version"
+
+Gem::Specification.new do |spec|
+  spec.name = "payment"
+  spec.version = Payment::VERSION
+  spec.authors = ["Mehmet Aydoğdu"]
+  spec.email = ["mehmet@akillibulut.net"]
+
+  spec.summary = "Payment is a wrapper library."
+  spec.description = "AKILLI BULUT is developing this gem and not responsible for any security issues."
+  spec.homepage = "https://git.akillibulut.net/AKILLIBULUT/Payment"
+  spec.license = "MIT"
+  spec.required_ruby_version = ">= 2.6.0"
+
+  spec.metadata["allowed_push_host"] = "https://git.akillibulut.net/AKILLIBULUT/Payment"
+
+  spec.metadata["homepage_uri"] = spec.homepage
+  spec.metadata["source_code_uri"] = "https://git.akillibulut.net/AKILLIBULUT/Payment"
+  spec.metadata["changelog_uri"] = "https://git.akillibulut.net/AKILLIBULUT/Payment"
+
+  # Specify which files should be added to the gem when it is released.
+  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
+  spec.files = Dir.chdir(__dir__) do
+    `git ls-files -z`.split("\x0").reject do |f|
+      (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
+    end
+  end
+  spec.bindir = "exe"
+  spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
+  spec.require_paths = ["lib"]
+
+  # Uncomment to register a new dependency of your gem
+  spec.add_dependency "activesupport", ">= 7.0"
+  spec.add_dependency "paratika", "~> 1.0"
+
+  # For more information and examples about making a new gem, check out our
+  # guide at: https://bundler.io/guides/creating_gem.html
+end

+ 4 - 0
sig/payment.rbs

@@ -0,0 +1,4 @@
+module Payment
+  VERSION: String
+  # See the writing guide of rbs: https://github.com/ruby/rbs#guides
+end

+ 25 - 0
sig/payment/base.rbs

@@ -0,0 +1,25 @@
+module Payment
+  class Payment
+    attr_reader amount: BigDecimal
+    attr_reader currency: String
+    attr_reader id: String
+  end
+
+  class Customer
+    attr_reader id: Integer
+    attr_reader name: String
+    attr_reader email: String
+  end
+
+  class Card
+    attr_reader number: String
+    attr_reader expiry: String
+    attr_reader ccv: String
+  end
+
+  class Base
+    def self.charge_from_card: (Payment, Customer, Card, bool, bool?) -> Hash
+    def self.cancel_transaction: (Payment, bool) -> Hash
+    def self.refund_money: (Payment) -> Hash
+  end
+end

+ 7 - 0
test/test_helper.rb

@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
+require "payment"
+
+require "minitest/autorun"
+require "minitest/focus"

+ 110 - 0
test/test_payment.rb

@@ -0,0 +1,110 @@
+# rubocop:disable all
+require 'test_helper'
+require 'bigdecimal'
+
+class PaymentTest < Minitest::Test
+  def setup
+    excluded_files = ["base.rb", "errors.rb", "paratika_gateway.rb", "test_cards.rb", "test_cards", "version.rb"]
+    @modules = (Dir.children("lib/payment") - excluded_files).map { |file| "Payment::#{file.split(".")[0].camelcase}" }
+    @mandatory_methods = %w(charge_from_card cancel_transaction refund_money query_saved_cards delete_card currency_exchange)
+    @customer = { id: 'c1', name: 'John Doe', email: 'test@example.com', phone: '905531781020', ip: '7.11.7.11' }
+    @card = { name: 'John Doe', number: '4355084355084358', expiry: '12/2030', ccv: '000', save: 'yes' }
+    @pid = -> { { id: SecureRandom.hex(16), amount: BigDecimal('1.00'), currency: 'TRY' } }
+    @refundable, @payment = @pid.call, @pid.call
+    @new_result_keys = %w(success amount currency card_token)
+    @saved_result_keys = %w(success amount currency)
+  end
+
+  def test_version_number
+    refute_nil ::Payment::VERSION
+  end
+
+  def test_every_billing_module_contains_mandatory_methods
+    @modules.each do |module_name|
+      @mandatory_methods.each do |method_name|
+        assert module_name.constantize.respond_to?(method_name.to_sym), "#{module_name} does not have #{method_name} method"
+      end
+    end
+  end
+
+  def test_pre_auth_method_is_responding_hash
+    @modules.each do |module_name|
+      binding.irb
+      request, response = module_name.constantize.try(:charge_from_card, @payment, @customer, @card, true, false)
+      check_response(response, module_name)
+      assert_equal @new_result_keys.all? { |s| response.key? s.to_sym }, true, "return value must contain all of the following keys: #{@new_result_keys}"
+      @payment = @pid.call
+      request, response = module_name.constantize.try(:charge_from_card, @payment, @customer, response[:card_token], true, true)
+      check_response(response, module_name)
+      assert_equal @saved_result_keys.all? { |s| response.key? s.to_sym }, true, "return value must contain all of the following keys: #{@saved_result_keys}"
+    end
+  end
+
+
+  def test_sale_method_is_responding_hash
+    @modules.each do |module_name|
+      request, response = module_name.constantize.try(:charge_from_card, @payment, @customer, @card, false, false)
+      check_response(response, module_name)
+      assert_equal @new_result_keys.all? {|s| response.key? s.to_sym}, true, "return value must contain all of the following keys: #{@new_result_keys}"
+      @payment = @pid.call
+      request, response = module_name.constantize.try(:charge_from_card, @payment, @customer, response[:card_token], false, true)
+      check_response(response, module_name)
+      assert_equal @saved_result_keys.all? {|s| response.key? s.to_sym}, true, "return value must contain all of the following keys: #{@saved_result_keys}"
+    end
+  end
+
+  def test_cancel_transaction_and_refund_money_methods_are_responding_hash
+    @methods = %w(refund_money cancel_transaction)
+    @modules.each do |module_name|
+      @methods.each do |method_name|
+        @refundable = @pid.call
+        module_name.constantize.charge_from_card(@refundable, @customer, @card, false, false)
+        request, response = send_method_to_gateway(module_name, method_name, @refundable)
+        assert_equal response[:success], true, "api call must be successful on module #{module_name}" if module_name == "TestGateway"
+        assert_equal Hash.new.class, response.class, "return value must be a Hash object on module #{module_name}"
+      end
+    end
+  end
+
+  def test_query_saved_cards_method_is_responding_hash
+    @modules.each do |module_name|
+      request, response = module_name.constantize.query_saved_cards(@customer)
+      check_response(response, module_name)
+      assert_equal response.key?(:card_list), true, "return value must contain :card_list key as a symbol on module #{module_name}"
+      assert_equal [].class, response[:card_list].class, "card_list must be an array on #{module_name} module"
+      assert_equal response[:card_list].all? {|a| a.class == Hash.new.class }, true, "card_list must contain Hash objects on #{module_name} module"
+      assert_equal response[:card_list].all? {|a| a.key? "cardToken" }, true, "card_list must contain cardToken key on #{module_name} module"
+    end
+  end
+
+  def test_delete_card_method_is_responding_hash
+    @modules.each do |module_name|
+      module_name.constantize.charge_from_card(@payment, @customer, @card, false, false)
+      request, response = module_name.constantize.query_saved_cards( @customer)
+      @token = response[:card_list].first["cardToken"]
+      request, response = module_name.constantize.delete_card(@token)
+      check_response(response, module_name)
+    end
+  end
+
+
+  def test_currency_exchange_method_is_responding_hash
+    @modules.each do |module_name|
+      request, response = module_name.constantize.currency_exchange "TRY", "USD", BigDecimal("1.00")
+      check_response(response, module_name)
+      assert_equal %w(amount converted_amount from_currency to_currency success).all? { |a| response.key? a.to_sym }, true, "return value must contain #{%w(amount converted_amount from_currency to_currency success)} keys"
+    end
+  end
+
+  private
+
+  def send_method_to_gateway(module_name, method_name, *args)
+    request, response = module_name.constantize.send(method_name.to_sym, *args)
+  end
+
+  def check_response(response, module_name)
+    assert_equal response[:success], true, "api call must be successful on module #{module_name}"
+    assert_equal Hash.new.class, response.class, "return value must be a Hash object on module #{module_name}"
+  end
+
+end