Authorize .NET AIM с несколькими элементами / продуктами с использованием PHP - PullRequest
1 голос
/ 04 августа 2011

Привет! Я занимаюсь разработкой веб-приложения и должен интегрировать его с Authorize.NET AIM. Я проверил код, предоставленный Authorize.NET, он отлично работает для одного продукта. Этот код имеет возможность использовать для позиций и по умолчанию комментируется. Я раскомментировал его, а затем использовал, но он показывает только обработку одного продукта без обработки отдельных позиций.

См. Пример кода Authorize.NET AIM

.
// 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"           => "API_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

Помогите опубликовать несколько элементов в Authorize.NET AIM.

Заранее спасибо.

Ответы [ 4 ]

1 голос
/ 04 сентября 2012

Вы также можете попробовать использовать AuthnetXML , который легче, чем их SDK, и проще в использовании.Он даже включает пример, который показывает, как добавить несколько позиций:

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>

Отказ от ответственности: я являюсь автором этого кода.

0 голосов
/ 14 июля 2016

Проблема в том, что наименование API вводит в заблуждение.

Ваш массив позиций не должен быть таким (НЕПРАВИЛЬНО):

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

Это должно быть похоже наthis (ПРАВИЛЬНО):

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

Несмотря на то, что «lineItems» является множественным, а «lineItem» - нет, запись множественного числа (массив) происходит в «lineItem», а не «lineItems».

Что еще хуже, у вас может быть такая настройка, и она будет работать для одного элемента и только для одного элемента:

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

Таким образом, вводя пользователя в заблуждение.Я обнаружил это, пытаясь использовать JSON-версию протокола auth.net, отказываясь и используя XML, только для того, чтобы понять, как работает мой XML-парсер, он дублировал записи «lineItems», что привело меня к попытке переместить массив на один уровень ниже.и все волшебным образом начало работать.

Я считаю, что основная проблема заключается в том, как работает парсер auth.net.Следующее:

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

становится таковым в их системе:

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

Что объясняет довольно странную ошибку, говоря о недействительных записях ключа, а затем перечисляя действительные записи ключа.

0 голосов
/ 27 августа 2012

Я бы предложил использовать их SDK вместо вызова CURL.https://developer.authorize.net/integration/fifteenminutes/#custom

Тогда код будет выглядеть следующим образом:

<?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;
}
?>

В вашем случае, когда вам нужна подробная информация о заказе, вам также необходимо добавить элементы в транзакцию:

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

Все это поведение Authorize.net при перечислении элементов немного глючит, поэтому, если это решение не работает, взгляните на: http://community.developer.authorize.net/t5/Integration-and-Testing/x-line-item-integration-in-PHP/td-p/9654

0 голосов
/ 10 сентября 2011

Где вы ищете позиции? Он не отображается в ответе от Authorize.NET. Вы найдете его на странице сведений о транзакции только после входа в Authorize.NET.

...