Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Created May 3, 2012 20:59
Show Gist options
  • Select an option

  • Save t2-support-gists/2589446 to your computer and use it in GitHub Desktop.

Select an option

Save t2-support-gists/2589446 to your computer and use it in GitHub Desktop.
Payment Ruby app1
AT&T API Samples - Payment app 1
----------------------------------
This file describes how to set up, configure and run the ruby versions of the AT&T HTML5 Program sample applications.
It covers all steps required to register the application on DevConnect and, based on the generated API keys and secrets,
create and run one's own full-fledged sample applications.
1. Configuration
2. Installation
3. Parameters
4. Running the application
1. Configuration
Configuration consists of a few steps necessary to get an application registered on DevConnect with the proper services and
endpoints, depending on the type of client-side application (autonomous/non-autonomous).
To register an application, go to https://devconnect-api.att.com/ and login with your valid username and password.
Next, choose "My Page" from the bar at the top of the page and click the "Setup a New Application" button.
Fill in the form, in particular all fields marked as "required".
Be careful while filling in the "OAuth Redirect URL" field. It should contain the URL that the oAuth provider will redirect
users to when he/she successfully authenticates and authorizes your application.
Having your application registered, you will get back an important pair of data: an API key and Secret key. They are
necessary to get your applications working with the AT&T HTML5 APIs. See 'Adjusting parameters' below to learn how to use
these keys.
Initially your newly registered application is restricted to the "Sandbox" environment only. To move it to production,
you may promote it by clicking the "Promote to production" button. Notice that you will get a different API key and secret,
so these values in your application should be adjusted accordingly.
Depending on the kind of authentication used, an application may be based on either the Autonomous Client or the Web-Server
Client OAuth flow (see https://devconnect-api.att.com/docs/oauth20/autonomous-client-application-oauth-flow or
https://devconnect-api.att.com/docs/oauth20/web-server-client-application-oauth-flow respectively).
2. Installation
** Requirements
To run the examples you need ruby 1.8+ and a few gems that the applications are heavily based on:
- sinatra (http://www.sinatrarb.com/)
used to construct a simple web application and manage URLs within.
- sinatra-contrib
additional set of useful helpers, including ones used to read settings from external files.
- also make sure you have rest-client and json gems installed
To install these gems open up a terminal window and invoke:
gem install sinatra sinatra-contrib rest-client json
Having them installed, you are almost ready to run the sample applications.
** Setting up on a different port number
In case multiple applications need to be run at the same time, you need to consider using different
port numbers.
By default sinatra uses port number 4567 and only one running application may use this port. In case
you want to run one more sinatra-based application, you need to change its port number, eg. to 4568. This way you
may have each application running on a unique port.
3. Parameters
Each application contains a config.yml file. It holds configurable parameters
described in an easy to read YAML format which you are free to adjust to your needs. Following are short descriptions
of parameters used by this application:
1) FQDN : https://api.att.com
2) port : port number that application binds to (default: 4567)
3) api_key : set the value as per your registered appliaction 'API key' field value
4) secret_key : set the value as per your registered appliaction 'Secret key' field value
5) tokens_file : file in which OAuth tokens are stored
4. Running the application
To run the application, first make sure you have Notary up and running. From Notary/Ruby/app1
directory, type in terminal window:
ruby ./notary.rb
Next, change directory back to the payment application and run it:
ruby ./app1.rb
or
./app1.rb
Your application becomes available in a web browser, so you may visit: http://localhost:4567/ to see it working.
You may interrupt the application at any time by pressing ctrl-C.
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'uri'
require 'rest_client'
require 'base64'
require 'sinatra'
require 'sinatra/config_file'
require File.join(File.dirname(__FILE__), 'common.rb')
enable :sessions
config_file 'config.yml'
set :port, settings.port
Scope = 'PAYMENT'
def read_recent_transactions
@transactions = Array.new
File.open settings.transactions_file, 'r' do |f|
while (line = f.gets)
a = line.split
t = Hash.new
t[:merchant_transaction_id] = a[0]
t[:transaction_auth_code] = a[1]
t[:transaction_id] = a[2]
@transactions.push t
end
end
@transactions = @transactions.drop(@transactions.length - settings.recent_transactions_stored) if @transactions.length > settings.recent_transactions_stored
rescue
return
end
def write_recent_transactions
File.open settings.transactions_file, 'w+' do |f|
@transactions.each do |t|
f.puts t[:merchant_transaction_id] + ' ' + t[:transaction_auth_code] + (t[:transaction_id] ? ' ' + t[:transaction_id] : '')
end
end
end
def new_transaction
session[:merchant_transaction_id] = 'User' + sprintf('%03d', rand(1000)) + 'Transaction' + sprintf('%04d', rand(10000))
# prepare payload
data = {
:Amount => params[:product] == "1" ? 0.99 : 2.99,
:Category => 1,
:Channel => 'MOBILE_WEB',
:Description => 'Word game 1',
:MerchantTransactionId => session[:merchant_transaction_id],
:MerchantProductId => 'wordGame1',
:MerchantApplicationId => 'wordGames',
:MerchantPaymentRedirectUrl => settings.payment_redirect_url
}
response = RestClient.post settings.notary_app_sign_url, :payload => data.to_json
from_json = JSON.parse response
u = settings.FQDN + "/Commerce/Payment/Rest/2/Transactions?clientid=" + settings.api_key + "&SignedPaymentDetail=" + from_json['signed_payload'] + "&Signature=" + from_json['signature']
redirect u
end
def return_transaction
@new_transaction = Hash.new
@new_transaction[:merchant_transaction_id] = session[:merchant_transaction_id]
@new_transaction[:transaction_auth_code] = params['TransactionAuthCode']
@transactions.push @new_transaction
@transactions.delete_at 0 if @transactions.length > settings.recent_transactions_stored
write_recent_transactions
ensure
return erb :app1
end
def get_transaction_status
if params['getTransactionType'] == '1'
u = settings.FQDN + "/Commerce/Payment/Rest/2/Transactions/MerchantTransactionId/" + @transactions.last[:merchant_transaction_id] + "?access_token=" + @access_token
elsif params['getTransactionType'] == '2'
u = settings.FQDN + "/Commerce/Payment/Rest/2/Transactions/TransactionAuthCode/" + @transactions.last[:transaction_auth_code] + "?access_token=" + @access_token
elsif params['getTransactionType'] == '3'
u = settings.FQDN + "/Commerce/Payment/Rest/2/Transactions/TransactionId/" + @transactions.last[:transaction_id] + "?access_token=" + @access_token
end
RestClient.get u do |response, request, code, &block|
@r = response
end
if @r.code == 200
@transaction_status = @transactions.last
@transaction_status[:status] = JSON.parse @r
@transactions.last[:transaction_id] = @transaction_status[:status]['TransactionId']
write_recent_transactions
else
@transaction_status_error = @r
end
erb :app1
end
def refund_transaction
if params['trxId'].nil? || params['trxId'].empty?
redirect '/'
end
u = settings.FQDN + "/Commerce/Payment/Rest/2/Transactions/" + params['trxId'] + "?access_token=" + @access_token + "&Action=refund"
payload = Hash.new
payload['RefundReasonCode'] = 1
payload['RefundReasonText'] = 'User did not like product'
RestClient.put u, payload.to_json, :content_type => 'application/json', :accept => 'application/json' do |response, request, code, &block|
@r = response
end
if @r.code == 200
@refund = Hash.new
@refund[:transaction_id] = params['trxId']
else
@refund_error = @r
end
erb :app1
end
#def refresh_notifications
# # make the API call
#
#ensure
# return erb :app1
#end
['/','/newTransaction','/getTransactionStatus','/refundTransaction', '/refreshNotifications', '/returnTransaction'].each do |path|
before path do
read_recent_transactions
obtain_tokens(settings.FQDN, settings.api_key, settings.secret_key, Scope, settings.tokens_file)
end
end
get '/' do
erb :app1
end
get '/returnTransaction' do
return_transaction
end
post '/newTransaction' do
new_transaction
end
post '/getTransactionStatus' do
# validate parameters
get_transaction_status
end
post '/refundTransaction' do
# validate parameters
refund_transaction
end
post '/refreshNotifications' do
# validate parameters
refresh_notifications
end
# Tries to parse supplied address using one of known formats. Returns false on failure.
def parse_address(address)
address.strip!
if (address.match('^\d{10}$'))
elsif (m = address.match('^1(\d{10})$'))
address = m[1].to_s
elsif (m = address.match('^\+1(\d{10})$'))
address = m[1].to_s
elsif (m = address.match('^tel:(\d{10})$'))
address = m[1].to_s
elsif (address.match('^\d{3}-\d{3}-\d{4}$'))
address.gsub! '-', ''
else
return false
end
address
end
# Makes sure that valid access_token is stored in the session. Retrieves new tokens if needed.
def obtain_tokens(fqdn, client_id, client_secret, scope, tokens_file)
read_tokens(tokens_file)
if @access_token and @access_token_expires > Time.now
return
elsif @refresh_token and @refresh_token_expires > Time.now
response = RestClient.post "#{fqdn}/oauth/token", :grant_type => 'refresh_token', :client_id => client_id, :client_secret => client_secret, :refresh_token => @refresh_token
else
response = RestClient.post "#{fqdn}/oauth/token", :grant_type => 'client_credentials', :client_id => client_id, :client_secret => client_secret, :scope => scope
end
from_json = JSON.parse(response.to_str)
@access_token = from_json['access_token']
@refresh_token = from_json['refresh_token']
@access_token_expires = Time.now + (from_json['expires_in'].to_i)/1000
@refresh_token_expires = Time.now + (60*60*24)
write_tokens(tokens_file)
end
def write_tokens(tokens_file)
File.open(tokens_file, 'w+') { |f| f.puts @access_token, @access_token_expires, @refresh_token, @refresh_token_expires }
end
def read_tokens(tokens_file)
@access_token, access_expiration, @refresh_token, refresh_expiration = File.foreach(tokens_file).first(4).map! &:strip!
@access_token_expires = Time.parse access_expiration
@refresh_token_expires = Time.parse refresh_expiration
rescue
return
end
port: 4567
api_key:
secret_key:
tokens_file: tokens
transactions_file: transactions
recent_transactions_stored: 5
notary_app_sign_url: http://localhost:4568/signPayload
notary_app_view_payload_url: http://localhost:4568/
payment_redirect_url: http://localhost:4567/returnTransaction
FQDN: https://api.att.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment