Giter Club home page Giter Club logo

sdk-php's Introduction

Authorize.Net PHP SDK

[Travis] (https://travis-ci.org/AuthorizeNet/sdk-php) Scrutinizer Code Quality Packagist

License

Proprietary, see the provided license.md.

Requirements

  • PHP 5.3+ (>=5.3.10 recommended)
  • cURL PHP Extension
  • JSON PHP Extension
  • SimpleXML PHP Extension
  • An Authorize.Net Merchant Account or Sandbox Account. You can get a free sandbox account at http://developer.authorize.net/sandbox/

Autoloading

Composer currently has a MITM security vulnerability. However, if you wish to use it, require its autoloader in your script or bootstrap file:

require 'vendor/autoload.php';

Note: you'll need a composer.json file with the following require section and to run composer update.

{
  "require": {
  "php": ">=5.2.0",
  "ext-curl": "*",
  "authorizenet/authorizenet": "1.8.8",
  "jms/serializer": "xsd2php-dev as 0.18.0"
},
"require-dev": {
  "goetas/xsd2php": "2.*@dev",
  "goetas/xsd-reader": "2.*@dev"
},
"repositories": [{
    "type": "vcs",
    "url": "https://github.com/goetas/serializer.git"
    }]

}

Alternatively, we provide a custom SPL autoloader:

require 'path/to/anet_php_sdk/autoload.php';

Issue with PHP 7: You may get below error when run the composer update with PHP 7. To get rid of this error, use composer update --ignore-platform-reqs

Problem 1
    - Installation request for authorizenet/authorizenet 1.8.6.2 -> satisfiable
by authorizenet/authorizenet[1.8.6.2].
    - authorizenet/authorizenet 1.8.6.2 requires php ~5.3 -> your PHP version (7
.0.3RC1) or value of "config.platform.php" in composer.json does not satisfy that requirement.

Authentication

To authenticate with the Authorize.Net API you will need to retrieve your API Login ID and Transaction Key from the Merchant Interface. You can find these details in the Settings section. If you need a sandbox account you can sign up for one really easily here.

Once you have your keys simply plug them into the appropriate variables, as per the below code dealing with the authentication part of the flow.

...

use net\authorize\api\contract\v1 as AnetAPI;

...

$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("YOURLOGIN");
$merchantAuthentication->setTransactionKey("YOURKEY");

...

$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);

...

Usage Examples

Apart from this README, you can find details and examples of using the SDK in the following places:

Quick Usage Example (with Charge Credit Card - Authorize and Capture)

Note: The following is a php console application. Ensure that you can invoke the php command from command line.

  • Save the below code to a php file named, say, charge-credit-card.php
  • Open command prompt and navigate to your sdk folder ( if want to run from a different folder, modify the require statement to have the full path to the sdk e.g. require 'c:/anet-sdk-php/vendor/autoload.php' in place of require 'vendor/autoload.php' )
  • Update dependecies - e.g., With composer, type composer update
  • Type php [<path to folder containing the php file>\]charge-credit-card.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");

// Common setup for API credentials
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("556KThWQ6vf2");
$merchantAuthentication->setTransactionKey("9ac2932kQ7kN2Wzq");

// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber("4111111111111111");
$creditCard->setExpirationDate("2038-12");
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);

// Create a transaction
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType( "authCaptureTransaction"); 
$transactionRequestType->setAmount(151.51);
$transactionRequestType->setPayment($paymentOne);

$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setTransactionRequest( $transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);

if ($response != null)
{
	$tresponse = $response->getTransactionResponse();

	if (($tresponse != null) && ($tresponse->getResponseCode()=="1") )   
	{
		echo "Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() . "\n";
		echo "Charge Credit Card TRANS ID  : " . $tresponse->getTransId() . "\n";
	}
	else
	{
		echo  "Charge Credit Card ERROR :  Invalid response\n";
	}
}
else
{
	echo  "Charge Credit card Null response returned";
}

Setting Production Environment

Replace the environment constant in the execute method. For example, in the method above:

$response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::PRODUCTION);

Logging

SDK generates log with masking for sensitive data like credit card, expiration dates. The provided levels for logging are debug, info, warn, error. Add use \net\authorize\util\LogFactory;. Logger can be initialized using $logger = LogFactory::getLog(get_class($this)); The default log file phplog gets generated in the current folder. The subsequent logs are appended to the same file, unless the execution folder is changed, and a new log file is generated.

Usage Examples

  • Logging a string message $logger->debug("Sending 'XML' Request type");
  • Logging xml strings $logger->debug($xmlRequest);
  • Logging using formatting $logger->debugFormat("Integer: %d, Float: %f, Xml-Request: %s\n", array(100, 1.29f, $xmlRequest));

Customizing Sensitive Tags

A local copy of AuthorizedNetSensitiveTagsConfig.json gets generated when code invoking the logger first gets executed. The local file can later be edited by developer to re-configure what is masked and what is visible (Do not edit the json in sdk).

  • For each element of the sensitiveTags array,
    • tagName field corresponds to the name of the property in object, or xml-tag that should be hidden entirely ( XXXX shown if no replacement specified ) or masked (e.g. showing the last 4 digits of credit card number).
    • pattern[Note] and replacement[Note] can be left "", if the default is to be used (as defined in Log.php). pattern gives the regex to identify, while replacement defines the visible part.
    • disableMask can be set to true to allow the log to fully display that property in an object, or tag in a xml string.
  • sensitiveStringRegexes[Note] has list of credit-card regexes. So if credit-card number is not already masked, it would get entirely masked.
  • Take care of non-ascii characters (refer manual) while defining the regex, e.g. use "pattern": "(\\p{N}+)(\\p{N}{4})" instead of "pattern": "(\\d+)(\\d{4})". Also note \\ escape sequence is used.

Note: For any regex, no starting or ending '/' or any other delimiter should be defined. The '/' delimiter and unicode flag is added in the code.

Testing

Integration tests for the AuthorizeNet SDK are in the tests directory. These tests are mainly for SDK development. However, you can also browse through them to find more usage examples for the various APIs.

  • Run composer update --dev to load the PHPUnit test library.
  • Copy the phpunit.xml.dist file to phpunit.xml and enter your merchant credentials in the constant fields.
  • Run vendor/bin/phpunit to run the test suite.

You'll probably want to disable emails on your sandbox account.

Test Credit Card Numbers

Card Type Card Number
American Express Test Card 370000000000002
Discover Test Card 6011000000000012
Visa Test Card 4007000000027
Second Visa Test Card 4012888818888
JCB 3088000000000017
Diners Club/ Carte Blanche 38000000000006

Set the expiration date to anytime in the future.

PHPDoc

Add PhpDocumentor to your composer.json and run composer update --dev:

"require-dev": {
    "phpdocumentor/phpdocumentor": "*"
}

To autogenerate PHPDocs run:

vendor/bin/phpdoc -t doc/api/ -d lib

sdk-php's People

Contributors

0b10011 avatar adear11 avatar adrienrusso avatar akankaria avatar apropos avatar ashtru avatar brianmc avatar drmonkeyninja avatar fulldecent avatar goetas avatar lakshmisundar avatar namanbansal avatar ncpga avatar rahulrnitc avatar ramittal avatar scrutinizer-auto-fixer avatar shahariaazam avatar srmisra avatar texdc avatar trevorw avatar vyoam avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.