• Stars
    star
    20
  • Rank 1,084,242 (Top 22 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 13 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple implementation of the Datatrans API (see datatrans.ch)

Datatrans

Ruby adapter for the Datatrans payment gateway (http://www.datatrans.ch).

Configuration

Build your Datatrans Configuration like so:

    datatrans = Datatrans::Config.new(
      :merchant_id => '1234567',
      :sign_key => 'ab739fd5b7c2a1...',
      :password => 'server to server request password',
      :environment => :production,
      :proxy => {
        :http_proxyaddr => "proxy.com",
        :http_proxyport => 80,
        :http_proxyuser => "hans",
        :http_proxpass => "xxx",
      }
    )

If you don't want to use signed requests (disabled in datatrans web console), you can set config.sign_key to false. The configuration is then used as parameter to all the constructors and helpers, see examples below.

Possible values for the environment: :production, :development

Web Authorization

Important

Datatrans no longer supports the Payment Page API. The support in this gem will be removed in the next major release. Please use the JSON API instead.

If you want to process a credit card the first time a web authorization is necessary. Add the following code to a controller action that shows the form. You need to pass at least amount, currency and refno (order number).

    @transaction = datatrans.web_transaction(
      :amount => 1000, # in cents!
      :currency => 'CHF',
      :refno => 'ABCDEF',
      :uppCustomerEmail => '[email protected]',
      # feel free to add more upp infos here ...
    )

In your View your show the credit card form with a convenient helper:

    = form_tag Datatrans.web_authorize_url do

      = text_field_tag :paymentmethod, 'ECA'
      = text_field_tag :cardno
      = text_field_tag :expm
      = text_field_tag :expy
      = text_field_tag :cvv

      = hidden_field_tag :successUrl, <your_application_return_url>
      = hidden_field_tag :cancelUrl, <your_application_return_url>
      = hidden_field_tag :errorUrl, <your_application_return_url>

      = datatrans_notification_request_hidden_fields(datatrans, @transaction)

      = submit_tag "send"

In this example we use just ECA (Mastercard) as paymentmethod. Feel free to provide an appropriate select field to offer more payment methods. Don't forget to add successUrl, cancelUrl and errorUrl. We recommend to set them all to the same value.

After you submit the request to Datatrans they redirect back to your application. Now you can process the transaction like this:

    begin
      transaction = datatrans.web_transaction(params)

      if transaction.authorize
        # transaction was successful, access the following attributes
        # transaction.transaction_id
        # transaction.creditcard_alias
        # transaction.masked_cc
        # transaction.authorization_code
        # ...

      else
        # transaction was not successful, accces the error details
        # transaction.error_code, transaction.error_message, transaction.error_detail

      end
    rescue Datatrans::InvalidSignatureError => exception
      # the signature was wrong, the request may have been compromised...
    end

JSON Transactions

More information about Datatrans JSON API can be found here. Our gem uses endpoints from /v1/transactions section.

We implemented support for Redirect mode (since Lightbox mode may not work correctly on mobile, whereas Redirect works well on all devices).

Saving Payment Information

According to the docs, there are three possible flows:

  • Customer Initiated Payments: Your customer pays and nothing is registered.
    • This is the most basic setup and does not save any payment information: First, call transaction.init, and then redirect the user to the transaction_path (see the sections Initialize and Start a transaction below).
  • Customer Initiated Payment and creating an alias for subsequent Merchant Initiated Payments: Your customer pays and the card or payment method information is registered. You receive an alias which you save for later merchant initiated payments or one-click checkouts.
    • In order to save payment information after your customer has finalized their payment, without them having to re-enter their payment information and go through the 3D-Secure flow, pass option: {"createAlias": true}. More information can be found here.
  • Merchant Initiated Payments: Your customer registers their card or payment method information without any payment. Their account is not charged. This is what we call a dedicated registration.
    • This setup allows you to save a customers payment information without any charge in the beginning. This is useful in the context of setting up a subscription model (e.g., usage-based billing at the end of a billing period). See the section Merchant Initiated Payments below.

Initialize

Initialize a JSON transaction:

transaction = datatrans.json_transaction(
  refno: 'ABCDEF',
  amount: 1000, # in cents!
  currency: "CHF",
  payment_methods: ["ECA", "VIS"],
  success_url: <your_application_return_url>,
  cancel_url: <your_application_return_url>,
  error_url: <your_application_return_url>
)

# call to initialize endpoint to initialize a transaction
# returns true or false depending if response was successful or not
init = transaction.init

# successful authorization call returns in response a transaction id
if init
  transaction_id = transaction.response.params["transactionId"]
end

Start a transaction

Once you have a transaction id, you can start a transaction. Users of your application will be redirected to the datatrans payment pages: https://pay.sandbox.datatrans.com/v1/start/{{transactionId}}.

 path = datatrans.json_transaction(transaction_id: transaction_id).transaction_path

 redirect_to path
 # or if you redirect after AJAX request:
 render js: "window.location='#{path}'"

You do not have to settle a transaction by yourself: we set "autoSettle": true by default when authorizing a transaction, which means the transaction will be settled automatically. This can be overridden by setting auto_settle: false when authorizing a transaction.

Transaction status

You can check the trasaction status, see its history and retrieve the card information.

  transaction = datatrans.json_transaction(transaction_id: transaction_id)

  # status method returns true or false depending if response was successfull
  if transaction.status
    data = transaction.response.params
    # this will return following hash (may vary dependong on your payment method):
    {
      "transactionId"=>"230223022302230223",
      "merchantId"=>"1100000000",
      "type"=>"payment",
      "status"=>"settled",
      "currency"=>"CHF",
      "refno"=>"123456abc",
      "paymentMethod"=>"VIS",
      "detail"=>
        {"authorize"=>{"amount"=>1000, "acquirerAuthorizationCode"=>"100000"}, "settle"=>{"amount"=>1000}},
      "language"=>"en",
      "card"=>
        {"masked"=>"400000xxxxxx0018",
        "expiryMonth"=>"06",
        "expiryYear"=>"25",
        "info"=>
          {"brand"=>"VISA",
          "type"=>"debit",
          "usage"=>"consumer",
          "country"=>"SE",
          "issuer"=>"SVENSKA HANDELSBANKEN AB"},
        "3D"=>{"authenticationResponse"=>"Y"}},
      "history"=>
        [{"action"=>"init",
          "amount"=>1000,
          "source"=>"api",
          "date"=>"2023-06-06T08:37:23Z",
          "success"=>true,
          "ip"=>"8.8.8.8"},
        {"action"=>"authorize",
          "autoSettle"=>true,
          "amount"=>1000,
          "source"=>"redirect",
          "date"=>"2023-06-06T08:37:42Z",
          "success"=>true,
          "ip"=>"8.8.8.8"}]
    }
  else
    transaction.response.error_code
    transaction.response.error_message
  end

Merchant Initiated Payments

It's possible to authorize transactions without user interaction, via merchant initiated payments.

To perform a so-called "dedicated registration" (so we can later charge the card via its alias), you should follow the same steps as described above, but not provide an amount:

transaction = datatrans.json_transaction(
  refno: 'ABCDEF',
  amount: 0, # omit amount for dedicated registrations
  currency: "CHF",
  payment_methods: ["ECA", "VIS"],
  success_url: <your_application_return_url>,
  cancel_url: <your_application_return_url>,
  error_url: <your_application_return_url>
)

init = transaction.init

# successful authorization call returns in response a transaction id
if init
  transaction_id = transaction.response.params["transactionId"]
end

Then, at a later point in time, and without needing any user interaction, you can create a payment via merchant_authorize:

dedicated_registration = datatrans.json_transaction(transaction_id: transaction_id)
dedicated_registration.status # this will contain the card information

card_alias = dedicated_registration.response.params["card"]["alias"]
card_expiry_month = dedicated_registration.response.params["card"]["expiryMonth"]
card_expiry_year = dedicated_registration.response.params["card"]["expiryYear"]

transaction = datatrans.json_transaction(
  refno: "ABCDEF",
  amount: 1000,
  currency: "CHF",
  card: {alias: card_alias, expiryMonth: card_expiry_month, expiryYear: card_expiry_year}
)

transaction.merchant_authorize # this will charge the card without user interaction

XML Transactions

Important

Datatrans will stop supporting the XML API on June 3rd, 2024. The support in this gem will be removed in the next major release. Please use the JSON API instead.

If you have already a credit card alias or an authorized transaction you can use the convenient XML methods to process payments.

Authorize

    transaction = datatrans.xml_transaction(
      :refno => 'ABCDEF',
      :amount => 1000, # in cents!
      :currency => 'CHF',
      :aliasCC => '8383843729284848348',
      :expm => 12,
      :expy => 15,
    )

    if transaction.authorize
      # ok, the transaction is authorized...
      # access same values as in the web authorization (e.g. transaction.transaction_id)
    else
      # transaction.error_code, transaction.error_message, transaction.error_detail
    end

Capture

To capture an authorized transaction you use the following code:

    transaction = datatrans.xml_transaction(
      :refno => 'ABCDEF',
      :amount => 1000, # in cents!
      :currency => 'CHF',
      :transaction_id => 19834324987349723948729834,
    )

    if transaction.capture
      # ok, the money is yours...
    else
      # transaction.error_code, transaction.error_message, transaction.error_detail
    end

Void

To make an authorized transaction invalid use void.

    transaction = datatrans.xml_transaction(
      :refno => 'ABCDEF',
      :amount => 1000, # in cents!
      :currency => 'CHF',
      :transaction_id => 19834324987349723948729834,
    )

    if transaction.void
      # ok, the transaction is not longer valid...
    else
      # transaction.error_code, transaction.error_message, transaction.error_detail
    end

Todo

  • allow signing of xml transactions
  • allow signing with different keys
  • add credit method to reverse already captured transactions
  • add purchase method to authorize and capture in one step
  • add url helpers for success, cancel and error urls
  • extend configuration possibilities
  • dry code more

Contribute

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add specs for it. This is important so we don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself we can ignore when we pull)
  • Send us a pull request. Bonus points for topic branches.

Credits

Datatrans is maintained by Simplificator GmbH (http://simplificator.com).

The initial development was sponsered by Evita AG and Limmex AG.

License

Datatrans is released under the MIT license.

More Repositories

1

sitincator

Simplificator's meeting room display system
JavaScript
55
star
2

rwebthumb

Ruby wrapper for webthumb.bluga.net
Ruby
47
star
3

simplificator-withings

a ruby implementation for the withing WIFI connected bodyscale
Ruby
47
star
4

inplace

Restful inplace plugin for Rails
Ruby
24
star
5

asset_pipeline_i18n

If you would like to internationalize your javascript/css files the same way you do in the rest of application... then this is for you.
Ruby
15
star
6

flatten_migrations

Flatten migrations into one
Ruby
12
star
7

babel

guessing language form texts (n-gram approach)
Ruby
9
star
8

compete

compete API for http://developer.compete.com/
Ruby
8
star
9

geoip

Lookup your IP
Ruby
6
star
10

keycloak_oauth

Ruby on Rails integration with the Keycloak identity and access management API.
Ruby
6
star
11

fsm

a simple finite state machine gem
Ruby
5
star
12

basecamp-next-scrum-calculator

Basecamp Next: SCRUM Calculator
JavaScript
4
star
13

ruby-kiva

a wrapper for the kiva.org api
Ruby
3
star
14

monitoring-dashboard

Monitoring Dashboard (Master Thesis by Helga & Marion)
Elixir
3
star
15

flogger

test/unit extension to flog
Ruby
3
star
16

ansible

Run ansible in a container
Dockerfile
3
star
17

tls-support

a tls support gem for older ruby versions. can be used to add tls support (i.g. GMail) to Active Record
Ruby
3
star
18

phonegap-helloworld

JavaScript
3
star
19

arext

Some ActiveRecord Extensions
Ruby
2
star
20

ansible-role-caddy

Ansible role to install Caddy and configure it as a reverse proxy.
Jinja
2
star
21

conversions

a simple gem with conversions from m to mm and m to m2. Just for testing gemcutter....
Ruby
2
star
22

mongomapper-tree

Ruby
2
star
23

caddy-reverse-proxy

Dockerfile
1
star
24

truesenses

implementing the http/https API for truesenes.com
Ruby
1
star
25

simplificator-filter

An attempt to generalize filtering of AR objects
Ruby
1
star
26

offside-rails

New kicker app in rails
Ruby
1
star
27

offside-node

New kicker app in node
LiveScript
1
star
28

station-board

Station Board
Ruby
1
star
29

cidisplay

Displaying messages from hudson on a LCD display
Ruby
1
star
30

cleanup_sessions

Cleanup sessions gem for rails 3
Ruby
1
star
31

kickstart-infra

Demo project for Infrastructure as Code using `terraform`
HCL
1
star
32

simplificator_infrastructure

Ruby
1
star
33

context_aware_scope

Ruby
1
star
34

isoelectric_point

A protein isoelectric point calculation class. Clone from GeorgeG to convert it to a gem.
Ruby
1
star
35

deploy-action

TypeScript
1
star