class AuthorizeNet::Api

This class uses the AuthroizeRequest object to interact with the Authorize.Net API

Add any new Authroize.Net API endpoints here

Public Class Methods

new(api_login_id, api_transaction_key, **options) click to toggle source
# File lib/authorize_net/api.rb, line 12
def initialize(api_login_id, api_transaction_key, **options)
  @api_login_id = api_login_id
  @api_transaction_key = api_transaction_key
  @is_sandbox = options[:sandbox]
  @signature_key = options[:signature_key]
  @logger = nil
  @log_full_request = false
end

Public Instance Methods

chargeAndCreateProfile(amount, customer_profile) click to toggle source

Creates the CustomerProfile and charges the first listed PaymentProfile on AuthorizeNet @param Number amount @param AuthorizeNet::CustomerProfile customer_profile @return {customer_profile_id, payment_profile_id}

# File lib/authorize_net/api.rb, line 63
def chargeAndCreateProfile(amount, customer_profile)
  if customer_profile.payment_profiles.empty?
    raise "[AuthorizeNet] CustomerProfile in Api.chargeAndCreateProfile requires a PaymentProfile"
  end

  payment_profile = customer_profile.payment_profiles.first
  xml_obj = getXmlAuth
  xml_obj["transactionRequest"] = {
    "transactionType" => "authCaptureTransaction",
    "amount" => amount,
    "payment" => {
      "creditCard" => payment_profile.credit_card.to_h,
    },
    "profile" => {
      "createProfile" => true,
    },
    "customer" => {
      "id" => customer_profile.merchant_id,
      "email" => customer_profile.email,
      "description" => customer_profile.description,
    },
    "billTo" => payment_profile.billing_address.to_h,
  }

  response = sendRequest("createTransactionRequest", xml_obj)
  validate_hash(response, amount)
  if !response.nil?
    return {
      :transaction => AuthorizeNet::Transaction.parse(response),
      :customer_profile_id => AuthorizeNet::Util.getXmlValue(
        response, "customerProfileId"),
      :payment_profile_id => AuthorizeNet::Util.getXmlValue(
        response, "customerPaymentProfileIdList numericString"),
    }
  end
end
chargeCard(amount, credit_card, billing_address=nil) click to toggle source

Charges the given credit card @param Number amount @param AuthorizeNet::CreditCard credit_card @param AuthorizeNet::Address billing_address @return {transaction_id}

# File lib/authorize_net/api.rb, line 36
def chargeCard(amount, credit_card, billing_address=nil)
  xml_obj = getXmlAuth
  xml_obj["transactionRequest"] = {
    "transactionType" => "authCaptureTransaction",
    "amount" => amount,
    "payment" => {
      "creditCard" => credit_card.to_h,
    },
  }
  if !billing_address.nil?
    xml_obj["transactionRequest"]["billTo"] = billing_address.to_h
  end

  response = sendRequest("createTransactionRequest", xml_obj)
  validate_hash(response, amount)
  if !response.nil?
    return AuthorizeNet::Transaction.parse(response)
  end
end
chargeProfile(amount, profile_id, payment_profile_id) click to toggle source

Charges the given profile and payment profile on Authorize.net @param Number amount @param String/Number customer_profile_id @param String/Number payment_profile_id @return transaction_id

# File lib/authorize_net/api.rb, line 107
def chargeProfile(amount, profile_id, payment_profile_id)
  xml_obj = getXmlAuth
  xml_obj["transactionRequest"] = {
    "transactionType" => "authCaptureTransaction",
    "amount" => amount,
    "profile" => {
      "customerProfileId" => profile_id,
      "paymentProfile" => {
        "paymentProfileId" => payment_profile_id,
      },
    },
  }

  response = sendRequest("createTransactionRequest", xml_obj)
  validate_hash(response, amount)
  if !response.nil?
    return AuthorizeNet::Transaction.parse(response)
  end
end
createCustomerProfile(customer_profile, validation_mode=nil) click to toggle source

Creates the given customer profile on Authorize.net @param AuthorizeNet::CustomerProfile customer_profile @param Number amount @param AuthorizeNet::ValidationMode validation_mode (optional) @return transaction_id

# File lib/authorize_net/api.rb, line 134
def createCustomerProfile(customer_profile, validation_mode=nil)
  xml_obj = getXmlAuth
  xml_obj["profile"] = customer_profile.to_h

  addValidationMode!(xml_obj, validation_mode)
  response = sendRequest("createCustomerProfileRequest", xml_obj)

  if !response.nil?
    return {
      :customer_profile_id => AuthorizeNet::Util.getXmlValue(
        response, "customerProfileId"),
      :payment_profile_id => AuthorizeNet::Util.getXmlValue(
        response, "customerPaymentProfileIdList numericString"),
    }
  end
end
createPaymentProfile(customer_profile_id, payment_profile, validation_mode=nil) click to toggle source

Create Customer Payment Profile @param String/Number customer_profile_id @param AuthorizeNet::PaymentProfile payment_profile @param AuthorizeNet::ValidationMode validation_mode (optional) @return {customer_profile_id, payment_profile_id}

# File lib/authorize_net/api.rb, line 158
def createPaymentProfile(customer_profile_id, payment_profile, validation_mode=nil)
  xml_obj = getXmlAuth
  xml_obj["customerProfileId"] = customer_profile_id
  xml_obj["paymentProfile"] = payment_profile.to_h

  addValidationMode!(xml_obj, validation_mode)
  response = sendRequest("createCustomerPaymentProfileRequest", xml_obj)

  if !response.nil?
    return {
      :customer_profile_id => AuthorizeNet::Util.getXmlValue(
        response, "customerProfileId"),
      :payment_profile_id => AuthorizeNet::Util.getXmlValue(
        response, "customerPaymentProfileId"),
    }
  end
end
deletePaymentProfile(customer_profile_id, payment_profile_id) click to toggle source

Delete Customer Payment Profile @param String/Number customer_profile_id @param String/Number payment_profile_id @return boolean is delete successful?

# File lib/authorize_net/api.rb, line 182
def deletePaymentProfile(customer_profile_id, payment_profile_id)
  xml_obj = getXmlAuth
  xml_obj["customerProfileId"] = customer_profile_id
  xml_obj["customerPaymentProfileId"] = payment_profile_id

  response = sendRequest("deleteCustomerPaymentProfileRequest", xml_obj)
  return !response.nil?
end
getCustomerProfile(customer_profile_id) click to toggle source

Get customer profile information @param String/Number customer_profile_id @param String/Number customer_profile_id @return AuthorizeNet::CustomerProfile

# File lib/authorize_net/api.rb, line 214
def getCustomerProfile(customer_profile_id)
  xml_obj = getXmlAuth
  xml_obj["customerProfileId"] = customer_profile_id

  response = sendRequest("getCustomerProfileRequest", xml_obj)
  if response
    return AuthorizeNet::CustomerProfile.parse(response)
  end
end
getTransactionInfo(transaction_id) click to toggle source

Gets transaction information @param String/Number customer_profile_id @param String/Number transaction_id @return AuthorizeNet::Transaction

# File lib/authorize_net/api.rb, line 230
def getTransactionInfo(transaction_id)
  xml_obj = getXmlAuth
  xml_obj["transId"] = transaction_id

  response = sendRequest("getTransactionDetailsRequest", xml_obj)
  if response
    return AuthorizeNet::Transaction.parse(response)
  end
end
setLogFullRequest(log_full_request) click to toggle source
# File lib/authorize_net/api.rb, line 25
def setLogFullRequest(log_full_request)
  @log_full_request = log_full_request
end
setLogger(logger) click to toggle source
# File lib/authorize_net/api.rb, line 21
def setLogger(logger)
  @logger = logger
end
validatePaymentProfile(customer_profile_id, payment_profile_id, validation_mode) click to toggle source

Validate Customer Payment Profile @param String/Number customer_profile_id @param String/Number payment_profile_id @param AuthorizeNet::ValidationMode::(String) validation_mode @return boolean is update successful?

# File lib/authorize_net/api.rb, line 198
def validatePaymentProfile(customer_profile_id, payment_profile_id, validation_mode)
  xml_obj = getXmlAuth
  xml_obj["customerProfileId"] = customer_profile_id
  xml_obj["customerPaymentProfileId"] = payment_profile_id
  xml_obj["validationMode"] = validation_mode

  response = sendRequest("validateCustomerPaymentProfileRequest", xml_obj)
  return !response.nil?
end

Private Instance Methods

addValidationMode!(xml_obj, validation_mode) click to toggle source
# File lib/authorize_net/api.rb, line 253
def addValidationMode!(xml_obj, validation_mode)
  if validation_mode
    xml_obj["validationMode"] = validation_mode
  end
end
getXmlAuth() click to toggle source
# File lib/authorize_net/api.rb, line 244
def getXmlAuth
  return {
    "merchantAuthentication" => {
      "name" => @api_login_id,
      "transactionKey" => @api_transaction_key,
    }
  }
end
handleResponse(raw_response) click to toggle source

Looks for potential errors in the response and raises an error if it finds any Passes through OK responses @throws AuthorizeNet::Exception

# File lib/authorize_net/api.rb, line 265
def handleResponse(raw_response)
  logHttpResponse(raw_response)

  response = AuthorizeNet::Response.parseXml(raw_response.read_body)
  if response.result == AuthorizeNet::RESULT_OK && response.errors.nil?
    return response.parsed_xml
  else
    logErrorResponse(response)
    AuthorizeNet::ErrorHandler.handle(response)
  end
end
logErrorResponse(response) click to toggle source

Returns a log string with http response data @param Net::HTTPResponse @throws RuntimeError

# File lib/authorize_net/api.rb, line 340
def logErrorResponse(response)
  if @logger.respond_to? :info
    @logger.info("[AuthorizeNet] Responded with resultCode=\"#{response.result}\"")
  end

  if !response.messages.nil? and @logger.respond_to?(:info)
    response.messages.each do |msg|
      @logger.info("[AuthorizeNet] Message code=\"#{msg[:code]}\" text=\"#{msg[:text]}\"")
    end
  end

  if !response.errors.nil? and @logger.respond_to?(:error)
    response.errors.each do |error|
      @logger.error("[AuthorizeNet] Error code=\"#{error[:code]}\" text=\"#{error[:text]}\"")
    end
  end
end
logHttpResponse(response) click to toggle source

Log HTTP response from Authorize Net @param Net::HTTPResponse @return String log

# File lib/authorize_net/api.rb, line 327
def logHttpResponse(response)
  if @logger.respond_to? :logHttpResponse
    @logger.logHttpResponse(response)
  elsif @logger.respond_to? :info
    @logger.info("[AuthorizeNet] HTTP Response code=#{response.code} message=#{response.message}")
  end
end
sendRequest(type, xml_obj) click to toggle source

Send HTTP request to Authorize Net @param Net::HTTPResponse @return response

# File lib/authorize_net/api.rb, line 311
def sendRequest(type, xml_obj)
  uri = @is_sandbox ? AuthorizeNet::TEST_URI : AuthorizeNet::URI
  request = AuthorizeNet::Request.new(type, xml_obj, uri)

  if @logger.respond_to? :info
    @logger.info(request.toLog(@log_full_request))
  end

  return handleResponse(request.postRequest)
end
validate_hash(response_xml, amount) click to toggle source

Validates that the returned transaction hash value is what we expect it to be

@throws AuthorizeNet::Exception

# File lib/authorize_net/api.rb, line 283
def validate_hash(response_xml, amount)
  if @signature_key.nil?
    return
  end

  formatted_amount = "%.2f" % amount
  transaction_id = AuthorizeNet::Util.getXmlValue(response_xml, "transId")
  hash_text = "^#{@api_login_id}^#{transaction_id}^#{formatted_amount}^"

  calculated_hash = OpenSSL::HMAC.hexdigest('sha512', [@signature_key].pack('H*'), hash_text).downcase
  trans_hash = AuthorizeNet::Util.getXmlValue(response_xml, "transHashSha2").downcase

  if calculated_hash != trans_hash
    if @logger.respond_to? :error
      @logger.error("[AuthorizeNet] Response Transaction Hash doesn't equal expected value. trans_hash=#{trans_hash} calculated_hash=#{calculated_hash}")
    end

    e = AuthorizeNet::Exception.new("[AuthorizeNet] Returned hash doesn't match expected value.")
    e.errors.push({:text => "Something went wrong. Please contact customer assistance or try again later"})
    raise e
  end
end