Zyad A
02/24/2023, 12:35 PMmodule PayMob
class Gateway
API_URL = "<https://accept.paymob.com/api>"
attr_reader :api_key
def initialize(options)
@api_key = options.fetch(:api_key)
end
def authorize(money, auth_token, options = {})
response = request(
:post,
"/auth/tokens",
payload_for_charge(money, auth_token, options).merge(capture: false),
)
if response.success?
ActiveMerchant::Billing::Response.new(
true,
"Transaction Authorized",
{},
authorization: response.parsed_response["token"],
)
else
ActiveMerchant::Billing::Response.new(
false,
response.parsed_response["error"],
)
end
end
#changed the option parameters as per the API
def purchase(money, auth_token, options = {})
response = request(
:post,
'/ecommerce/orders',
{
"auth_token": authorization,
"delivery_needed": false,
"amount_cents": money,
"items": []
}
)
if response.success?
ActiveMerchant::Billing::Response.new(
true,
"Transaction Purchased",
{},
order_key: response.parsed_response["id"],
)
else
ActiveMerchant::Billing::Response.new(
false,
response.parsed_response["error"],
)
end
end
def capture(money, transaction_id, options = {})
response = request(
:post,
'acceptance/payment_keys',
{
"auth_token": authorization,
"amount_cents": money,
"expiration": 3600,
"order_id": order_key,
"billing_data": {},
"currency": "EGP",
"integration_id": 3410599
}
)
if response.success?
ActiveMerchant::Billing::Response.new(
true,
"Transaction Captured",
{},
token: response.parsed_response["token"],
)
else
ActiveMerchant::Billing::Response.new(
false,
response.parsed_response["error"],
)
end
end
private
def request(method, uri, body = {})
HTTParty.send(
method,
"#{API_URL}#{uri}",
headers: {
"Authorization" => "Bearer #{api_key}",
"Content-Type" => "application/json",
"Accept" => "application/json",
},
body: body.to_json,
)
end
def payload_for_charge(money, auth_token, options = {})
{
auth_token: auth_token,
amount: money,
currency: options[:currency],
description: "Payment #{options[:order_id]}",
billing_address: options[:billing_address],
}
end
end
end
class PayMob::PaymentMethod < Spree::PaymentMethod
end