开发者

Authorize.NET AIM with Multiple Items/Products using PHP

Hi I'm developing a web application and needs to Integrate it with Authorize.NET AIM. I have tested the code provided by Authorize.NET it works fine for Single product. This code has an option to use for line items and is commented by default. I uncommented it and then used it but it only shows a single product processing no line items processing.

Please see the Authorize.NET AIM Sample Code

// By default, this sample code is designed to post to our test server for
// developer accounts: https://test.authorize.net/gateway/transact.dll
// for real accounts (even in test mode), please make sure that you are
// posting to: https://secure.authorize.net/gateway/transact.dll
$post_url = "https://test.authorize.net/gateway/transact.dll";

$post_values = array(

// the API Login ID and Transaction Key must be replaced with valid values
"x_login"           => "A开发者_运维知识库PI_LOGIN_ID",
"x_tran_key"        => "TRANSACTION_KEY",

"x_version"         => "3.1",
"x_delim_data"      => "TRUE",
"x_delim_char"      => "|",
"x_relay_response"  => "FALSE",

"x_type"            => "AUTH_CAPTURE",
"x_method"          => "CC",
"x_card_num"        => "4111111111111111",
"x_exp_date"        => "0115",

"x_amount"          => "19.99",
"x_description"     => "Sample Transaction",

"x_first_name"      => "John",
"x_last_name"       => "Doe",
"x_address"         => "1234 Street",
"x_state"           => "WA",
"x_zip"             => "98004"
// Additional fields can be added here as outlined in the AIM integration
// guide at: http://developer.authorize.net
   );

   // This section takes the input fields and converts them to the proper format
   // for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
   $post_string = "";
   foreach( $post_values as $key => $value )
   { $post_string .= "$key=" . urlencode( $value ) . "&"; }
   $post_string = rtrim( $post_string, "& " );

   // The following section provides an example of how to add line item details to
   // the post string.  Because line items may consist of multiple values with the
   // same key/name, they cannot be simply added into the above array.
   //
   // This section is commented out by default.

   $line_items = array(
   "item1<|>golf balls<|><|>2<|>18.95<|>Y",
   "item2<|>golf bag<|>Wilson golf carry bag, red<|>1<|>39.99<|>Y",
   "item3<|>book<|>Golf for Dummies<|>1<|>21.99<|>Y");

   foreach( $line_items as $value )
    { $post_string .= "&x_line_item=" . urlencode( $value ); }


   // This sample code uses the CURL library for php to establish a connection,
   // submit the post, and record the response.
   // If you receive an error, you may want to ensure that you have the curl
   // library enabled in your php configuration
   $request = curl_init($post_url); // initiate curl object
    curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from    response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
$post_response = curl_exec($request); // execute curl post and store results in $post_response
// additional options may be required depending upon your server configuration
// you can find documentation on curl options at http://www.php.net/curl_setopt
    curl_close ($request); // close curl object

    // This line takes the response and breaks it into an array using the specified        delimiting character
    $response_array = explode($post_values["x_delim_char"],$post_response);

    // The results are output to the screen in the form of an html numbered list.
    echo "<OL>\n";
    foreach ($response_array as $value)
    {
      echo "<LI>" . $value . "&nbsp;</LI>\n";
      $i++;
    }
    echo "</OL>\n";
     // individual elements of the array could be accessed to read certain response
     // fields.  For example, response_array[0] would return the Response Code,
     // response_array[2] would return the Response Reason Code.
     // for a list of response fields, please review the AIM Implementation Guide

Please help to post mutiple items with Authorize.NET AIM.

Thanks in Advance.


You can also try using AuthnetXML which is lighter then their SDK and easier to use. It even includes an example that shows how to add multiple line items:

require('../../config.inc.php');
require('../../AuthnetXML.class.php');

$xml = new AuthnetXML(AUTHNET_LOGIN, AUTHNET_TRANSKEY, AuthnetXML::USE_DEVELOPMENT_SERVER);
$xml->createTransactionRequest(array(
    'refId' => rand(1000000, 100000000),
    'transactionRequest' => array(
        'transactionType' => 'authCaptureTransaction',
        'amount' => 5,
        'payment' => array(
            'creditCard' => array(
                'cardNumber' => '4111111111111111',
                'expirationDate' => '122016',
                'cardCode' => '999',
            ),
        ),
        'order' => array(
            'invoiceNumber' => '1324567890',
            'description' => 'this is a test transaction',
        ),
        'lineItems' => array(
            'lineItem' => array(
                0 => array(
                    'itemId' => '1',
                    'name' => 'vase',
                    'description' => 'Cannes logo',
                    'quantity' => '18',
                    'unitPrice' => '45.00'
                ),
                1 => array(
                    'itemId' => '2',
                    'name' => 'desk',
                    'description' => 'Big Desk',
                    'quantity' => '10',
                    'unitPrice' => '85.00'
                )
            )
        ),
        'tax' => array(
           'amount' => '4.26',
           'name' => 'level2 tax name',
           'description' => 'level2 tax',
        ),
        'duty' => array(
           'amount' => '8.55',
           'name' => 'duty name',
           'description' => 'duty description',
        ),
        'shipping' => array(
           'amount' => '4.26',
           'name' => 'level2 tax name',
           'description' => 'level2 tax',
        ),
        'poNumber' => '456654',
        'customer' => array(
           'id' => '18',
           'email' => 'someone@blackhole.tv',
        ),
        'billTo' => array(
           'firstName' => 'Ellen',
           'lastName' => 'Johnson',
           'company' => 'Souveniropolis',
           'address' => '14 Main Street',
           'city' => 'Pecan Springs',
           'state' => 'TX',
           'zip' => '44628',
           'country' => 'USA',
        ),
        'shipTo' => array(
           'firstName' => 'China',
           'lastName' => 'Bayles',
           'company' => 'Thyme for Tea',
           'address' => '12 Main Street',
           'city' => 'Pecan Springs',
           'state' => 'TX',
           'zip' => '44628',
           'country' => 'USA',
        ),
        'customerIP' => '192.168.1.1',
        'transactionSettings' => array(
            'setting' => array(
                0 => array(
                    'settingName' =>'allowPartialAuth',
                    'settingValue' => 'false'
                ),
                1 => array(
                    'settingName' => 'duplicateWindow',
                    'settingValue' => '0'
                ),
                2 => array(
                    'settingName' => 'emailCustomer',
                    'settingValue' => 'false'
                ),
                3 => array(
                    'settingName' => 'recurringBilling',
                    'settingValue' => 'false'
                ),
                4 => array(
                    'settingName' => 'testRequest',
                    'settingValue' => 'false'
                )
            )
        ),
        'userFields' => array(
            'userField' => array(
                'name' => 'MerchantDefinedFieldName1',
                'value' => 'MerchantDefinedFieldValue1',
            ),
            'userField' => array(
                'name' => 'favorite_color',
                'value' => 'blue',
            ),
        ),
    ),
));
?>

<!DOCTYPE html>
<html>
<html lang="en">
    <head>
        <title>AIM :: Authorize and Capture</title>
        <style type="text/css">
            table
            {
                border: 1px solid #cccccc;
                margin: auto;
                border-collapse: collapse;
                max-width: 90%;
            }

            table td
            {
                padding: 3px 5px;
                vertical-align: top;
                border-top: 1px solid #cccccc;
            }

            pre
            {
                overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
                white-space: pre-wrap; /* css-3 */
                white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
                white-space: -pre-wrap; /* Opera 4-6 */
                white-space: -o-pre-wrap; /* Opera 7 */ /*
                width: 99%; */
                word-wrap: break-word; /* Internet Explorer 5.5+ */
            }

            table th
            {
                background: #e5e5e5;
                color: #666666;
            }

            h1, h2
            {
                text-align: center;
            }
        </style>
    </head>
    <body>
        <h1>
            AIM :: Authorize and Capture
        </h1>
        <h2>
            Results
        </h2>
        <table>
            <tr>
                <th>Response</th>
                <td><?php echo $xml->messages->resultCode; ?></td>
            </tr>
            <tr>
                <th>code</th>
                <td><?php echo $xml->messages->message->code; ?></td>
            </tr>
            <tr>
                <th>Successful?</th>
                <td><?php echo ($xml->isSuccessful()) ? 'yes' : 'no'; ?></td>
            </tr>
            <tr>
                <th>Error?</th>
                <td><?php echo ($xml->isError()) ? 'yes' : 'no'; ?></td>
            </tr>
            <tr>
                <th>authCode</th>
                <td><?php echo $xml->transactionResponse->authCode; ?></td>
            </tr>
            <tr>
                <th>transId</th>
                <td><?php echo $xml->transactionResponse->transId; ?></td>
            </tr>
        </table>
        <h2>
            Raw Input/Output
        </h2>
<?php
    echo $xml;
?>
    </body>
</html>

Disclaimer: I am the author of that code.


Where are you looking for the line items? It does not show up in the response back from Authorize.NET. You will only find it on the transaction detail page when you sign in to Authorize.NET.


I would suggest using their SDK instead of a CURL call. https://developer.authorize.net/integration/fifteenminutes/#custom

Then the code would be like:

<?php
require_once 'anet_php_sdk/AuthorizeNet.php'; // Make sure this path is correct.
$transaction = new AuthorizeNetAIM('YOUR_API_LOGIN_ID', 'YOUR_TRANSACTION_KEY');
$transaction->amount = '9.99';
$transaction->card_num = '4007000000027';
$transaction->exp_date = '10/16';

$response = $transaction->authorizeAndCapture();

if ($response->approved) {
  echo "<h1>Success! The test credit card has been charged!</h1>";
  echo "Transaction ID: " . $response->transaction_id;
} else {
  echo $response->error_message;
}
?>

In your case that you need the itemized order information you would have to add the items to the transaction also:

$transaction->addLineItem(
  'item1', // Item Id
  'Golf tees', // Item Name
  'Blue tees', // Item Description
  '2', // Item Quantity
  '5.00', // Item Unit Price
  'N' // Item taxable
);

All this Authorize.net behavior of listing the items it's a little bit buggy, so if that solution does not work, take a look at: http://community.developer.authorize.net/t5/Integration-and-Testing/x-line-item-integration-in-PHP/td-p/9654


The problem is the naming of the API is wildly misleading.

You're array of line items shouldn't be this (WRONG):

{ lineItems:[
  { lineItem: { ..Line item data..}},
  { lineItem: { ..Line item data..}}
]}

It should be like this (CORRECT):

{ lineItems:
  { lineItem: [{ ..Line item data..},
               { ..Line item data..}]
}}

Even though "lineItems" is plural, and "lineItem" isn't, the plural entry (array) happens on "lineItem" not "lineItems".

Whats even worse, you can have a setup like this, and it will work for one item, and one item only:

{ lineItems:[
  { lineItem: { ..Line item data..}}   
]}

Thus further misleading the user. I discovered this by trying to use the JSON version of auth.net protocol, giving up and using XML, only to realize how my XML parser works, it was duplicating "lineItems" entries, which led me to try moving the array down one level and things magically started working.

I believe the core issue is how auth.net's parser works. The following:

{ lineItems:[
  { lineItem: { ..Line item data..}},
  { lineItem: { ..Line item data..}}
]}

becomes this in their system:

{[
   {lineItems: { lineItem: { ..Line item data..}}},
   {lineItems: { lineItem: { ..Line item data..}}}
]}

Which would explain the rather odd error talking about invalid key entries, and then listing the valid key entries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜