cancel
Showing results for 
Search instead for 
Did you mean: 

Procedural Code with Authorize.net

I have built a website using PHP in a procedural coding style, and I would like to know how to integrate Authorize.net with my website.

 

I do not know object oriented coding and hope there is a way to use traditional procedural coding instead.

 

I did not see any tutorials dealing with this, and when I looked for help on the website I became immediately confused.  :(

 

All I want to build is a one page form where a user enters payment details and is charged a fixed dollar amount with no fancy shopping cart or anything.

 

Please help!

 

Your truly,

 

 

Sally

 

 

ssimons
Contributor
9 REPLIES 9

Hi @ssimons,

 

We have a PHP SDK and PHP sample code available to assist you. However, that PHP SDK may be a little bit overkill for what you need.

 

Here's some sample code that is about the simplest transaction that can be done. You would have a form that gathers the card number, expiration date, and card code, and posts them to this script. This script would than insert the right values into an XML formatted request that comes to us via curl.

 

<?php

//create a template for the XML that's sent as the transaction request
$xmlStr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<createTransactionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
    <merchantAuthentication></merchantAuthentication>
    <transactionRequest>
        <transactionType>authCaptureTransaction</transactionType>
        <payment>
            <creditCard>
            </creditCard>
        </payment>
    </transactionRequest>
</createTransactionRequest>
XML;
$xml = simplexml_load_string($xmlStr,'SimpleXMLElement', LIBXML_NOWARNING);

// the following assumes you've put your credentials in somewhere
// as environment variables called "API_LOGIN_ID" and "TRANSACTION_KEY"
$loginId = getenv("API_LOGIN_ID");
$transactionKey = getenv("TRANSACTION_KEY");


//modify the template to add apropriate values
$xml->merchantAuthentication->addChild('name',$loginId);
$xml->merchantAuthentication->addChild('transactionKey',$transactionKey);
//add the payment information from the information that was posted to this script
$xml->creditCard->addChild('cardNumber',$cardNumber);
$xml->creditCard->addChild('expirationDate',$expirationDate);
$xml->creditCard->addChild('cardCode',$cardCode);

$url = "https://apitest.authorize.net/xml/v1/request.api";

    try{
        $ch = curl_init();
        if (FALSE === $ch)
        	throw new Exception('failed to initialize');
        curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
        
        $content = curl_exec($ch);
        $content = str_replace('xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $content);

        $PaymentResponse = new SimpleXMLElement($content);
        if (FALSE === $content)
        	throw new Exception(curl_error($ch), curl_errno($ch));
        curl_close($ch);

    }catch(Exception $e) {
    	trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
	}


?>

 

It might be good to familiarize yourself with our API reference guide, and particularly the "Try It" tabs to see how our API works. If you want to send additional information like bill to address or anything, just follow this same pattern.

 

 

Aaron
All Star
Aaron,
Thank you for the response!
1.) I clicked clicked on PHP SDK last night but felt lost when I looked in that directory.
Since I do not know object-oriented programming, where would I go to learn how to incorporate AUthorize.net into my basic procedure website code base?  (There is no way I can learn OOP in the time I have to get this up and running.)
Is there a directory or files that would help me learn more?

 

 

2.) In the PHO Sample Code link, again I am confused what all of those links mean.

 

Where would I go to do what I described?

 

 

 

3.) > This script would than insert the right values into an XML formatted

      > request that comes to us via curl.

 

What is curl?

 

Where do I get curl?

 

How do I incorporate curl into my PHP code?

 

 

4.) Is the code below safe to use for an actual live website after I correct the field names for credit card info?

 

 

 

5.)

$loginId = getenv("API_LOGIN_ID");
$transactionKey = getenv("TRANSACTION_KEY");

 

It looks like I can define some PHP constants and then make them avaiable to this script?

 

 

 

6.)

$xml->creditCard->addChild('cardNumber',$cardNumber);
$xml->creditCard->addChild('expirationDate',$expirationDate);
$xml->creditCard->addChild('cardCode',$cardCode);

 

This information would come from my credit card submittal form, right?

 

 

7.)

$url = "https://apitest.authorize.net/xml/v1/request.api";

 

Do I need to request a "test" account?

 

What do I put here for production?

 

 

8.) I will try and read the API Reference guide but all of this seems so foreign to me.

 

Aren't API part of object oriented programming too?

 

Thank you for the help so far!

 

Sincerely,

 

 

Sally

 

 

 

****************************************************************************


@Aaron wrote:

Hi @ssimons,

 

We have a PHP SDK and PHP sample code available to assist you. However, that PHP SDK may be a little bit overkill for what you need.

 

Here's some sample code that is about the simplest transaction that can be done. You would have a form that gathers the card number, expiration date, and card code, and posts them to this script. This script would than insert the right values into an XML formatted request that comes to us via curl.

 

<?php

//create a template for the XML that's sent as the transaction request
$xmlStr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<createTransactionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
    <merchantAuthentication></merchantAuthentication>
    <transactionRequest>
        <transactionType>authCaptureTransaction</transactionType>
        <payment>
            <creditCard>
            </creditCard>
        </payment>
    </transactionRequest>
</createTransactionRequest>
XML;
$xml = simplexml_load_string($xmlStr,'SimpleXMLElement', LIBXML_NOWARNING);

// the following assumes you've put your credentials in somewhere
// as environment variables called "API_LOGIN_ID" and "TRANSACTION_KEY"
$loginId = getenv("API_LOGIN_ID");
$transactionKey = getenv("TRANSACTION_KEY");


//modify the template to add apropriate values
$xml->merchantAuthentication->addChild('name',$loginId);
$xml->merchantAuthentication->addChild('transactionKey',$transactionKey);
//add the payment information from the information that was posted to this script
$xml->creditCard->addChild('cardNumber',$cardNumber);
$xml->creditCard->addChild('expirationDate',$expirationDate);
$xml->creditCard->addChild('cardCode',$cardCode);

$url = "https://apitest.authorize.net/xml/v1/request.api";

    try{
        $ch = curl_init();
        if (FALSE === $ch)
        	throw new Exception('failed to initialize');
        curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
        
        $content = curl_exec($ch);
        $content = str_replace('xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $content);

        $PaymentResponse = new SimpleXMLElement($content);
        if (FALSE === $content)
        	throw new Exception(curl_error($ch), curl_errno($ch));
        curl_close($ch);

    }catch(Exception $e) {
    	trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
	}


?>

 

It might be good to familiarize yourself with our API reference guide, and particularly the "Try It" tabs to see how our API works. If you want to send additional information like bill to address or anything, just follow this same pattern.

 

 


 

Hi Sally,

 

An API has nothing to do with object oriented programming. API just means "Application Programming Interface", a set of specs for programmatically communicating with something else.

 

Our service is a web service, and we have an API which is the set of commands and parameters and procedures to tell that service to do something and to understand the response you get back.

 

At a basic level, you cause your server to send a piece of text like this to our server:

 

<authenticateTestRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
    <merchantAuthentication>
        <name>API_LOGIN_ID</name>
        <transactionKey>API_TRANSACTION_KEY</transactionKey>
    </merchantAuthentication>
</authenticateTestRequest>

Our server responds with a string of text like this:

 

 

<?xml version="1.0" encoding="utf-8"?>
<authenticateTestResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
    <messages>
        <resultCode>Ok</resultCode>
        <message>
            <code>I00001</code>
            <text>Successful.</text>
        </message>
    </messages>
</authenticateTestResponse>

 

The API is just the set of instructions to tell you what stuff to put in the request and what stuff to put in the response.

 

What you want to do is to create a PHP script that takes information off of a web form and sends it to us. That's what the sample PHP script I posted does. It takes three variabled from the form that was posted to it and puts those into a request like the above. It also takes your login ID and transaction key for your sandbox account from a couple of environment variables you set outside the script and adds those to the request. Then, it calls curl to send that request to our server, and get the response. It's up to you to put some code in at the end to put the response into some HTML set up however you want to give that response to the customer.

 

It's not so much an issue of knowing object oriented programming as it is knowing PHP. If you know PHP you can turn that sample code into whatever you need.

 


@ssimons wrote:

3.) > This script would than insert the right values into an XML formatted

      > request that comes to us via curl.

 

What is curl?

 

Where do I get curl?

 

How do I incorporate curl into my PHP code?

 


 

curl is a program that basically fetches stuff from a URL for you. If your server has PHP installed, it almost always will also have curl. You incorporate it into your PHP code just like I showed you, but if you'd like to see more step by step instructions on how to incorporate curl into PHP, check the PHP documentation.

 

 


@ssimons wrote:

4.) Is the code below safe to use for an actual live website after I correct the field names for credit card info?

 

 


 

Safe to use? Define safe.

 

Will it work? Sure. Does this code by itself meet all your requirements to keep your system secure, thereby meeting all of your legal and contractual obligations to abide by the requirements of the PCI Data Security Standards v3.2? I don't know. Please be advised though, that by working with credit card data, you have the requirement of making sure you meet the PCI-DSS requirements. More info here: http://www.authorize.net/resources/pcicompliance/

 


@ssimons wrote:

5.)

$loginId = getenv("API_LOGIN_ID");
$transactionKey = getenv("TRANSACTION_KEY");

 

It looks like I can define some PHP constants and then make them avaiable to this script?

 

 


 

This is using PHP's getenv() function to retrieve environment variables called "API_LOGIN_ID" and "TRANSACTION_KEY". You don't want to put those right in the script since your server could break (or be broken into), and you'd be exposing your Authorize.Net credentials to the world. You can set these variables in the php.ini file. Or, set them in some other file and then reference them here. Just make sure that other file doesn't get put anywhere that's accessible.

 


@ssimons wrote:

6.)

$xml->creditCard->addChild('cardNumber',$cardNumber);
$xml->creditCard->addChild('expirationDate',$expirationDate);
$xml->creditCard->addChild('cardCode',$cardCode);

 

This information would come from my credit card submittal form, right?

  


 Yes, I'm assuming you'd have fields in that form named "cardNumber", "expirationDate", and "cardCode". Or, if they are named something different, change the names here.

 

 


@ssimons wrote:

7.)

$url = "https://apitest.authorize.net/xml/v1/request.api";

 

Do I need to request a "test" account?

 

What do I put here for production?

 


 

 Absolutely you need a test account. Request that here. The production url is the same, but without the word "test". So https://api.authorize.net/xml/v1/request.api

 

 

If you feel like you're in a little over your head here, I apologize. I wish it was easier, but we assume a certain level of knowledge regarding interacting with web services. We do have some easier ways in if that would help. Instead of trying to take the card information directly and then pass it to our servers, you might be more interested in something like Accept.js, or Accept Hosted. Accept.js will help you with the PCI requirements, because you put a script in your web form that turns the card number into a single-use token before sending it to you. Accept Hosted goes one better by sending the customer to a payment form hosted on our site, where we process the payment for you.

@Aaron, I feel like I have made some progress reading over the sample code you provided, plus looking at the links as well.  However I am still struggling to put everything together because I don't have any eperience with object-oriented code, APIs, cURL or XML.  (The code you provided above does use some object-oriented notation, so that does throw me off a bit!)
Aaron wrote:

 

Here's some sample code that is about the simplest transaction that can be done...

 

 $content = curl_exec($ch);

 

This line executes the cURL handle, but what exactly does that mean?

 

Does this line send my credit card request to Authorize.net?

 

 

        $content = str_replace('xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd"', '', $content);

 

What are you trying to do here?

 

What does $content represent?

 

 

        $PaymentResponse = new SimpleXMLElement($content);

 

SimpleXMLElement was an object we created earlier that contained all of my credit card form data after it was inserted into the XML template, right?

 

So what are we doing here?

 

 

Sincerely,

 

 

Sally 

 

My post above is not supposed to be an entire quote.  Can I edit it?

 

I was trying to ask @Aaron some follow up questions and quote his code.

Belwo is some sample code provided to me by @Aaron... 

 

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML()); // The full data to post in a HTTP "POST" operation.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false );

 

 

Should this have the following line in it so that it functions as a POST??

 

curl_setopt($ch, CURLOPT_POST, 1);

 

 

Hi @ssimons,

 

 

CURLOPT_POSTFIELDS implies CURLOPT_POST. You don't need to use CURLOPT_POST while using CURLOPT_POSTFIELDS. The request method will always be set to POST in this case.

 

There's no harm in also setting CURLOPT_POST to true, but it's not necessary in this case.

@Aaron,

 

Thank you for clarifying things on CURLOPT_POST.

 

If you can please respond to my questions in Message #5, that would be appreciated.

 

(I think I now understand how to build the XML template, but am still foggy on how submitting the Request and getting the Response back works...)

 

Sincerely,

 

Sally

This works fine for me, simple and straight forward.  have been using it for years:

 

function authorize_cc ($cc,$exp,$cvv,$amount,$first_name,$last_name,$login='',$tranKey='',$signatureKey=''){

 

$post_string = 'x_login=' . $login;
$post_string .= '&x_tran_key=' . $tranKey;
$post_string .= '&x_delim_data=TRUE';
$post_string .= '&x_url=FALSE';
$post_string .= '&x_type=AUTH_CAPTURE';
$post_string .= '&x_method=CC';
$post_string .= '&x_relay_response=FALSE';
$post_string .= '&x_card_num=' . $cc;
$post_string .= '&x_exp_date=' . $exp;
$post_string .= '&x_amount=' . $amount;
$post_string .= '&x_address=';
$post_string .= '&x_zip=';
$post_string .= '&x_card_code=' . $cvv;
$post_string .= '&x_name=' . $first_name . ' ' . $last_name;

 

$test_url = 'https://test.authorize.net/gateway/transact.dll';
$production_url = 'https://secure2.authorize.net/gateway/transact.dll';

$curl_request = curl_init( $test_url );

curl_setopt( $curl_request, CURLOPT_POSTFIELDS, $post_string );
curl_setopt( $curl_request, CURLOPT_HEADER, 0 );
curl_setopt( $curl_request, CURLOPT_TIMEOUT, 45 );
curl_setopt( $curl_request, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl_request, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl_request, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2 );
curl_setopt( $curl_request, CURLOPT_SSL_VERIFYPEER, false );

$response = curl_exec( $curl_request );

curl_close( $curl_request );

$results = explode(',',$response);

return $results;

}