Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create new gateway connection Everyaction. #249

Open
wants to merge 1 commit into
base: waysact/master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
356 changes: 356 additions & 0 deletions lib/active_merchant/billing/gateways/everyaction.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,356 @@
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class EveryactionGateway < Gateway
self.test_url = 'https://api.securevan.com/v4'
self.live_url = 'https://api.securevan.com/v4'

# https://payments-api.securevan.com/v4/commitments/recurringPayments

self.supported_countries = ['US']
self.default_currency = 'USD'
self.supported_cardtypes = [:visa, :master, :american_express, :discover]

self.homepage_url = 'https://www.everyaction.com/'
self.display_name = 'Everyaction'

STANDARD_ERROR_CODE_MAPPING = {}

ACCOUNT_TYPES = {
"checking" => "PersonalChecking",
"savings" => "PersonalSavings",
}

def initialize(options={})
requires!(options, :api_key, :application_name)
requires!(options, :designation_id, :gateway_id)

super
end

def recurring(amount, payment, options = {})
post = {}
add_everyaction_options(post, amount, payment, options)
add_frequency_data(post, options)

post = post.reject { |_, v| v.blank? }

commit(:post, 'recurring', post, options)
end

# Creates a Contributions record in Everyaction.
#
# a Contributions is a record of a person’s monetary gift.
#
# They must be linked to both the contact that contributed, and the
# designation corresponding to the contribution.
#
def purchase(money, payment, options={})
post = {}
add_everyaction_options(post, money, payment, options)
add_purchase_options(post, options)

post = post.reject { |_, v| v.blank? }

commit(:post, 'purchase', post, options)
end

# Possible commitment updates
#
# Cancel a commitment
# Update the next transaction date
# Update the commitment amount
# Update the commitment end date
#
def update_contribution(options)
post = {}

post['status'] = options[:status]
post['nextTransactionDate'] = options[:next_transaction_date]
post['amount'] = options[:amount]
post['endDate'] = options[:end_date]

post = post.reject { |_, v| v.blank? }

commit(:patch, "/commitments/#{options[:commitment_id]}", post)
end

def find_contribution(post, options)
commit(:get, "/contributions/#{options['contibution_id']}")
end

# Finds or Creates a new person record and returns a full
# response where we can find the vanId that we need in further
# queries.
#
def find_or_create_person(options = {})
post = {}
add_person_data(post, options)

# Attempts to find the given match candidate.
# If a person is found, it is updated with the information provided.
# If a person is not found, a new person record is created.
response = commit(:post, '/people/findOrCreate', post)

if response.success?
find_person(response.params)
else
raise Error, response.error_code
end
end

# Retrieves a person record and associated contact information.
#
def find_person(options = {})
args_to_expands = {}
if options[:expand_options].present?
args_to_expands.update({
expand: options[:expand_options]
})
end
query_string_params = args_to_expands&.to_query.presence

base_endpoint = "/people/#{options['vanId']}"
endpoint = [base_endpoint, query_string_params].compact.join('?')

commit(:get, endpoint, nil)
end

def add_contact_data(post, options)
post['contact'] = {
'vanId' => options[:van_id]
}
end

def add_amount_options_data(post, amount, options)
post['amount'] = amount

if options[:general_ledger_fund_id].present?
post['generalLedgerFund'] = {
'GeneralLedgerFundId' => options[:general_ledger_fund_id]
}
end

if options[:cost_center_id].present?
post['costCenter'] = {
'costCenterId' => options[:cost_center_id]
}
end
end

def add_frequency_data(post, options)
# Weekly
# EveryTwoWeeks
# EveryFourWeeks
# Monthly
# TwiceMonthly
# Quarterly
# Annually
# TwiceAnnually
post['frequency'] = options[:frequency]

if options[:start_date].present?
post['startDate'] = options[:start_date]
end

if options[:end_date].present?
post['endData'] = options[:end_date]
end
end

def add_everyaction_options(post, amount, payment, options)
add_merchant_data(post, options)
add_contact_data(post, { van_id: options[:van_id] })
add_payment_data(post, payment, options)
add_amount_options_data(post, amount, options)
add_miscellaneous_data(post, options)
end

def add_purchase_options(post, options)
post['financialBatchId'] = options[:financial_batch_id]
end

def add_merchant_data(post, options)
post['gatewayId'] = options[:gateway_id].presence || @options[:gateway_id]
post['designation'] = {
'designationId' => options[:designation_id].presence || @options[:designation_id]
}
end

def add_miscellaneous_data(post, options)
post['directMarketingCode'] = options[:marketing_code]
post['notes'] = options[:notes]

if options[:extended_source_code].present?
post['extendedSourceCode'] = {
'extendedSourceCodeId' => options[:extended_source_code]
}
end
end

def add_payment_data(post, source, options)
post['paymentMethod'] = payment_method(post, source, options)

if options[:codes].present?
post['codes'] = options[:codes].map do |code|
{
'codeId' => code[:id],
'codeName' => code[:name]
}
end
end
end

def add_person_data(post, options)
post[:firstName] = options[:first_name]
post[:lastName] = options[:last_name]
post[:emails] = [{ email: options[:email] }]
end

def payment_method(post, source, options)
payment_hash = {}
if source.is_a?(CreditCard)
payment_hash['paymentType'] = 'CreditCard'
payment_hash['creditCardNumber'] = source.number
payment_hash["cvv"] = source.verification_value
payment_hash["expirationMonth"] = format(source.month, :two_digits)
payment_hash["expirationYear"] = format(source.year, :four_digits)

elsif source.is_a?(Check)
payment_hash['paymentType'] = 'ElectronicFundsTransfer'
if ACCOUNT_TYPES[source.account_type]
payment_hash['accountType'] = ACCOUNT_TYPES[source.account_type]
end
payment_hash['accountNumber'] = source.account_number
payment_hash['routingNumber'] = source.routing_number
end

payment_hash
end

def supports_scrubbing?
true
end

def scrub(transcript)
transcript.
gsub(%r((Authorization: Basic )\w+), '\1[FILTERED]').
gsub(/(creditCardNumber\\?":\\?")(\d*)/, '\1[FILTERED]').
gsub(/(cvv\\?":\\?")(\d*)/, '\1[FILTERED]')
end

private

def add_invoice(post, money, options)
post[:amount] = amount(money)
post[:currency] = (options[:currency] || currency(money))
end

def parse(body)
JSON.parse(body)
end

def headers(options)
hash = {
"Content-Type" => "application/json",
"accept" => "application/json",
"Authorization" => "Basic #{basic_auth}",
}

if options.key?(:unique_identifier)
hash["idempotency-Key"] = options[:unique_identifier]
end

hash
end

# database_mode means 0 to work in My Voters and 1 to work in My Campaign
#
# https://docs.everyaction.com/reference/authentication
# https://docs.everyaction.com/reference/data-model
#
def basic_auth
database_mode = @options[:database_mode] || '1'
Base64.strict_encode64(
"#{@options[:application_name]}:#{@options[:api_key]}|#{database_mode}"
)
end

def url(action)
case action
when 'recurring'
'https://payments-api.securevan.com/v4/commitments/recurringPayments'
when 'purchase'
'https://payments-api.securevan.com/v4/contributions/payments'
else
(test? ? test_url : live_url) + action
end
end

def commit(verb, action, parameters, options = {})
raw_response =
begin
parse(ssl_request(verb, url(action), post_data(action, parameters), headers(options)))
rescue ActiveMerchant::ResponseError => e
if e.response.code == '400'
JSON.parse(e.response.body)

# They respond with a 302 (redirect) and it means it was success!
else
JSON.parse(e.response.body)
end
end

response =
raw_response.is_a?(Integer) ? { authorization_id: raw_response } : raw_response

Response.new(
success_from(raw_response, action),
message_from(raw_response, action),
response,
authorization: authorization_from(raw_response, action),
test: test?,
error_code: error_code_from(raw_response, action)
)
end

def success_from(response, action)
# When we do a POST /contributions/payments the success response is
# only an Integer number, so we consider it as a success!
if action == 'purchase'
response.is_a?(Integer)
else
response.key?('vanId') || response.key?('commitmentId')
end
end

def message_from(response, action)
if success_from(response, action)
'Transaction approved'
else
'Transaction failed'
end
end

def authorization_from(response, action)
if action == 'purchase'
response
else
response['vanId'].presence || response['commitmentId']
end
end

def post_data(action, parameters)
return if parameters.nil?
parameters.to_json
end

def error_code_from(response, action)
unless success_from(response, action)
response['errors']
.map { |x| "#{x['code']}: #{x['text']}" }
.join(', ')
end
end
end
end
end
7 changes: 7 additions & 0 deletions test/fixtures.yml
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,13 @@ euplatesc:
merchant_id: MERCHANT_ID
key: KEY

everyaction:
application_name: APPLICATION_NAME
api_key: API_KEY
database_mode: 1
designation_id: DESIGNATION_ID
gateway_id: GATWAY_ID

evo_ca:
username: demo
password: password
Expand Down
Loading