PHP Authorize.net Integration with JSON API: Process online payments with Authorize.net API

Recommend this page to a friend!
  Info   View files Documentation   View files View files (122)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2020-06-22 (3 months ago) RSS 2.0 feedNot yet rated by the usersTotal: 61 All time: 9,790 This week: 324Up
Version License PHP version Categories
authnetjson 4.1The PHP License7.2E-Commerce, Web services, PHP 7
Description Author

This package can be used to process online payments with Authorize.net API.

It can send HTTP requests to the Authorize.net JSON API Web server to execute several types of operations to obtain authorization for payments on the Internet. Currently it can:

- Authorize payments with a given credit card and capture the authorization results.
- Create a customer profile with his billing and shipping address and credit card details.
- Create a recurring subscription payment with credit card details
- Get processed transaction details
- Create a web hook to get payment processing response

Recommendations
Picture of John Conde
  Performance   Level  
Name: John Conde <contact>
Classes: 5 packages by
Country: United States United States
Age: 47
All time rank: 3283411 in United States United States
Week rank: 68 Up5 in United States United States Up
Innovation award
Innovation award
Nominee: 1x

Details

Latest Stable Version Total Downloads Scrutinizer Code Quality Build Status Code Coverage Maintainability License

AuthnetJSON

Library that abstracts Authorize.Net's JSON APIs.

Requirements

  • PHP 7.2+ (Support for PHP 7.2.0 - 7.4.*)
  • cURL PHP Extension
  • JSON PHP Extension
  • An Authorize.Net account

Support for PHP versions less than 7.2 has been removed from the master branch. There is a PHP 5.6 compatible branch available for development and releases for 5.6 may continue to be made as long as it is feasible to do so.

Installation

Simply add a dependency on stymiee/authnetjson to your project's composer.json file if you use Composer to manage the dependencies of your project.

Here is a minimal example of a composer.json file that just defines a dependency on AuthnetJSON:

{
    "require": {
        "stymiee/authnetjson": "~4.1"
    }
}

Basic Usage

Using this library usually consists of three steps:

  1. Initiate the library with the login credentials for your Authorize.Net account
  2. Make the API call passing any required parameters as an array
  3. Check for the results and use them appropriately

NOTE: If you are viewing any of the examples in a browser you will need to fill your Authorize.Net credentials in config.inc.php before usage

Simple usage:

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->getTransactionDetailsRequest([
    'transId' => '2162566217'
]);
if ($response->isSuccessful()) {
    echo $json->transaction->transactionStatus;
}

The format of the array to be passed during the API call follows the structure outlined in Authorize.Net's Integration Guide.

Using the Authorize.Net Development Server

Authorize.Net provides a development environment for developers to test their integration against. To use this endpoint (as opposed to their production endpoint) set the optional third parameter of AuthnetApiFactory::getJsonApiHandler() to be 1 or use the built in class constant AuthnetApiFactory::USE_DEVELOPMENT_SERVER:

$json = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY, 
                                                AuthnetApiFactory::USE_DEVELOPMENT_SERVER);

Usage Examples

To help make how this library is used easier to understand example API calls are provided in the example directory. Examples for all of the current APIs calls are represented. You may need to make adjustments to get some to work as they may be dependent on valid values created from other API calls (i.e. a void will not work without a valid transaction ID).

Authorize and Capture (Basic)

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->createTransactionRequest([
    'refId' => rand(1000000, 100000000),
    'transactionRequest' => [
        'transactionType' => 'authCaptureTransaction',
        'amount' => 5,
        'payment' => [
            'creditCard' => [
                'cardNumber' => '4111111111111111',
                'expirationDate' => '122026',
                'cardCode' => '999',
            ]
        ]
    ]
]);

if ($response->isSuccessful()) {
    echo $response->transactionResponse->authCode;
}

Authorize and Capture (Full)

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->createTransactionRequest([
    'refId' => rand(1000000, 100000000),
    'transactionRequest' => [
        'transactionType' => 'authCaptureTransaction',
        'amount' => 5,
        'payment' => [
            'creditCard' => [
                'cardNumber' => '4111111111111111',
                'expirationDate' => '122026',
                'cardCode' => '999',
            ],
        ],
        'order' => [
            'invoiceNumber' => '1324567890',
            'description' => 'this is a test transaction',
        ],
        'lineItems' => [
            'lineItem' => [
                0 => [
                    'itemId' => '1',
                    'name' => 'vase',
                    'description' => 'Cannes logo',
                    'quantity' => '18',
                    'unitPrice' => '45.00'
                ],
                1 => [
                    'itemId' => '2',
                    'name' => 'desk',
                    'description' => 'Big Desk',
                    'quantity' => '10',
                    'unitPrice' => '85.00'
                ]
            ]
        ],
        'tax' => [
           'amount' => '4.26',
           'name' => 'level2 tax name',
           'description' => 'level2 tax',
        ],
        'duty' => [
           'amount' => '8.55',
           'name' => 'duty name',
           'description' => 'duty description',
        ],
        'shipping' => [
           'amount' => '4.26',
           'name' => 'level2 tax name',
           'description' => 'level2 tax',
        ],
        'poNumber' => '456654',
        'customer' => [
           'id' => '18',
           'email' => 'someone@blackhole.tv',
        ],
        'billTo' => [
           'firstName' => 'Ellen',
           'lastName' => 'Johnson',
           'company' => 'Souveniropolis',
           'address' => '14 Main Street',
           'city' => 'Pecan Springs',
           'state' => 'TX',
           'zip' => '44628',
           'country' => 'USA',
        ],
        'shipTo' => [
           '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' => [
            'setting' => [
                0 => [
                    'settingName' =>'allowPartialAuth',
                    'settingValue' => 'false'
                ],
                1 => [
                    'settingName' => 'duplicateWindow',
                    'settingValue' => '0'
                ],
                2 => [
                    'settingName' => 'emailCustomer',
                    'settingValue' => 'false'
                ],
                3 => [
                    'settingName' => 'recurringBilling',
                    'settingValue' => 'false'
                ],
                4 => [
                    'settingName' => 'testRequest',
                    'settingValue' => 'false'
                ]
            ])
        ],
        'userFields' => [
            'userField' => [
                0 => [
                    'name' => 'MerchantDefinedFieldName1',
                    'value' => 'MerchantDefinedFieldValue1',
                ],
                1 => [
                    'name' => 'favorite_color',
                    'value' => 'blue',
                ],
            ],
        ],
    ],
]);

if ($response->isSuccessful()) {
    echo $response->transactionResponse->authCode;
}

Create a Customer Profile

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->createCustomerProfileRequest([
        'profile' => [
        'merchantCustomerId' => '12345',
        'email' => 'user@example.com',
        'paymentProfiles' => [
            'billTo' => [
                'firstName' => 'John',
                'lastName' => 'Smith',
                'address' => '123 Main Street',
                'city' => 'Townsville',
                'state' => 'NJ',
                'zip' => '12345',
                'phoneNumber' => '800-555-1234'
            ],
            'payment' => [
                'creditCard' => [
                'cardNumber' => '4111111111111111',
                'expirationDate' => '2026-08',
                ],
            ],
        ],
        'shipToList' => [
            'firstName' => 'John',
            'lastName' => 'Smith',
            'address' => '123 Main Street',
            'city' => 'Townsville',
            'state' => 'NJ',
            'zip' => '12345',
            'phoneNumber' => '800-555-1234'
        ],
    ],
    'validationMode' => 'liveMode'
]);

if ($response->isSuccessful()) {
    echo $response->customerProfileId;
}

Create a Recurring Subscription

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->ARBCreateSubscriptionRequest([
    'refId' => 'Sample',
    'subscription' => [
        'name' => 'Sample subscription',
        'paymentSchedule' => [
            'interval' => [
                'length' => '1',
                'unit' => 'months'
            ],
            'startDate' => '2020-04-18',
            'totalOccurrences' => '12',
            'trialOccurrences' => '1'
        ],
        'amount' => '10.29',
        'trialAmount' => '0.00',
        'payment' => [
            'creditCard' => [
                'cardNumber' => '4111111111111111',
                'expirationDate' => '2016-08'
            ])
        ],
        'billTo' => [
            'firstName' => 'John',
            'lastName' => 'Smith'
        ]
    ]
]);

if ($response->isSuccessful()) {
    echo $response->subscriptionId;
}

Get a List of Settled Batches

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->getSettledBatchListRequest([
    'includeStatistics'   => 'true',
    'firstSettlementDate' => '2020-01-01T08:15:30',
    'lastSettlementDate'  => '2020-01-30T08:15:30',
]);

if ($response->isSuccessful()) {
    foreach ($response->batchList as $batch) {
        echo $batch->batchId;
    }
}

Get Transaction Detail From CIM API Calls

Some CIM API calls process an AUTH_CAPTURE transaction and return data similar to AIM AUTH_CAPTURE transactions. To access this information you can call AuthnetJsonResponse::getTransactionResponseField() using the field name or field number. For example, if you are looking for the transaction ID you can use:

$response->getTransactionResponseField('TransactionID');

or

$response->getTransactionResponseField(7);

Field name and number can be found in the Authorize.Net AIM Guide. Note that the field name has all spaces removed so TransactionID becomes TransactionID.

Create a Webhook

$response = $request->createWebhooks([
    "net.authorize.customer.subscription.expiring",
    "net.authorize.customer.subscription.suspended",
    "net.authorize.payment.authcapture.created",
    "net.authorize.payment.authorization.created",
    "net.authorize.payment.capture.created",
    "net.authorize.payment.fraud.approved",
    "net.authorize.payment.fraud.declined",
    "net.authorize.payment.fraud.held",
    "net.authorize.payment.priorAuthCapture.created",
    "net.authorize.payment.refund.created",
    "net.authorize.payment.void.created"
], 'http://www.example.com:55950/api/webhooks', 'active');

Validate and access a Webhook

$payload = file_get_contents("php://input");
$webhook = new AuthnetWebhook(AUTHNET_SIGNATURE, $payload);
if ($webhook->isValid()) {
    // Access notifcation values
    // echo $webhook->eventType;
}

If apache_request_headers()/getallheaders() are not available to you, you can will need to get the HTTP request

headers and pass them as the third parameter to `AuthnetWebhook()`.

$headers = yourGetHeadersFunction();
$payload = file_get_contents("php://input");
$webhook = new AuthnetWebhook(AUTHNET_SIGNATURE, $payload, $headers);
if ($webhook->isValid()) {
    // Access notifcation values
    // echo $webhook->eventType;
}

Accept.js

To see examples of an Accept.js powered self hosted payment form, an Authorize.Net hosted payment form, and a hosted customer profile page, visit the Accept.js examples directory.

Debugging

To assist with debugging the __toString() method has been overridden to output important elements pertaining to the usage of this library. Simple echo your AuthnetJSON object to see:

  • The API Login ID used
  • The API transaction Key used
  • The API endpoint the request was sent to
  • The request JSON
  • The response JSON

Basic Usage:

$request = AuthnetApiFactory::getJsonApiHandler(AUTHNET_LOGIN, AUTHNET_TRANSKEY);
$response = $request->getUnsettledTransactionListRequest();
echo $request, $response;

Support

If you require assistance using this library start by viewing the HELP.md file included in this package. It includes common problems and their solutions.

If you need additional assistance, I can be found at Stack Overflow. Be sure when you ask a question pertaining to the usage of this class be sure to tag your question with the PHP and Authorize.Net tags. Make sure you follow their guide for asking a good question as poorly asked questions will be closed and I will not be able to assist you.

Do not use Stack Overflow to report bugs. Bugs may be reported here.

  Files folder image Files  
File Role Description
Files folder image.github (1 directory)
Files folder imageexamples (8 directories)
Files folder imagesrc (2 directories)
Files folder imagetests (13 files)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file CHANGELOG Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file config.inc.php.dist Example Example script
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file HELP.md Data Auxiliary data
Accessible without login Plain text file license.txt Doc. Documentation
Accessible without login Plain text file phpdoc.xml Data Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Accessible without login Plain text file SECURITY.md Data Auxiliary data

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (1 file)

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file php.yml Data Auxiliary data

  Files folder image Files  /  examples  
File Role Description
Files folder imageacceptjs (3 files)
Files folder imageaim (18 files)
Files folder imagearb (16 files)
Files folder imagecim (23 files)
Files folder imagefraud (2 files)
Files folder imagereporting (8 files)
Files folder imagesim (1 file)
Files folder imagewebhooks (8 files)

  Files folder image Files  /  examples  /  acceptjs  
File Role Description
  Accessible without login Plain text file getHostedPaymentPageRequest.php Example Example script
  Accessible without login Plain text file getHostedProfilePageRequest.php Example Example script
  Accessible without login Plain text file selfHostedPaymentForm.php Example Example script

  Files folder image Files  /  examples  /  aim  
File Role Description
  Accessible without login Plain text file createTransactionRequest_authCapture.php Example Example script
  Accessible without login Plain text file createTransactionRequest_authOnly.php Example Example script
  Accessible without login Plain text file createTransactionRequest_captureOnly.php Example Example script
  Accessible without login Plain text file createTransactionRequest_partialAuth.php Example Example script
  Accessible without login Plain text file createTransactionR...ypalAuthCapture.php Example Example script
  Accessible without login Plain text file createTransactionR...CaptureContinue.php Example Example script
  Accessible without login Plain text file createTransactionR..._paypalAuthOnly.php Example Example script
  Accessible without login Plain text file createTransactionR...uthOnlyContinue.php Example Example script
  Accessible without login Plain text file createTransactionR...aypalGetDetails.php Example Example script
  Accessible without login Plain text file createTransactionR...riorAuthCapture.php Example Example script
  Accessible without login Plain text file createTransactionR...st_paypalRefund.php Example Example script
  Accessible without login Plain text file createTransactionRequest_paypalVoid.php Example Example script
  Accessible without login Plain text file createTransactionR...riorAuthCapture.php Example Example script
  Accessible without login Plain text file createTransactionRequest_refund.php Example Example script
  Accessible without login Plain text file createTransactionR...st_visaCheckout.php Example Example script
  Accessible without login Plain text file createTransactionRequest_void.php Example Example script
  Accessible without login Plain text file decryptPaymentDataRequest.php Example Example script
  Accessible without login Plain text file sendCustomerTransa...nReceiptRequest.php Example Example script

  Files folder image Files  /  examples  /  arb  
File Role Description
  Accessible without login Plain text file ARBCancelSubscriptionRequest.php Example Example script
  Accessible without login Plain text file ARBCreateSubscriptionRequest.php Example Example script
  Accessible without login Plain text file ARBCreateSubscript...uestFromProfile.php Example Example script
  Accessible without login Plain text file ARBCreateSubscript...uestFromProfile.php Example Example script
  Accessible without login Plain text file ARBCreateSubscript...uestFromProfile.php Example Example script
  Accessible without login Plain text file ARBCreateSubscript...uestFromProfile.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionListRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionListRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionListRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionListRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionRequest.php Example Example script
  Accessible without login Plain text file ARBGetSubscriptionStatusRequest.php Example Example script
  Accessible without login Plain text file ARBUpdateSubscriptionRequest.php Example Example script

  Files folder image Files  /  examples  /  cim  
File Role Description
  Accessible without login Plain text file createCustomerPaymentProfileRequest.php Example Example script
  Accessible without login Plain text file createCustomerProfileRequest.php Example Example script
  Accessible without login Plain text file createCustomerProf...iplePayAccounts.php Example Example script
  Accessible without login Plain text file createCustomerProf...est_authCapture.php Example Example script
  Accessible without login Plain text file createCustomerProf...equest_authOnly.php Example Example script
  Accessible without login Plain text file createCustomerProf...est_captureOnly.php Example Example script
  Accessible without login Plain text file createCustomerProf...riorAuthCapture.php Example Example script
  Accessible without login Plain text file createCustomerProf...nRequest_refund.php Example Example script
  Accessible without login Plain text file createCustomerProf...ionRequest_void.php Example Example script
  Accessible without login Plain text file createCustomerShippingAddressRequest.php Example Example script
  Accessible without login Plain text file deleteCustomerPaymentProfileRequest.php Example Example script
  Accessible without login Plain text file deleteCustomerProfileRequest.php Example Example script
  Accessible without login Plain text file deleteCustomerShippingAddressRequest.php Example Example script
  Accessible without login Plain text file getCustomerPaymentProfileRequest.php Example Example script
  Accessible without login Plain text file getCustomerProfileIdsRequest.php Example Example script
  Accessible without login Plain text file getCustomerProfileRequest.php Example Example script
  Accessible without login Plain text file getCustomerShippingAddressRequest.php Example Example script
  Accessible without login Plain text file getHostedProfilePageRequest.php Example Example script
  Accessible without login Plain text file updateCustomerPaymentProfileRequest.php Example Example script
  Accessible without login Plain text file updateCustomerProfileRequest.php Example Example script
  Accessible without login Plain text file updateCustomerShippingAddressRequest.php Example Example script
  Accessible without login Plain text file updateSplitTenderGroupRequest.php Example Example script
  Accessible without login Plain text file validateCustomerPa...tProfileRequest.php Example Example script

  Files folder image Files  /  examples  /  fraud  
File Role Description
  Accessible without login Plain text file getUnsettledTransactionListRequest.php Example Example script
  Accessible without login Plain text file updateHeldTransactionRequest.php Example Example script

  Files folder image Files  /  examples  /  reporting  
File Role Description
  Accessible without login Plain text file getAUJobDetailsRequest.php Example Example script
  Accessible without login Plain text file getAUJobSummaryRequest.php Example Example script
  Accessible without login Plain text file getBatchStatisticsRequest.php Example Example script
  Accessible without login Plain text file getMerchantDetailsRequest.php Example Example script
  Accessible without login Plain text file getSettledBatchListRequest.php Example Example script
  Accessible without login Plain text file getTransactionDetailsRequest.php Example Example script
  Accessible without login Plain text file getTransactionListRequest.php Example Example script
  Accessible without login Plain text file getUnsettledTransactionListRequest.php Example Example script

  Files folder image Files  /  examples  /  sim  
File Role Description
  Accessible without login Plain text file sim.php Example Example script

  Files folder image Files  /  examples  /  webhooks  
File Role Description
  Accessible without login Plain text file createWebhook.php Example Example script
  Accessible without login Plain text file deleteWebhook.php Example Example script
  Accessible without login Plain text file getEventTypes.php Example Example script
  Accessible without login Plain text file getWebhook.php Example Example script
  Accessible without login Plain text file listWebhooks.php Example Example script
  Accessible without login Plain text file notificationHistory.php Example Example script
  Accessible without login Plain text file ping.php Example Example script
  Accessible without login Plain text file updateWebhook.php Example Example script

  Files folder image Files  /  src  
File Role Description
Files folder imageauthnet (10 files)
Files folder imageexceptions (8 files)

  Files folder image Files  /  src  /  authnet  
File Role Description
  Plain text file AuthnetAcceptJs.php Class Class source
  Plain text file AuthnetApiFactory.php Class Class source
  Plain text file AuthnetJson.php Class Class source
  Plain text file AuthnetJsonRequest.php Class Class source
  Plain text file AuthnetJsonResponse.php Class Class source
  Plain text file AuthnetSim.php Class Class source
  Plain text file AuthnetWebhook.php Class Class source
  Plain text file AuthnetWebhooksRequest.php Class Class source
  Plain text file AuthnetWebhooksResponse.php Class Class source
  Plain text file TransactionResponse.php Class Class source

  Files folder image Files  /  src  /  exceptions  
File Role Description
  Plain text file AuthnetCannotSetParamsException.php Class Class source
  Plain text file AuthnetCurlException.php Class Class source
  Plain text file AuthnetException.php Class Class source
  Plain text file AuthnetInvalidAmountException.php Class Class source
  Plain text file AuthnetInvalidCredentialsException.php Class Class source
  Plain text file AuthnetInvalidJsonException.php Class Class source
  Plain text file AuthnetInvalidServerException.php Class Class source
  Plain text file AuthnetTransaction...seCallException.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file AuthnetApiFactoryTest.php Class Class source
  Plain text file AuthnetJsonAimPaypalTest.php Class Class source
  Plain text file AuthnetJsonAimTest.php Class Class source
  Plain text file AuthnetJsonArbTest.php Class Class source
  Plain text file AuthnetJsonCimTest.php Class Class source
  Plain text file AuthnetJsonReportingTest.php Class Class source
  Plain text file AuthnetJsonRequestTest.php Class Class source
  Plain text file AuthnetJsonResponseTest.php Class Class source
  Plain text file AuthnetSimTest.php Class Class source
  Plain text file AuthnetWebhooksRequestTest.php Class Class source
  Plain text file AuthnetWebhooksResponseTest.php Class Class source
  Plain text file AuthnetWebhookTest.php Class Class source
  Plain text file TransactionResponseTest.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 95%
Total:61
This week:0
All time:9,790
This week:324Up

For more information send a message to info at phpclasses dot org.