Skip to content

Instantly share code, notes, and snippets.

@oyeb
Last active January 12, 2018 20:17
Show Gist options
  • Save oyeb/6b3ea6954fc7779c1a326362544ee949 to your computer and use it in GitHub Desktop.
Save oyeb/6b3ea6954fc7779c1a326362544ee949 to your computer and use it in GitHub Desktop.
Utility functions for GlobalCollect
# This is a module attribute, keep it after the `@moduledoc`
# This maps thecard brand to a GlobalCollect specific code
@brand_map %{
"VISA": "1",
"AMERICANEXPRESS": "2",
"MASTER": "3",
"DISCOVER": "128",
"JCB": "125",
"DINERSCLUB": "132"
}
# Take the declaration and body of `commit` from here
defp commit(method, path, params, opts) do
headers = create_headers()
data = Poison.encode!(params)
url = "#{@base_url}#{path}"
response = HTTPoison.request(method, url, data, headers)
end
defp create_headers(path) do
time = date()
sha_signature = auth_digest(path, @secret_api_key, time) |> Base.encode64
auth_token = "GCS v1HMAC:#{@api_key_id}:#{sha_signature}"
headers = [{"Content-Type", "application/json"}, {"Authorization", auth_token}, {"Date", time}]
end
defp add_order(money, options) do
%{
amountOfMoney: add_money(money, options),
customer: add_customer(options),
references: add_references(options)
}
end
defp add_money(amount, options) do
%{
amount: amount,
currencyCode: options[:currency]
}
end
defp add_customer(options) do
%{
merchantCustomerId: options[:merchantCustomerId],
personalInformation: personal_info(options),
dateOfBirth: options[:doB],
companyInformation: company_info(options),
billingAddress: options[:billingAddress],
shippingAddress: options[:shippingAddress],
contactDetails: contact(options)
}
end
defp add_references(options) do
%{
descriptor: options[:description],
invoiceData: options[:invoice]
}
end
defp personal_info(options) do
%{
name: options[:name]
}
end
defp company_info(options) do
%{
name: options[:company]
}
end
defp contact(options) do
%{
emailAddress: options[:email],
phoneNumber: options[:phone]
}
end
def add_card(%CreditCard{} = payment) do
%{
cvv: payment.verification_code,
cardNumber: payment.number,
expiryDate: "#{payment.month}"<>"#{payment.year}",
cardholderName: CreditCard.full_name(payment)
}
end
defp add_payment(payment, brand_map, opts) do
brand = payment.brand
%{
paymentProductId: Map.fetch!(brand_map, String.to_atom(brand)),
skipAuthentication: opts[:skipAuthentication],
card: add_card(payment)
}
end
defp auth_digest(path, secret_api_key, time) do
data = "POST\napplication/json\n#{time}\n/v1/1226/#{path}\n"
:crypto.hmac(:sha256, secret_api_key, data)
end
defp date() do
use Timex
datetime = Timex.now |> Timex.local
strftime_str = Timex.format!(datetime, "%a, %d %b %Y %H:%M:%S ", :strftime)
time_zone = Timex.timezone(:local, datetime)
time = strftime_str <>"#{time_zone.abbreviation}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment