Skip to content

Instantly share code, notes, and snippets.

@csexton
Created August 22, 2011 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csexton/1163030 to your computer and use it in GitHub Desktop.
Save csexton/1163030 to your computer and use it in GitHub Desktop.
Amazon Sample Code for Simple Payments
Originally from http://aws.amazon.com/code/Ruby/3007
################################################################################
# Copyright 2008-2010 Amazon Technologies, Inc
# Licensed under the Apache License, Version 2.0 (the "License");
#
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
################################################################################
require 'ButtonGenerator'
module Amazon
module FPS
class MarketplacePayButtonSample
@@accessKey = "<insert-access-key>"; #Put your Access Key here
@@secretKey = "<insert-secret-key>"; #Put your Secret Key here
@@amount="USD 1.1"; #Enter the amount you want to collect for the item
@@signatureMethod="HmacSHA256"; #Valid values are HmacSHA256 and HmacSHA1.
@@description="Test Widget"; #Enter a description of the item
@@referenceId="test-reference123"; #Optionally, enter an ID that uniquely identifies this transaction for your records
@@abandonUrl="http://yourwebsite.com/cancel.html"; #Optionally, enter the URL where senders should be redirected if they cancel their transaction
@@returnUrl="http://yourwebsite.com/return.html"; #Optionally enter the URL where buyers should be redirected after they complete the transaction
@@immediateReturn="0"; #Optionally, enter "1" if you want to skip the final status page in Amazon Payments
@@processImmediate="1"; #Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"
@@ipnUrl="http://yourwebsite.com/ipn"; #Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.
@@collectShippingAddress=nil; #Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information
@@recipientEmail = "new_ngo@amazon.com"; #Enter the e-mail address for the seller
@@fixedMarketplaceFee ="0.01"; #Optionally, enter the fixed market place fee
@@variableMarketplaceFee = "4" ; #Optionally, enter the variable market place fee
@@environment="sandbox"; #Valid values are "sandbox" or "prod"
def self.sample_form()
Amazon::FPS::ButtonGenerator.generate_marketplace_pay_button_form( @@accessKey, @@secretKey, @@amount, @@description, @@referenceId, @@immediateReturn,@@returnUrl, @@abandonUrl, @@processImmediate, @@ipnUrl,@@collectShippingAddress, @@signatureMethod,@@recipientEmail,@@fixedMarketplaceFee, @@variableMarketplaceFee, @@environment)
rescue Exception => msg
puts msg
end
end
end
end
Amazon::FPS::MarketplacePayButtonSample.sample_form()
Apache License
Version 2.0, January 2004
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
2. You must cause any modified files to carry prominent notices stating that You changed the files; and
3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
################################################################################
# Copyright 2008-2010 Amazon Technologies, Inc
# Licensed under the Apache License, Version 2.0 (the "License");
#
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
################################################################################
require 'uri'
require 'SignatureUtils'
module Amazon
module FPS
class ButtonGenerator
@@app_name = "ASP"
@@ASPhttp_method = "POST"
@@CBUIhttp_method = "POST"
@@CBUI_REQUEST_URI = "/cobranded-ui/actions/start";
@@SANDBOX_END_POINT = "https://authorize.payments-sandbox.amazon.com/pba/paypipeline";
@@SANDBOX_IMAGE_LOCATION="https://authorize.payments-sandbox.amazon.com/pba/images/payNowButton.png";
@@SANDBOX_MP_IMAGE_LOCATION = "https://authorize.payments-sandbox.amazon.com/pba/images/MarketPlaceFeeWithLogo.png";
@@PROD_END_POINT = "https://authorize.payments.amazon.com/pba/paypipeline";
@@PROD_IMAGE_LOCATION="https://authorize.payments.amazon.com/pba/images/payNowButton.png";
@@PROD_MP_IMAGE_LOCATION = "https://authorize.payments.amazon.com/pba/images/MarketPlaceFeeWithLogo.png";
SIGNATURE_KEYNAME = "signature"
SIGNATURE_METHOD_KEYNAME = "signatureMethod"
SIGNATURE_VERSION_KEYNAME = "signatureVersion"
SIGNATURE_VERSION = "2"
COBRANDING_STYLE = "logo"
HMAC_SHA256_ALGORITHM = "HmacSHA256"
HMAC_SHA1_ALGORITHM = "HmacSHA1"
# Function creates a Map of key-value pairs for all valid values passed to the function
# @param accessKey - Put your Access Key here
# @param amount - Enter the amount you want to collect for the item
# @param description - description - Enter a description of the item
# @param referenceId - Optionally enter an ID that uniquely identifies this transaction for your records
# @param abandonUrl - Optionally, enter the URL where senders should be redirected if they cancel their transaction
# @param returnUrl - Optionally enter the URL where buyers should be redirected after they complete the transaction
# @param immediateReturn - Optionally, enter "1" if you want to skip the final status page in Amazon Payments,
# @param processImmediate - Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"
# @param ipnUrl - Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.
# @param collectShippingAddress - Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information.
# @param signatureMethod - Valid values are HmacSHA256 and HmacSHA1
# @param recipientEmail - Enter the e-mail address for the seller.
# @param fixedMarketplaceFee - Optionally, enter the fixed market place fee
# @param variableMarketplaceFee - Optionally, enter the variable market place fee
# @return - A map of key of key-value pair for all non null parameters
def self.get_marketplace_pay_button_params(access_key,amount, description, reference_id, immediate_return,
return_url, abandon_url, process_immediate, ipn_url, collectShippingAddress,
signatureMethod,recipientEmail, fixedMarketplaceFee,variableMarketplaceFee)
form_hidden_inputs = {}
if (access_key== nil) then
raise ArgumentError, 'AccessKey is required parameter'
else
form_hidden_inputs["accessKey"] = access_key
end
if (amount == nil) then
raise ArgumentError, 'Amount is required parameter'
else
form_hidden_inputs["amount"] = amount
end
if (description == nil) then
raise ArgumentError, 'Description is required parameter'
else
form_hidden_inputs["description"] = description
end
if (signatureMethod == nil) then
raise ArgumentError, 'Signature Method is required parameter'
else
form_hidden_inputs[SIGNATURE_METHOD_KEYNAME] = signatureMethod
end
if ( recipientEmail == nil) then
raise ArgumentError, 'Recipient Email is required parameter'
else
form_hidden_inputs["recipientEmail"] = recipientEmail
end
form_hidden_inputs["referenceId"] = reference_id unless reference_id.nil?
form_hidden_inputs["immediateReturn"] = immediate_return unless immediate_return.nil?
form_hidden_inputs["returnUrl"] = return_url unless return_url.nil?
form_hidden_inputs["abandonUrl"] = abandon_url unless abandon_url.nil?
form_hidden_inputs["processImmediate"] = process_immediate unless process_immediate.nil?
form_hidden_inputs["ipnUrl"] = ipn_url unless ipn_url.nil?
form_hidden_inputs["collectShippingAddress"] = collectShippingAddress unless collectShippingAddress.nil?
form_hidden_inputs["fixedMarketplaceFee"] = fixedMarketplaceFee unless fixedMarketplaceFee.nil?
form_hidden_inputs["variableMarketplaceFee"] = variableMarketplaceFee unless variableMarketplaceFee.nil?
form_hidden_inputs["cobrandingStyle"] = COBRANDING_STYLE
form_hidden_inputs[SIGNATURE_VERSION_KEYNAME] = SIGNATURE_VERSION
return form_hidden_inputs
end
# Creates a form from the provided key-value pairs
# @param form_hidden_inputs
# - A map of key of key-value pair for all non null parameters
# @param service_end_point
# - The Endpoint to be used based on environment selected
# @param image_location
# - The imagelocation based on environment
# @return - An html form created using the key-value pairs
def self.get_marketplace_pay_button_form(form_hidden_inputs,service_end_point,image_location)
form = "<form action=\"" + service_end_point + "\" method=\"" + @@ASPhttp_method + "\">\n"
form += "<input type=\"image\" src=\""+image_location+"\" border=\"0\">\n"
form_hidden_inputs.each { |k,v|
form += "<input type=\"hidden\" name=\"" + k + "\" value=\"" + v + "\" >\n"
}
form += "</form>\n"
end
# @param accessKey - Put your Access Key here
# @param secretKey - Put your Secret Key here
# @param amount - Enter the amount you want to collect for the item
# @param description - description - Enter a description of the item
# @param referenceId - Optionally enter an ID that uniquely identifies this transaction for your records
# @param abandonUrl - Optionally, enter the URL where senders should be redirected if they cancel their transaction
# @param returnUrl - Optionally enter the URL where buyers should be redirected after they complete the transaction
# @param immediateReturn - Optionally, enter "1" if you want to skip the final status page in Amazon Payments,
# @param processImmediate - Optionally, enter "1" if you want to settle the transaction immediately else "0". Default value is "1"
# @param ipnUrl - Optionally, type the URL of your host page to which Amazon Payments should send the IPN transaction information.
# @param collectShippingAddress - Optionally, enter "1" if you want Amazon Payments to return the buyer's shipping address as part of the transaction information.
# @param signatureMethod - Valid values are HmacSHA256 and HmacSHA1
# @param recipientEmail - Enter the e-mail address for the seller.
# @param fixedMarketplaceFee - Optionally, enter the fixed market place fee
# @param variableMarketplaceFee - Optionally, enter the variable market place fee
# @param environment - Valid values are "sandbox" or "prod"
def self.generate_marketplace_pay_button_form(accessKey, secretKey, amount, description, referenceId, immediateReturn,returnUrl, abandonUrl, processImmediate, ipnUrl,collectShippingAddress, signatureMethod,recipientEmail, fixedMarketplaceFee,variableMarketplaceFee, environment)
if (environment == "prod") then
endPoint = @@PROD_END_POINT;
imageLocation = @@PROD_IMAGE_LOCATION;
else
endPoint = @@SANDBOX_END_POINT;
imageLocation = @@SANDBOX_IMAGE_LOCATION;
end
uri = URI.parse(endPoint)
params = Amazon::FPS::ButtonGenerator.get_marketplace_pay_button_params(accessKey, amount, description, referenceId, immediateReturn,returnUrl, abandonUrl, processImmediate, ipnUrl,collectShippingAddress, signatureMethod,recipientEmail, fixedMarketplaceFee,variableMarketplaceFee)
signature = Amazon::FPS::SignatureUtils.sign_parameters({:parameters => params,
:aws_secret_key => secretKey,
:host => uri.host,
:verb => @@ASPhttp_method,
:uri => uri.path,
:algorithm => signatureMethod })
params[SIGNATURE_KEYNAME] = signature
marketplace_pay_button_form = get_marketplace_pay_button_form(params,endPoint,imageLocation)
print marketplace_pay_button_form
end
# Function creates a Map of key-value pairs for all valid values passed to the function
# @param accessKey - Put your Access Key here
# @param returnUrl - Enter the URL where recipient should be redirected after they accept the Marketplace Fee
# @param signatureMethod - Valid values are HmacSHA256 and HmacSHA1
# @param callerReference -Optionally, enter an ID that uniquely identifies this transaction for callers Record
# @param fixedMarketplaceFee - Optionally, enter the fixed market place fee
# @param variableMarketplaceFee - Optionally, enter the variable market place fee
# @return - A map of key of key-value pair for all non null parameters
def self.get_accept_marketplace_fee_button_params(access_key,return_url,signatureMethod,callerReference, fixedMarketplaceFee,variableMarketplaceFee)
form_hidden_inputs = {}
if (access_key== nil) then
raise ArgumentError, 'AccessKey is required parameter'
else
form_hidden_inputs["callerKey"] = access_key
end
if (signatureMethod == nil) then
raise ArgumentError, 'Signature Method is required parameter'
else
form_hidden_inputs[SIGNATURE_METHOD_KEYNAME] = signatureMethod
end
if (return_url == nil) then
raise ArgumentError, 'Return_url is required parameter'
else
form_hidden_inputs["returnUrl"] = return_url
end
form_hidden_inputs["pipelineName"] = "Recipient"
form_hidden_inputs["recipientPaysFee"] = "True"
form_hidden_inputs["collectEmailAddress"] = "True"
if (callerReference == nil) then
value=""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
callerReference = value
end
form_hidden_inputs["callerReference"] = callerReference
form_hidden_inputs["maxFixedFee"] = fixedMarketplaceFee unless fixedMarketplaceFee.nil?
form_hidden_inputs["maxvariableFee"] = variableMarketplaceFee unless variableMarketplaceFee.nil?
form_hidden_inputs["cobrandingStyle"] = COBRANDING_STYLE
form_hidden_inputs[SIGNATURE_VERSION_KEYNAME] = SIGNATURE_VERSION
return form_hidden_inputs
end
# Creates a form from the provided key-value pairs
# @param form_hidden_inputs
# - A map of key of key-value pair for all non null parameters
# @param service_end_point
# - The Endpoint to be used based on environment selected
# @param image_location
# - The imagelocation based on environment
# @return - An html form created using the key-value pairs
def self.get_accept_marketplace_fee_button_form(form_hidden_inputs,service_end_point,image_location,path)
form = "<form action=\"https://" + service_end_point + path + "\" method=\"" + @@CBUIhttp_method + "\">\n"
form += "<input type=\"image\" src=\""+image_location+"\" border=\"0\">\n"
form_hidden_inputs.each { |k,v|
form += "<input type=\"hidden\" name=\"" + k + "\" value=\"" + v + "\" >\n"
}
form += "</form>\n"
end
# @param accessKey - Put your Access Key here
# @param secretKey - Put your Secret Key here
# @param returnUrl - Enter the URL where recipient should be redirected after they accept the Marketplace Fee
# @param callerReference -Optionally, enter an ID that uniquely identifies this transaction for callers Record
# @param signatureMethod - Valid values are HmacSHA256 and HmacSHA1
# @param fixedMarketplaceFee - Optionally, enter the fixed market place fee
# @param variableMarketplaceFee - Optionally, enter the variable market place fee
# @param environment - Valid values are "sandbox" or "prod"
def self.generate_accept_marketplace_fee_button_form(accessKey, secretKey,returnUrl,signatureMethod,callerReference, fixedMarketplaceFee,variableMarketplaceFee, environment)
if (environment == "prod") then
endPoint = @@PROD_END_POINT;
imageLocation = @@PROD_MP_IMAGE_LOCATION;
else
endPoint = @@SANDBOX_END_POINT;
imageLocation = @@SANDBOX_MP_IMAGE_LOCATION;
end
uri = URI.parse(endPoint)
params = Amazon::FPS::ButtonGenerator.get_accept_marketplace_fee_button_params(accessKey,returnUrl,signatureMethod,callerReference, fixedMarketplaceFee,variableMarketplaceFee)
signature = Amazon::FPS::SignatureUtils.sign_parameters({:parameters => params,
:aws_secret_key => secretKey,
:host => uri.host,
:verb => @@CBUIhttp_method,
:uri => @@CBUI_REQUEST_URI,
:algorithm => signatureMethod })
params[SIGNATURE_KEYNAME] = signature
accept_marketplace_fee_button_form = get_accept_marketplace_fee_button_form(params,uri.host,imageLocation,@@CBUI_REQUEST_URI)
print accept_marketplace_fee_button_form
end
end
end
end
Amazon FPS Ruby Library
Copyright 2008-2010 Amazon Technologies, Inc
This product includes software developed by
Amazon Technologies, Inc (http://www.amazon.com/).
################################################################################
# Copyright 2008-2010 Amazon Technologies, Inc
# Licensed under the Apache License, Version 2.0 (the "License");
#
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
################################################################################
require 'base64'
require 'cgi'
require 'openssl'
module Amazon
module FPS
#
# Copyright:: Copyright (c) 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# RFC 2104-compliant HMAC signature for request parameters
# Implements AWS Signature, as per following spec:
#
# In Signature Version 2, string to sign is based on following:
#
# 1. The HTTP Request Method followed by an ASCII newline (%0A)
# 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline.
# 3. The URL encoded HTTP absolute path component of the URI
# (up to but not including the query string parameters);
# if this is empty use a forward '/'. This parameter is followed by an ASCII newline.
# 4. The concatenation of all query string components (names and values)
# as UTF-8 characters which are URL encoded as per RFC 3986
# (hex characters MUST be uppercase), sorted using lexicographic byte ordering.
# Parameter names are separated from their values by the '=' character
# (ASCII character 61), even if the value is empty.
# Pairs of parameter and values are separated by the '&' character (ASCII code 38).
#
class SignatureUtils
SIGNATURE_KEYNAME = "signature"
HMAC_SHA256_ALGORITHM = "HmacSHA256"
HMAC_SHA1_ALGORITHM = "HmacSHA1"
def self.sign_parameters(args)
string_to_sign = "";
string_to_sign = calculate_string_to_sign_v2(args)
return compute_signature(string_to_sign, args[:aws_secret_key],get_algorithm(args[:algorithm]))
end
# Convert a string into URL encoded form.
def self.urlencode(plaintext)
CGI.escape(plaintext.to_s).gsub("+", "%20").gsub("%7E", "~")
end
private # All the methods below are private
def self.calculate_string_to_sign_v2(args)
parameters = args[:parameters]
uri = args[:uri]
uri = "/" if uri.nil? or uri.empty?
uri = urlencode(uri).gsub("%2F", "/")
verb = args[:verb]
host = args[:host].downcase
# exclude any existing Signature parameter from the canonical string
sorted = (parameters.reject { |k, v| k == SIGNATURE_KEYNAME }).sort
canonical = "#{verb}\n#{host}\n#{uri}\n"
isFirst = true
sorted.each { |v|
if(isFirst) then
isFirst = false
else
canonical << '&'
end
canonical << urlencode(v[0])
unless(v[1].nil?) then
canonical << '='
canonical << urlencode(v[1])
end
}
return canonical
end
def self.get_algorithm(signature_method)
return 'sha256' if (signature_method == HMAC_SHA256_ALGORITHM);
return 'sha1'
end
def self.compute_signature(canonical, aws_secret_key, algorithm = 'sha1')
digest = OpenSSL::Digest::Digest.new(algorithm)
return Base64.encode64(OpenSSL::HMAC.digest(digest, aws_secret_key, canonical)).chomp
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment