helloworld.rb - How to run Ruby Sample Code using the Hello World API and X-Pay-Token

shameem
Visa Employee

helloworld.rb - How to run Ruby Sample Code using the Hello World API and X-Pay-Token

In this "How-to" guide we will show you how to run the “Hello World” project using Visa Hello World API and and API Key - Shared Secret Authentication. The Hello World API is a simple API for testing the connectivity with the Visa Network.

 

Important Links:

 

 

How to Create a Visa Developer Project

 

Before you are able to run the “Hello World” Project, you must create a Visa Developer Portal (VDP) project and get credentials. If you haven't registered yet just click on register here, fill out the account information, agree to the terms and conditions and click on receive emails. Once you have successfully activated your account, you will see your dashboard and you are ready to go.

 

 

java1.png

 

 

Once you are there, click on create your first project if this is your first project.  On the next page, you will be asked for details, such as project name, description and a list of APIs to choose from.

 

 

Java2.png

 

For this tutorial, we're going to select CyberSource Payments and click create project.

 

 

CyberSourcePaymentMethod.png

 

 

 

How to get Credentials

 

After creating your project, you will be redirected to the project summary page. You can obtain your project credentials by browsing the left side navigation menu of your project and click on “Credentials”.

 

 

Java4.png

 

What is required for the X-Pay-Token Authentication?

 

To be able to make an API call with X-Pay-Token Authentication, you need to have the following:

  1. Api Key
  2. Secret Key

CredentialsForXPayToken.png

 

How to run the Ruby Sample code of the “Hello World API” using RubyMine

 

 

Next, we'll show you how to run the Ruby sample code of the “Hello World API” using RubyMine. RubyMine is an integrated development environment (IDE) that helps you be more productive in every aspect of Ruby/Rails projects development. and can be downloaded using below link:

 

https://www.jetbrains.com/ruby/download

 

In RubyMine, a project helps you organize your source code, tests, libraries that you use, build instructions, and your personal settings in a single unit.

 

 

Step 1 - Launch RubyMine

 

  • On the RubyMine Welcome Screen, click Create New Project.

2020-11-16_13-44-16.png

 

 

 

Otherwise, from the main menu, select File | New | Project

 

Step 2 - In the New Project wizard, select Ruby Empty Project from the list on the left, provide the project Location and click Create.

 

Please make sure to specify your “Ruby SDK”

 

 

2020-11-16_13-49-23.png

 

 

Step 3 - Create a new Ruby file and named it “helloworld

 

2020-11-16_13-50-21.png

 

 

Step 4 - Copy the below sample code to the “helloworld.rb” file

 

  • Set the below parameters:

@api_key = '<YOUR API KEY>'

@shared_secret = '<YOUR SHARED SECRET KEY>'

 

 

 

# *(c) Copyright 2018 - 2020 Visa. All Rights Reserved.**
#
# *NOTICE: The software and accompanying information and documentation (together, the “Software”) remain the property of and are proprietary to Visa and its suppliers and affiliates. The Software remains protected by intellectual property rights and may be covered by U.S. and foreign patents or patent applications. The Software is licensed and not sold.*
#
# * By accessing the Software you are agreeing to Visa's terms of use (developer.visa.com/terms) and privacy policy (developer.visa.com/privacy).In addition, all permissible uses of the Software must be in support of Visa products, programs and services provided through the Visa Developer Program (VDP) platform only (developer.visa.com). **THE SOFTWARE AND ANY ASSOCIATED INFORMATION OR DOCUMENTATION IS PROVIDED ON AN “AS IS,” “AS AVAILABLE,” “WITH ALL FAULTS” BASIS WITHOUT WARRANTY OR  CONDITION OF ANY KIND. YOUR USE IS AT YOUR OWN RISK.** All brand names are the property of their respective owners, used for identification purposes only, and do not imply product endorsement or affiliation with Visa. Any links to third party sites are for your information only and equally  do not constitute a Visa endorsement. Visa has no insight into and control over third party content and code and disclaims all liability for any such components, including continued availability and functionality. Benefits depend on implementation details and business factors and coding steps shown are exemplary only and do not reflect all necessary elements for the described capabilities. Capabilities and features are subject to Visa’s terms and conditions and may require development,implementation and resources by you based on your business and operational details. Please refer to the specific API documentation for details on the requirements, eligibility and geographic availability.*
#
# *This Software includes programs, concepts and details under continuing development by Visa. Any Visa features,functionality, implementation, branding, and schedules may be amended, updated or canceled at Visa’s discretion.The timing of widespread availability of programs and functionality is also subject to a number of factors outside Visa’s control,including but not limited to deployment of necessary infrastructure by issuers, acquirers, merchants and mobile device manufacturers.*
#
require 'rest-client'
require 'yaml'
require 'sysrandom'
require 'json'

@visa_url = 'https://sandbox.api.visa.com/'

# THIS IS EXAMPLE ONLY how will apiKey and password look like
# apiKey = "1WM2TT4IHPXC8DQ5I3CH21n1rEBGK-Eyv_oLdzE2VZpDqRn_U";
# sharedSecret = "19JRVdej9";

@api_key = '<YOUR API KEY>'
@shared_secret = '<YOUR SHARED SECRET KEY>'

def logRequest(test_info, url, request_body)
  puts test_info
  puts "URL : #{url}"
  if (request_body != nil && request_body != '')
    puts "Request Body : "
    puts request_body
  end
end

def logResponse(response)
  puts "Response Status : #{response.code.to_s}"
  puts "Response Headers : "
  for header, value in response.headers
    puts "#{header.to_s} : #{value.to_s}"
  end
  puts "Response Body : " + JSON.pretty_generate(JSON.parse(response.body))
end

def get_xpay_token(resource_path, query_string, request_body)
  timestamp = Time.now.utc.to_i
  hash_input = "#{timestamp}#{resource_path}#{query_string}#{request_body}"
  hash_output = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @shared_secret, hash_input)
  "xv2:#{timestamp}:#{hash_output}"
end

def doXPayTokenRequest(base_uri, resource_path, query_string, test_info, method_type, request_body, headers = {})
  url = "#{@visa_url}#{base_uri}#{resource_path}?#{query_string}"
  logRequest(test_info, url, request_body)
  xpay_token = get_xpay_token(resource_path, query_string, request_body)
  if method_type == 'post' || method_type == 'put'
    headers['Content-type'] = 'application/json'
  end
  headers['accept'] = 'application/json'
  headers['x-pay-token'] = xpay_token
  begin
    response = RestClient::Request.execute(
        :method => method_type,
        :url => url,
        :headers => headers,
        :payload => request_body
    )
    logResponse(response)
    return response.code.to_s
  rescue RestClient::ExceptionWithResponse => e
    logResponse(e.response)
    return e.response.code.to_s
  end
end

base_uri = 'vdp/'
resource_path = 'helloworld'
query_string = 'apiKey=' + @api_key
response_code = doXPayTokenRequest("#{base_uri}", "#{resource_path}", query_string, "Hellow World Test", "get", "")
fail 'Hello world test failed' if "200" != response_code

 

 

 

Step 5 - Compile Your Code 

 

  • Simply right click and run “helloworld”

2020-11-16_13-50-42.png

 

 

Want more? Join the Visa Developer Community to get alerts on the latest tutorials, guides and new developer resources. Stay tuned for more in the series. 

 

Written by: @shameem@jmedlen, & @mprsic