### Install Authorize.Net PHP SDK with Composer Source: https://context7.com/authorizenet/sdk-php/llms.txt Use Composer to install the SDK. Ensure your PHP version meets the requirements. Run 'composer update' after modifying composer.json. ```json { "require": { "php": ">=5.6", "authorizenet/authorizenet": "2.0.4" } } ``` -------------------------------- ### Composer Installation Configuration Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Add this to your composer.json file to specify the PHP version and the Authorize.Net SDK version for installation. ```json { "require": { "php": ">=5.6", "authorizenet/authorizenet": "2.0.3" } } ``` -------------------------------- ### AuthorizeNetAIM.php Legacy Example Source: https://github.com/authorizenet/sdk-php/blob/master/MIGRATING.md This is an example of the old AuthorizeNetAIM.php class usage for processing a sale. It requires defining API credentials and using the AuthorizeNetAIM object to perform an authorize and capture operation. ```php define("AUTHORIZENET_API_LOGIN_ID", "YOURLOGIN"); define("AUTHORIZENET_TRANSACTION_KEY", "YOURKEY"); define("AUTHORIZENET_SANDBOX", true); $sale = new AuthorizeNetAIM; $sale->amount = "5.99"; $sale->card_num = '6011000000000012'; $sale->exp_date = '04/15'; $response = $sale->authorizeAndCapture(); if ($response->approved) { $transaction_id = $response->transaction_id; } ``` -------------------------------- ### Include Autoloader Source: https://github.com/authorizenet/sdk-php/blob/master/doc/AIM.markdown Include the Composer autoloader to load SDK classes. Ensure Composer is installed and dependencies are managed. ```PHP require 'vendor/autoload.php'; ``` -------------------------------- ### Require Composer Autoloader Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Include this line in your main script or bootstrap file after installing the SDK via Composer to enable autoloading of classes. ```php require 'vendor/autoload.php'; ``` -------------------------------- ### Create Customer Profile Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown This snippet demonstrates how to create a new customer profile with payment profiles and shipping addresses using the AuthorizeNetCIM SDK. It includes examples of adding credit card and bank account details, as well as multiple shipping addresses. ```APIDOC ## Create Customer Profile ### Description Creates a new customer profile with associated payment profiles and shipping addresses. ### Method `createCustomerProfile` ### Parameters - **customerProfile** (AuthorizeNetCustomer) - Required - An object containing customer details, payment profiles, and shipping addresses. ### Request Example ```php $customerProfile = new AuthorizeNetCustomer; $customerProfile->description = "Description of customer"; $customerProfile->merchantCustomerId = 123; $customerProfile->email = "user@domain.com"; // Add payment profiles (credit card, bank account) $paymentProfile = new AuthorizeNetPaymentProfile; $paymentProfile->customerType = "individual"; $paymentProfile->payment->creditCard->cardNumber = "4111111111111111"; $paymentProfile->payment->creditCard->expirationDate = "2015-10"; $customerProfile->paymentProfiles[] = $paymentProfile; // Add shipping addresses $address = new AuthorizeNetAddress; $address->firstName = "john"; $address->lastName = "Doe"; $address->address = "1 Main Street"; $address->city = "Boston"; $address->state = "MA"; $address->zip = "02412"; $address->country = "USA"; $customerProfile->shipToList[] = $address; $request = new AuthorizeNetCIM; $response = $request->createCustomerProfile($customerProfile); ``` ### Response #### Success Response - **customerProfileId** (string) - The ID of the newly created customer profile. #### Response Example ```php $new_customer_id = $response->getCustomerProfileId(); // or $new_customer_id = $response->xpath('customerProfileId')[0]; ``` ``` -------------------------------- ### Charge Credit Card using AuthorizeNet SDK PHP Source: https://github.com/authorizenet/sdk-php/blob/master/MIGRATING.md Use this snippet to perform an authorization and capture transaction with a credit card. Ensure you have the SDK installed via Composer and replace placeholder credentials. ```php require 'vendor/autoload.php'; use net\authorize\api\contract\v1 as AnetAPI; use net\authorize\api\controller as AnetController; define("AUTHORIZENET_LOG_FILE", "phplog"); $merchantAuthentication = new AnetAPI\MerchantAuthenticationType(); $merchantAuthentication->setName("YOURLOGIN"); $merchantAuthentication->setTransactionKey("YOURKEY"); // Create the payment data for a credit card $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber("6011000000000012"); $creditCard->setExpirationDate("2015-04"); $creditCard->setCardCode("123"); // Add the payment data to a paymentType object $paymentOne = new AnetAPI\PaymentType(); $paymentOne->setCreditCard($creditCard); $transactionRequestType = new AnetAPI\TransactionRequestType(); $transactionRequestType->setTransactionType("authCaptureTransaction"); $transactionRequestType->setAmount("5.99"); $transactionRequestType->setPayment($paymentOne); // Assemble the complete transaction request $request = new AnetAPI\CreateTransactionRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setTransactionRequest($transactionRequestType); // Create the controller and get the response $controller = new AnetController\CreateTransactionController($request); $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX); if ($response != null) { // Check to see if the API request was successfully received and acted upon if ($response->getMessages()->getResultCode() == "Ok") { // Since the API request was successful, look for a transaction response // and parse it to display the results of authorizing the card $tresponse = $response->getTransactionResponse(); if ($tresponse != null && $tresponse->getMessages() != null) { echo " Successfully created transaction with Transaction ID: " . $tresponse->getTransId() . "\n"; echo " Transaction Response Code: " . $tresponse->getResponseCode() . "\n"; echo " Message Code: " . $tresponse->getMessages()[0]->getCode() . "\n"; echo " Auth Code: " . $tresponse->getAuthCode() . "\n"; echo " Description: " . $tresponse->getMessages()[0]->getDescription() . "\n"; } } } ``` -------------------------------- ### Get Settled Batch List Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Retrieves a list of settled batches. ```APIDOC ## Get Settled Batch List ### Description Retrieves a list of settled batches. ### Method Signature `getSettledBatchList(): SimpleXMLElement` ### Parameters None ### Request Example ```php $request = new AuthorizeNetTD; $response = $request->getSettledBatchList(); ``` ### Response #### Success Response Returns a SimpleXMLElement object containing the settled batch list. #### Response Example ```php // Accessing batch IDs $batches = $response->xpath("batchList/batch"); echo "Batch 1: " . $batches[0]->batchId; ``` ``` -------------------------------- ### Get Customer Profile IDs Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Retrieves a list of customer profile IDs. ```APIDOC ## Get Customer Profile IDs ### Description Retrieves a list of customer profile IDs. ### Method ```php $response = $request->getCustomerProfileIds(); ``` ``` -------------------------------- ### Test TLS 1.2 Connection Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Use this code to test if your PHP installation can connect to Authorize.Net servers using TLS 1.2. Examine the verbose output for connection details. ```php name = "Short subscription"; $subscription->intervalLength = "1"; $subscription->intervalUnit = "months"; $subscription->startDate = "2011-03-12"; $subscription->totalOccurrences = "14"; $subscription->amount = rand(1,100); $subscription->creditCardCardNumber = "6011000000000012"; $subscription->creditCardExpirationDate = "2018-10"; $subscription->creditCardCardCode = "123"; $subscription->billToFirstName = "john"; $subscription->billToLastName = "doe"; ``` -------------------------------- ### Get Settled Batch List Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Fetches a list of settled batches using the getSettledBatchList method. Allows access to batch information. ```PHP $request = new AuthorizeNetTD; $response = $request->getSettledBatchList(); $batches = $response->xpath("batchList/batch"); echo "Batch 1: {$batches[0]->batchId}"; ``` -------------------------------- ### Implement jsonSerialize for Subclasses in PHP Source: https://github.com/authorizenet/sdk-php/blob/master/scripts/appendJsonSerializeSubClassCode.txt Implement the `jsonSerialize` method to customize how an object is serialized to JSON. This example handles date and datetime objects, and conditionally formats arrays based on class metadata. Ensure the `Mapper` class is correctly configured. ```php #[\ReturnTypeWillChange] public function jsonSerialize(){ $values = array_filter((array)get_object_vars($this), function ($val){ return !is_null($val); }); $mapper = \net\authorize\util\Mapper::Instance(); foreach($values as $key => $value){ $classDetails = $mapper->getClass(get_class($this) , $key); if (isset($value)){ if ($classDetails->className === 'Date'){ $dateTime = $value->format('Y-m-d'); $values[$key] = $dateTime; } else if ($classDetails->className === 'DateTime'){ $dateTime = $value->format('Y-m-d\TH:i:s\Z'); $values[$key] = $dateTime; } if (is_array($value)){ if (!$classDetails->isInlineArray){ $subKey = $classDetails->arrayEntryname; $subArray = [$subKey => $value]; $values[$key] = $subArray; } } } } return array_merge(parent::jsonSerialize(), $values); } } ``` -------------------------------- ### Switch to Production Environment Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Use this code to switch the SDK from the default sandbox environment to the production environment for live transactions. ```php // For PRODUCTION use $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION); ``` -------------------------------- ### Initialize Merchant Authentication and API Endpoint Source: https://context7.com/authorizenet/sdk-php/llms.txt Include the autoloader, define API credentials, and set the environment endpoint. Replace placeholders with your actual API login ID and transaction key. Use ANetEnvironment::PRODUCTION for live transactions. ```php require 'vendor/autoload.php'; use net\authorize\api\contract\v1 as AnetAPI; use net\authorize\api\controller as AnetController; use net\authorize\api\constants\ANetEnvironment; // Build reusable merchant authentication (use constants or env vars in production) $merchantAuthentication = new AnetAPI\MerchantAuthenticationType(); $merchantAuthentication->setName("YOUR_API_LOGIN_ID"); $merchantAuthentication->setTransactionKey("YOUR_TRANSACTION_KEY"); // Sandbox endpoint for testing; swap to ANetEnvironment::PRODUCTION for live $endpoint = ANetEnvironment::SANDBOX; ``` -------------------------------- ### Create Customer Profile Object Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Instantiate and populate an AuthorizeNetCustomer object with basic customer details. ```PHP $customerProfile = new AuthorizeNetCustomer; $customerProfile->description = "Description of customer"; $customerProfile->merchantCustomerId = 123; $customerProfile->email = "user@domain.com"; ``` -------------------------------- ### Get Transactions for Day Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Helper method to retrieve all transactions for a specific day. ```APIDOC ## Get Transactions for Day ### Description Helper method to retrieve all transactions for a specific day. If no parameters are provided, it defaults to the current day. ### Method Signature `getTransactionsForDay(int $month, int $day, ?int $year = false): SimpleXMLElement` ### Parameters #### Query Parameters - **month** (int) - Required - The month of the day for which to retrieve transactions. - **day** (int) - Required - The day of the month for which to retrieve transactions. - **year** (int) - Optional - The year for which to retrieve transactions. Defaults to the current year if not provided. ### Request Example ```php // Get transactions for today $request = new AuthorizeNetTD; $response = $request->getTransactionsForDay(date('m'), date('d')); // Get transactions for a specific day $response = $request->getTransactionsForDay(10, 26, 2023); ``` ### Response #### Success Response Returns a SimpleXMLElement object containing the transactions for the specified day. ``` -------------------------------- ### Create Customer Profile Request Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Instantiate the AuthorizeNetCIM object and call the createCustomerProfile method with the populated customer profile. ```PHP $request = new AuthorizeNetCIM; $response = $request->createCustomerProfile($customerProfile); ``` -------------------------------- ### Initialize Logger Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Initialize the logger using LogFactory. The logger generates logs with sensitive data masked. ```php use \net\authorize\util\LogFactory; $logger = LogFactory::getLog(get_class($this)); ``` -------------------------------- ### Get Transaction List Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Retrieves a list of transactions for a given batch ID. ```APIDOC ## Get Transaction List ### Description Retrieves a list of transactions for a given batch ID. ### Method Signature `getTransactionList(string $batch_id): SimpleXMLElement` ### Parameters #### Path Parameters - **batch_id** (string) - Required - The ID of the batch to retrieve transactions from. ### Request Example ```php $request = new AuthorizeNetTD; $response = $request->getTransactionList($batch_id); ``` ### Response #### Success Response Returns a SimpleXMLElement object containing the list of transactions. #### Response Example ```php // Accessing transactions $transactions = $response->xpath("transactions/transaction"); ``` ``` -------------------------------- ### Get Transaction Details Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Retrieves the details for a specific transaction using its ID. ```APIDOC ## Get Transaction Details ### Description Retrieves the details for a specific transaction using its ID. ### Method Signature `getTransactionDetails(string $transId): SimpleXMLElement` ### Parameters #### Path Parameters - **transId** (string) - Required - The ID of the transaction to retrieve. ### Request Example ```php $request = new AuthorizeNetTD; $response = $request->getTransactionDetails($transId); ``` ### Response #### Success Response Returns a SimpleXMLElement object containing the transaction details. #### Response Example ```php // Accessing the authorization amount $response->xml->transaction->authAmount ``` ``` -------------------------------- ### Get Customer Profile IDs Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Retrieve a list of all customer profile IDs associated with the merchant account. ```PHP $response = $request->getCustomerProfileIds(); ``` -------------------------------- ### Create Customer Profile with Validation Mode Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Enable validation mode during customer profile creation by passing 'testMode' as a parameter to createCustomerProfile. ```PHP $response = $request->createCustomerProfile($customerProfile, "testMode"); ``` -------------------------------- ### Get Transaction List Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Retrieves a list of transactions for a given batch ID using the getTransactionList method. ```PHP $request = new AuthorizeNetTD; $response = $request->getTransactionList($batch_id); $transactions = $response->xpath("transactions/transaction") ``` -------------------------------- ### Get Subscription Status Source: https://github.com/authorizenet/sdk-php/blob/master/doc/ARB.markdown Retrieves the current status of a specific recurring billing subscription using its ID. ```APIDOC ## Get Subscription Status ### Description Retrieves the current status of a specific recurring billing subscription. ### Method ```php $status_request = new AuthorizeNetARB; $status_response = $status_request->getSubscriptionStatus($subscription_id); ``` ### Parameters - **$subscription_id** (string) - Required - The ID of the subscription whose status is to be retrieved. ``` -------------------------------- ### ARBCreateSubscriptionController Source: https://context7.com/authorizenet/sdk-php/llms.txt Sets up an Automated Recurring Billing (ARB) subscription that charges a payment method on a schedule. Supports monthly, daily, and other interval units with optional trial periods. ```APIDOC ## ARBCreateSubscriptionController — Create a Recurring Subscription Sets up an Automated Recurring Billing (ARB) subscription that charges a payment method on a schedule. Supports monthly, daily, and other interval units with optional trial periods. ```php use net\authorize\api\contract\v1 as AnetAPI; use net\authorize\api\controller as AnetController; use net\authorize\api\constants\ANetEnvironment; // Payment schedule $interval = new AnetAPI\PaymentScheduleType\IntervalAType(); $interval->setLength("1"); $interval->setUnit("months"); $paymentSchedule = new AnetAPI\PaymentScheduleType(); $paymentSchedule->setInterval($interval); $paymentSchedule->setStartDate(new \DateTime("2024-02-01")); $paymentSchedule->setTotalOccurrences("12"); // 12 months $paymentSchedule->setTrialOccurrences("2"); // 2 trial months // Credit card for billing $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber("4111111111111111"); $creditCard->setExpirationDate("2038-12"); $payment = new AnetAPI\PaymentType(); $payment->setCreditCard($creditCard); // Billing name $billTo = new AnetAPI\NameAndAddressType(); $billTo->setFirstName("John"); $billTo->setLastName("Doe"); // Build the subscription $subscription = new AnetAPI\ARBSubscriptionType(); $subscription->setName("Monthly Premium Plan"); $subscription->setPaymentSchedule($paymentSchedule); $subscription->setAmount("29.99"); $subscription->setTrialAmount("0.00"); $subscription->setPayment($payment); $subscription->setBillTo($billTo); $request = new AnetAPI\ARBCreateSubscriptionRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setRefId("ref" . time()); $request->setSubscription($subscription); $controller = new AnetController\ARBCreateSubscriptionController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { echo "Subscription ID: " . $response->getSubscriptionId() . "\n"; // Expected output: Subscription ID: 6931209 } ``` ``` -------------------------------- ### Set Transaction Endpoint Source: https://github.com/authorizenet/sdk-php/blob/master/doc/AIM.markdown Configure the SDK to use the live Authorize.Net gateway or the test server by defining the AUTHORIZENET_SANDBOX constant. Manual setting per request is also possible. ```PHP define("AUTHORIZENET_SANDBOX", false); ``` ```PHP define("AUTHORIZENET_SANDBOX", true); ``` ```PHP $sale->setSandbox(false); ``` -------------------------------- ### Use Separate Credentials for Environments Source: https://context7.com/authorizenet/sdk-php/llms.txt Configure distinct merchant credentials (API Login ID and Transaction Key) based on whether you are targeting the production or sandbox environment. This is crucial for security and proper API access. ```php // Use separate credentials for each environment: $merchantAuthentication = new AnetAPI\MerchantAuthenticationType(); if ($isProd) { $merchantAuthentication->setName(getenv("PROD_API_LOGIN_ID")); $merchantAuthentication->setTransactionKey(getenv("PROD_TRANSACTION_KEY")); $endpoint = ANetEnvironment::PRODUCTION; } else { $merchantAuthentication->setName(getenv("SANDBOX_API_LOGIN_ID")); $merchantAuthentication->setTransactionKey(getenv("SANDBOX_TRANSACTION_KEY")); $endpoint = ANetEnvironment::SANDBOX; } ``` -------------------------------- ### Get Settled Batch List for Month Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Helper method to retrieve all settled batch lists for a specific month. ```APIDOC ## Get Settled Batch List for Month ### Description Helper method to retrieve all settled batch lists for a specific month. If no parameters are provided, it defaults to the current month. ### Method Signature `getSettledBatchListForMonth(int $month, ?int $year = false): SimpleXMLElement` ### Parameters #### Query Parameters - **month** (int) - Required - The month for which to retrieve settled batch lists. - **year** (int) - Optional - The year for which to retrieve settled batch lists. Defaults to the current year if not provided. ### Request Example ```php // Get settled batch lists for the current month $request = new AuthorizeNetTD; $response = $request->getSettledBatchListForMonth(date('m')); // Get settled batch lists for a specific month and year $response = $request->getSettledBatchListForMonth(11, 2023); ``` ### Response #### Success Response Returns a SimpleXMLElement object containing the settled batch lists for the specified month. ``` -------------------------------- ### Get Transaction Details Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Retrieves specific transaction details using the getTransactionDetails method. Requires a transaction ID. ```PHP $request = new AuthorizeNetTD; $response = $request->getTransactionDetails($transId); echo "Amount: {$response->xml->transaction->authAmount}"; ``` -------------------------------- ### Custom SPL Autoloader Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Use this require statement if you are not using Composer and have manually included the SDK's vendor directory. This assumes the SDK is located at 'path/to/anet_php_sdk/'. ```php require 'path/to/anet_php_sdk/autoload.php'; ``` -------------------------------- ### Import API Contract Namespace Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Import the necessary namespace for Authorize.Net API contracts. ```php use net\authorize\api\contract\v1 as AnetAPI; ``` -------------------------------- ### Get ARB Subscription Status Source: https://context7.com/authorizenet/sdk-php/llms.txt Retrieves the current status of an existing recurring billing subscription using its subscription ID. Requires merchant authentication. ```php $request = new AnetAPI\ARBGetSubscriptionStatusRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setSubscriptionId("6931209"); $controller = new AnetController\ARBGetSubscriptionStatusController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { echo "Status: " . $response->getStatus() . "\n"; // active, suspended, canceled, expired, etc. } ``` -------------------------------- ### Get Subscription Status Source: https://github.com/authorizenet/sdk-php/blob/master/doc/ARB.markdown Retrieve the current status of a subscription using its ID. Instantiate AuthorizeNetARB and call getSubscriptionStatus with the subscription ID. This is useful for monitoring active subscriptions. ```PHP $status_request = new AuthorizeNetARB; $status_response = $status_request->getSubscriptionStatus($subscription_id); ``` -------------------------------- ### Add Payment and Shipping Profiles to Customer Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Add payment profiles (credit card and bank account) and shipping addresses to an existing customer profile object. ```PHP // Add payment profile. $paymentProfile = new AuthorizeNetPaymentProfile; $paymentProfile->customerType = "individual"; $paymentProfile->payment->creditCard->cardNumber = "4111111111111111"; $paymentProfile->payment->creditCard->expirationDate = "2015-10"; $customerProfile->paymentProfiles[] = $paymentProfile; // Add another payment profile. $paymentProfile2 = new AuthorizeNetPaymentProfile; $paymentProfile2->customerType = "business"; $paymentProfile2->payment->bankAccount->accountType = "businessChecking"; $paymentProfile2->payment->bankAccount->routingNumber = "121042882"; $paymentProfile2->payment->bankAccount->accountNumber = "123456789123"; $paymentProfile2->payment->bankAccount->nameOnAccount = "Jane Doe"; $paymentProfile2->payment->bankAccount->echeckType = "WEB"; $paymentProfile2->payment->bankAccount->bankName = "Pandora Bank"; $customerProfile->paymentProfiles[] = $paymentProfile2; // Add shipping address. $address = new AuthorizeNetAddress; $address->firstName = "john"; $address->lastName = "Doe"; $address->company = "John Doe Company"; $address->address = "1 Main Street"; $address->city = "Boston"; $address->state = "MA"; $address->zip = "02412"; $address->country = "USA"; $address->phoneNumber = "555-555-5555"; $address->faxNumber = "555-555-5556"; $customerProfile->shipToList[] = $address; // Add another shipping address. $address2 = new AuthorizeNetAddress; $address2->firstName = "jane"; $address2->lastName = "Doe"; $address2->address = "11 Main Street"; $address2->city = "Boston"; $address2->state = "MA"; $address2->zip = "02412"; $address2->country = "USA"; $address2->phoneNumber = "555-512-5555"; $address2->faxNumber = "555-523-5556"; $customerProfile->shipToList[] = $address2; ``` -------------------------------- ### Log Using Formatting Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Log messages with formatted strings, including integers, floats, and XML requests. ```php $logger->debugFormat("Integer: %d, Float: %f, Xml-Request: %s\n", array(100, 1.29f, $xmlRequest)); ``` -------------------------------- ### Enable Partial Authorization Source: https://github.com/authorizenet/sdk-php/blob/master/doc/AIM.markdown Enable partial authorization transactions by setting the allow_partial_auth flag to true. This allows for transactions where the authorized amount may be less than the requested amount. ```PHP $sale->allow_partial_auth = true; ``` -------------------------------- ### Get Merchant Details Source: https://context7.com/authorizenet/sdk-php/llms.txt Retrieves details about the merchant account, including supported card types, currencies, and processor features. Ensure the merchant authentication object is properly configured. ```php $request = new AnetAPI\GetMerchantDetailsRequest(); $request->setMerchantAuthentication($merchantAuthentication); $controller = new AnetController\GetMerchantDetailsController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { echo "Merchant Name: " . $response->getMerchantName() . "\n"; echo "Gateway ID: " . $response->getGatewayId() . "\n"; foreach ($response->getPaymentMethods() as $method) { echo "Payment Method: " . $method . "\n"; } // Expected output: // Merchant Name: Test Account // Gateway ID: 1234567 // Payment Method: Visa // Payment Method: MasterCard } ``` -------------------------------- ### Helper Methods for Date-Based Transaction Retrieval Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Provides helper methods to retrieve all transactions for a specific day or all settled batches for a month. Defaults to the current date if no parameters are provided. ```PHP getTransactionsForDay($month, $day, $year = false) getSettledBatchListForMonth($month , $year) ``` -------------------------------- ### Set API Credentials Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Set your API Login ID and Transaction Key for authentication. It is recommended to store these in a constants file rather than directly in your code for security. ```php $merchantAuthentication = new AnetAPI\MerchantAuthenticationType(); $merchantAuthentication->setName("YOURLOGIN"); $merchantAuthentication->setTransactionKey("YOURKEY"); ``` -------------------------------- ### Create ARB Subscription Source: https://context7.com/authorizenet/sdk-php/llms.txt Sets up an Automated Recurring Billing (ARB) subscription. Configure payment schedule, amount, and billing details. Requires merchant authentication and API credentials. ```php use net\authorize\api\contract\v1 as AnetAPI; use net\authorize\api\controller as AnetController; use net\authorize\api\constants\ANetEnvironment; // Payment schedule $interval = new AnetAPI\PaymentScheduleType\IntervalAType(); $interval->setLength("1"); $interval->setUnit("months"); $paymentSchedule = new AnetAPI\PaymentScheduleType(); $paymentSchedule->setInterval($interval); $paymentSchedule->setStartDate(new \DateTime("2024-02-01")); $paymentSchedule->setTotalOccurrences("12"); // 12 months $paymentSchedule->setTrialOccurrences("2"); // 2 trial months // Credit card for billing $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber("4111111111111111"); $creditCard->setExpirationDate("2038-12"); $payment = new AnetAPI\PaymentType(); $payment->setCreditCard($creditCard); // Billing name $billTo = new AnetAPI\NameAndAddressType(); $billTo->setFirstName("John"); $billTo->setLastName("Doe"); // Build the subscription $subscription = new AnetAPI\ARBSubscriptionType(); $subscription->setName("Monthly Premium Plan"); $subscription->setPaymentSchedule($paymentSchedule); $subscription->setAmount("29.99"); $subscription->setTrialAmount("0.00"); $subscription->setPayment($payment); $subscription->setBillTo($billTo); $request = new AnetAPI\ARBCreateSubscriptionRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setRefId("ref" . time()); $request->setSubscription($subscription); $controller = new AnetController\ARBCreateSubscriptionController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { echo "Subscription ID: " . $response->getSubscriptionId() . "\n"; // Expected output: Subscription ID: 6931209 } ``` -------------------------------- ### Log XML Strings Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Log an XML string using the debug level. ```php $logger->debug($xmlRequest); ``` -------------------------------- ### Verify TLS Version Support Source: https://github.com/authorizenet/sdk-php/blob/master/README.md This snippet helps determine the TLS version your connection supports by querying howsmyssl.com. It decodes the JSON response to display the TLS version used. ```php tls_version ."\n"; ``` -------------------------------- ### Create Customer Profile Transaction Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Initiate a transaction (e.g., AuthCapture) using customer profile details. This includes setting transaction amount, customer IDs, and line item details. Ensure all required transaction and line item fields are correctly populated. ```PHP // Create Auth & Capture Transaction $transaction = new AuthorizeNetTransaction; $transaction->amount = "9.79"; $transaction->customerProfileId = $customerProfileId; $transaction->customerPaymentProfileId = $paymentProfileId; $transaction->customerShippingAddressId = $customerAddressId; $lineItem = new AuthorizeNetLineItem; $lineItem->itemId = "4"; $lineItem->name = "Cookies"; $lineItem->description = "Chocolate Chip"; $lineItem->quantity = "4"; $lineItem->unitPrice = "1.00"; $lineItem->taxable = "true"; $lineItem2 = new AuthorizeNetLineItem; $lineItem2->itemId = "4"; $lineItem2->name = "Cookies"; $lineItem2->description= "Peanut Butter"; $lineItem2->quantity = "4"; $lineItem2->unitPrice = "1.00"; $lineItem2->taxable = "true"; $transaction->lineItems[] = $lineItem; $transaction->lineItems[] = $lineItem2; $response = $request->createCustomerProfileTransaction("AuthCapture", $transaction); $transactionResponse = $response->getTransactionResponse(); $transactionId = $transactionResponse->transaction_id; ``` -------------------------------- ### GetCustomerProfileController Source: https://context7.com/authorizenet/sdk-php/llms.txt Fetches a stored customer profile and all associated payment profiles and shipping addresses. ```APIDOC ## `GetCustomerProfileController` — Retrieve a Customer Profile Fetches a stored customer profile and all associated payment profiles and shipping addresses. ```php $request = new AnetAPI\GetCustomerProfileRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setCustomerProfileId("1813900410"); $controller = new AnetController\GetCustomerProfileController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { $profile = $response->getProfile(); echo "Email: " . $profile->getEmail() . "\n"; foreach ($profile->getPaymentProfiles() as $pp) { echo "Payment Profile ID: " . $pp->getCustomerPaymentProfileId() . "\n"; echo "Card last 4: " . $pp->getPayment()->getCreditCard()->getCardNumber() . "\n"; // Returns masked card, e.g., XXXX1111 } } ``` ``` -------------------------------- ### Create Customer Profile (CIM) in PHP Source: https://context7.com/authorizenet/sdk-php/llms.txt Stores a customer's payment and shipping information securely in the Authorize.Net CIM vault. Returns a profile ID for future transactions without re-entering card data. Ensure the merchant authentication object is properly configured. ```php // Payment profile (credit card) $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber("4111111111111111"); $creditCard->setExpirationDate("2038-12"); $creditCard->setCardCode("123"); $paymentCreditCard = new AnetAPI\PaymentType(); $paymentCreditCard->setCreditCard($creditCard); $paymentProfile = new AnetAPI\CustomerPaymentProfileType(); $paymentProfile->setCustomerType("individual"); $paymentProfile->setPayment($paymentCreditCard); // Shipping address $shippingAddress = new AnetAPI\CustomerAddressType(); $shippingAddress->setFirstName("Jane"); $shippingAddress->setLastName("Doe"); $shippingAddress->setAddress("123 Main St"); $shippingAddress->setCity("Boston"); $shippingAddress->setState("MA"); $shippingAddress->setZip("02101"); $shippingAddress->setCountry("USA"); // Customer profile $customerProfile = new AnetAPI\CustomerProfileType(); $customerProfile->setDescription("Jane Doe - VIP customer"); $customerProfile->setMerchantCustomerId("cust_" . time()); $customerProfile->setEmail("jane.doe@example.com"); $customerProfile->setPaymentProfiles([$paymentProfile]); $customerProfile->setShipToList([$shippingAddress]); $request = new AnetAPI\CreateCustomerProfileRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setProfile($customerProfile); $request->setValidationMode("testMode"); // or "liveMode" $controller = new AnetController\CreateCustomerProfileController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { $customerProfileId = $response->getCustomerProfileId(); $paymentProfileIds = $response->getCustomerPaymentProfileIdList(); echo "Customer Profile ID: $customerProfileId\n"; echo "Payment Profile ID: " . $paymentProfileIds[0] . "\n"; // Expected output: // Customer Profile ID: 1813900410 // Payment Profile ID: 1808053161 } ``` -------------------------------- ### Retrieve Customer Profile Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Call the getCustomerProfile method with a customer profile ID to fetch profile details. ```PHP $response = $request->getCustomerProfile($customerProfileId); ``` -------------------------------- ### CreateCustomerPaymentProfileController Source: https://context7.com/authorizenet/sdk-php/llms.txt Adds a new payment method to an existing customer profile. ```APIDOC ## `CreateCustomerPaymentProfileController` — Add a Payment Profile Adds a new payment method to an existing customer profile. ```php $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber("5424000000000015"); $creditCard->setExpirationDate("2040-01"); $payment = new AnetAPI\PaymentType(); $payment->setCreditCard($creditCard); $paymentProfile = new AnetAPI\CustomerPaymentProfileType(); $paymentProfile->setCustomerType("individual"); $paymentProfile->setPayment($payment); $request = new AnetAPI\CreateCustomerPaymentProfileRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setCustomerProfileId("1813900410"); $request->setPaymentProfile($paymentProfile); $request->setValidationMode("testMode"); $controller = new AnetController\CreateCustomerPaymentProfileController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { echo "New Payment Profile ID: " . $response->getCustomerPaymentProfileId() . "\n"; } ``` ``` -------------------------------- ### CreateCustomerProfileController Source: https://context7.com/authorizenet/sdk-php/llms.txt Stores a customer's payment and shipping information securely in the Authorize.Net CIM vault, returning a profile ID for future transactions without re-entering card data. ```APIDOC ## `CreateCustomerProfileController` — Create a Customer Profile (CIM) Stores a customer's payment and shipping information securely in the Authorize.Net Customer Information Manager (CIM) vault, returning a profile ID for future transactions without re-entering card data. ```php // Payment profile (credit card) $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber("4111111111111111"); $creditCard->setExpirationDate("2038-12"); $creditCard->setCardCode("123"); $paymentCreditCard = new AnetAPI\PaymentType(); $paymentCreditCard->setCreditCard($creditCard); $paymentProfile = new AnetAPI\CustomerPaymentProfileType(); $paymentProfile->setCustomerType("individual"); $paymentProfile->setPayment($paymentCreditCard); // Shipping address $shippingAddress = new AnetAPI\CustomerAddressType(); $shippingAddress->setFirstName("Jane"); $shippingAddress->setLastName("Doe"); $shippingAddress->setAddress("123 Main St"); $shippingAddress->setCity("Boston"); $shippingAddress->setState("MA"); $shippingAddress->setZip("02101"); $shippingAddress->setCountry("USA"); // Customer profile $customerProfile = new AnetAPI\CustomerProfileType(); $customerProfile->setDescription("Jane Doe - VIP customer"); $customerProfile->setMerchantCustomerId("cust_" . time()); $customerProfile->setEmail("jane.doe@example.com"); $customerProfile->setPaymentProfiles([$paymentProfile]); $customerProfile->setShipToList([$shippingAddress]); $request = new AnetAPI\CreateCustomerProfileRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setProfile($customerProfile); $request->setValidationMode("testMode"); // or "liveMode" $controller = new AnetController\CreateCustomerProfileController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { $customerProfileId = $response->getCustomerProfileId(); $paymentProfileIds = $response->getCustomerPaymentProfileIdList(); echo "Customer Profile ID: $customerProfileId\n"; echo "Payment Profile ID: " . $paymentProfileIds[0] . "\n"; // Expected output: // Customer Profile ID: 1813900410 // Payment Profile ID: 1808053161 } ``` ``` -------------------------------- ### Create Customer Payment Profile Source: https://github.com/authorizenet/sdk-php/blob/master/doc/CIM.markdown Creates a new payment profile for an existing customer. ```APIDOC ## Create Customer Payment Profile ### Description Creates a new payment profile for an existing customer. ### Method ```php $response = $request->createCustomerPaymentProfile($customerProfileId, $paymentProfile); ``` ``` -------------------------------- ### Create Subscription Request Source: https://github.com/authorizenet/sdk-php/blob/master/doc/ARB.markdown Use the AuthorizeNetARB class to create a subscription request. Pass the populated subscription object to the createSubscription method. This is used for initiating new recurring billing subscriptions. ```PHP $request = new AuthorizeNetARB; $response = $request->createSubscription($subscription); ``` -------------------------------- ### Accessing Transaction Details via XPath Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Shows how to retrieve a list of batches from the AuthorizeNetTD response using XPath queries. ```PHP $batches = $response->xpath("batchList/batch"); ``` -------------------------------- ### List Transactions in a Batch Source: https://context7.com/authorizenet/sdk-php/llms.txt Retrieve all transactions belonging to a specific settled batch. Supports sorting and pagination. Requires merchant authentication and a batch ID. ```php $sorting = new AnetAPI\TransactionListSortingType(); $sorting->setOrderBy("id"); $sorting->setOrderDescending(false); $paging = new AnetAPI\PagingType(); $paging->setLimit(25); $paging->setOffset(1); $request = new AnetAPI\GetTransactionListRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setBatchId("8290955"); $request->setSorting($sorting); $request->setPaging($paging); $controller = new AnetController\GetTransactionListController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { foreach ($response->getTransactions() as $tx) { echo "Trans ID: " . $tx->getTransId() . " | "; echo "Amount: " . $tx->getSettleAmount() . " | "; echo "Status: " . $tx->getTransactionStatus() . "\n"; } } ``` -------------------------------- ### Accessing Transaction Details via SimpleXML Source: https://github.com/authorizenet/sdk-php/blob/master/doc/TD.markdown Demonstrates accessing specific transaction details using the SimpleXML object provided by the AuthorizeNetTD response. ```PHP $response->xml->transaction->payment->creditCard->cardType ``` -------------------------------- ### Create Transaction Request with Merchant Authentication Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Create a new transaction request and set the merchant authentication details. ```php $request = new AnetAPI\CreateTransactionRequest(); $request->setMerchantAuthentication($merchantAuthentication); ``` -------------------------------- ### List Settled Batches Source: https://context7.com/authorizenet/sdk-php/llms.txt Retrieve a list of settled payment batches within a specified date range. Optionally include statistics for each batch. Requires merchant authentication and valid date range. ```php $request = new AnetAPI\GetSettledBatchListRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setIncludeStatistics(true); $request->setFirstSettlementDate(new \DateTime("2024-01-01T00:00:00")); $request->setLastSettlementDate(new \DateTime("2024-01-31T23:59:59")); $controller = new AnetController\GetSettledBatchListController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { foreach ($response->getBatchList() as $batch) { echo "Batch ID: " . $batch->getBatchId() . "\n"; echo "Settlement State: " . $batch->getSettlementState() . "\n"; echo "Settlement Time: " . $batch->getSettlementTimeUTC()->format('Y-m-d H:i:s') . "\n"; foreach ($batch->getStatistics() as $stat) { echo " Count: " . $stat->getCount() . ", Amount: " . $stat->getChargeAmount() . "\n"; } } } ``` -------------------------------- ### Create Subscription Source: https://github.com/authorizenet/sdk-php/blob/master/doc/ARB.markdown Creates a new recurring billing subscription. You first construct a subscription object with all the necessary details and then pass it to the createSubscription method of the AuthorizeNetARB object. ```APIDOC ## Create Subscription ### Description Creates a new recurring billing subscription. ### Method ```php $request = new AuthorizeNetARB; $response = $request->createSubscription($subscription); ``` ### Parameters - **$subscription** (AuthorizeNet_Subscription) - Required - An object containing the details of the subscription to be created. ``` -------------------------------- ### Switch API Endpoint Source: https://context7.com/authorizenet/sdk-php/llms.txt Change the endpoint constant to switch between sandbox, production, or a custom API environment. The default for testing is the sandbox environment. ```php // Sandbox (default for testing) — https://apitest.authorize.net $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); ``` ```php // Production — https://api2.authorize.net $response = $controller->executeWithApiResponse(ANetEnvironment::PRODUCTION); ``` ```php // Custom endpoint (e.g., proxy or private environment) $response = $controller->executeWithApiResponse("https://my-custom-endpoint.example.com"); ``` -------------------------------- ### Retrieve Customer Profile (CIM) in PHP Source: https://context7.com/authorizenet/sdk-php/llms.txt Fetches a stored customer profile and all associated payment profiles and shipping addresses. Requires the customer profile ID to be provided in the request. ```php $request = new AnetAPI\GetCustomerProfileRequest(); $request->setMerchantAuthentication($merchantAuthentication); $request->setCustomerProfileId("1813900410"); $controller = new AnetController\GetCustomerProfileController($request); $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX); if ($response !== null && $response->getMessages()->getResultCode() === "Ok") { $profile = $response->getProfile(); echo "Email: " . $profile->getEmail() . "\n"; foreach ($profile->getPaymentProfiles() as $pp) { echo "Payment Profile ID: " . $pp->getCustomerPaymentProfileId() . "\n"; echo "Card last 4: " . $pp->getPayment()->getCreditCard()->getCardNumber() . "\n"; // Returns masked card, e.g., XXXX1111 } } ``` -------------------------------- ### Log a String Message Source: https://github.com/authorizenet/sdk-php/blob/master/README.md Log a simple string message using the debug level. ```php $logger->debug("Sending 'XML' Request type"); ```