Académique Documents
Professionnel Documents
Culture Documents
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
1 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
an API call. This enables you to host the payment process on your website in full, which might make for a more complete shopping experience for your customers. The Direct Payment method has several variations that enable you to authorize a payment and complete it at a later date: the appropriately named Authorization and Capture methods. These variations are a part of the Website Payments Pro API, which is available only to US, Canadian and UK accounts. Recurring Payments This allows you to set up a recurring transaction (i.e. a subscription payment). Mass Payments This allows you to transfer money to multiple accounts at once. Adaptive Payments Here is another API for sending funds to multiple recipients, with some differences from the Mass Payments API. (Did I mention that the PayPal API is confusing and a bit redundant?) This list is not comprehensive, but it covers the main payment options (see the API documentation for more).
2 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
01 class Paypal { 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 /** * API Version * @var string */ protected $_version = '74.0'; /** * API endpoint * Live - https://api-3t.paypal.com/nvp * Sandbox - https://api-3t.sandbox.paypal.com/nvp * @var string */ protected $_endPoint = 'https://api-3t.sandbox.paypal.com/nvp'; ); /** * API Credentials * Use the correct credentials for the environment in use (Live / Sandbox) * @var array */ protected $_credentials = array( 'USER' => 'seller_1297608781_biz_api1.lionite.com', 'PWD' => '1297608792', 'SIGNATURE' => 'A3g66.FS3NAf4mkHn3BDQdpo6JD.ACcPc4wMrInvUEqO3Uapovity47p', /** * Last error message(s) * @var array */ protected $_errors = array();
3 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 //cURL settings $curlOptions = array ( CURLOPT_URL => $this -> _endPoint, CURLOPT_VERBOSE => 1, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem', //CA cert file //Building our NVP string $request = http_build_query($requestParams + $params); //Our request parameters $requestParams = array( 'METHOD' => $method, 'VERSION' => $this -> _version ) + $this -> _credentials; } /** * Make API request * * @param string $method string API method to request * @param array $params Additional request parameters * @return array / boolean Response array / boolean false on failure */ public function request($method,$params = array()) { $this -> _errors = array(); if( empty($method) ) { //Check if API method is not empty $this -> _errors = array('API method is missing'); return false;
4 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 } } } );
//Sending our request - $response will hold the API response $response = curl_exec($ch);
//Checking for cURL errors if (curl_errno($ch)) { $this -> _errors = curl_error($ch); curl_close($ch); return false; //Handle errors } else { curl_close($ch); $responseArray = array(); parse_str($response,$responseArray); // Break the NVP string to an array return $responseArray;
Note that I use a CA certificate file for SSL certificate validation. You can obtain the file from the cURL website or any trusted source. Update the path to the certificate file according to where youve placed it. The response returned will be in NVP format as well, and I reformat it into an array before returning it. A parameter named ACK signifies the status of the request: Success or SuccessWithWarning when the request succeeds, and Error or Warning when the request fails.
5 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
A request could fail for many reasons, and there are different reasons for each API method, which are covered in detail in the manual. Well go over some further down in this article and look at ways to handle them. Keep in mind that the parameter values are case-sensitive, so code against them accordingly.
Express Checkout
One of the most popular APIs is the Express Checkout API, which enables you to receive payments without opening a Website Payments Pro account (which is available only to verified US accounts) or hosting the actual transaction yourself (which requires additional security). The Express Checkout process works as follows: 1. We request a checkout token from PayPal using the transaction details; 2. If successful, we redirect the user to the PayPal endpoint using the received token; 3. The user completes or cancels the payment on the PayPal platform and is redirected back to our website; 4. We complete the payment either when the user is redirected back or via an Instant Payment Notification (IPN).
6 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
METHOD This is the API method that were using (i.e. SetExpressCheckout). RETURNURL The URL that the user will be redirected to after the payment process is completed. CANCELURL The URL that the user will be redirected to after having cancelled the payment process. PAYMENTREQUEST_0_AMT The transactions total amount. This must have two decimal places, with the decimal separator being a period (.). The optional thousands separator must be a comma (,). PAYMENTREQUEST_0_ITEMAMT The total cost of the items in the order, excluding shipping, taxes and other costs. If there are no extra costs, then it should be the same value as PAYMENTREQUEST_0_AMT. We can pass additional parameters to add more information about the order, some of which have default values: PAYMENTREQUEST_0_CURRENCYCODE The payments currency, as a three-letter code. The default is USD. PAYMENTREQUEST_0_SHIPPINGAMT The total shipping costs for this order. PAYMENTREQUEST_0_TAXAMT The total tax amount for this order. This is required if per-item tax is specified (see below). PAYMENTREQUEST_0_DESC The orders description. We can also add details about individual items in the order: L_PAYMENTREQUEST_0_NAMEm The items name. L_PAYMENTREQUEST_0_DESCm The items description. L_PAYMENTREQUEST_0_AMTm The items cost. L_PAYMENTREQUEST_0_QTYm The quantity of an item. The variable index m identifies the item. (Use the same variable for all details of the same item.) There are many other optional parameters, which can be found in the API documentation. Well use the function that we wrote above to build the SetExpressCheckout request:
7 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
01 //Our request parameters 02 $requestParams = array( 03 04 05 ); 06 07 $orderParams = array( 08 09 10 11 12 ); 13 14 $item = array( 15 16 17 18 19 ); 20 21 $paypal = new Paypal(); 22 $response = $paypal -> request('SetExpressCheckout',$requestParams + $orderParams + $item); 'L_PAYMENTREQUEST_0_NAME0' => 'iPhone', 'L_PAYMENTREQUEST_0_DESC0' => 'White iPhone, 16GB', 'L_PAYMENTREQUEST_0_AMT0' => '496', 'L_PAYMENTREQUEST_0_QTY0' => '1' 'PAYMENTREQUEST_0_AMT' => '500', 'PAYMENTREQUEST_0_SHIPPINGAMT' => '4', 'PAYMENTREQUEST_0_CURRENCYCODE' => 'GBP', 'PAYMENTREQUEST_0_ITEMAMT' => '496' 'RETURNURL' => 'http://www.yourdomain.com/payment/success', 'CANCELURL' => 'http://www.yourdomain.com/payment/cancelled'
1 2 3
8 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
checkout&token=' . urlencode($token) ); 4} The user now goes through the purchase process on PayPals website. When they confirm or cancel it, they will return to one of the URLs that weve specified in the request.
01 02 03 04 05
9 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
08 09 10 11 12
$requestParams = array( 'TOKEN' => $_GET['token'], 'PAYMENTACTION' => 'Sale', 'PAYERID' => $_GET['PayerID'], 'PAYMENTREQUEST_0_AMT' => '500', // Same amount as in the original request
13 14 15 16 );
17 18 19 20
if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful // We'll fetch the transaction ID for internal bookkeeping $transactionId = $response['PAYMENTINFO_0_TRANSACTIONID']; }
21 }
Direct Payment
The Direct Payment API allows you to receive payments directly on your website or application, giving you complete control over the checkout process. PayPal tends to push users to register and use a PayPal account, which is understandable, but this conflicts somewhat with our interest to make the payment process as simple and clear as possible for our customers. For this reason, full control over the checkout process is preferred and gives us more options to optimize sales and generate more sales.
The process is a bit simpler than that of Express Checkout, because the entire interaction
10 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
occurs on our website, and we need to perform just one API call to process a normal payment: DoDirectPayment. A couple of more API requests are required if you want to perform a transaction that is billed at a later date (for example, when you ship the product or confirm availability). These would be the Authorization & Capture API methods, which I will not cover in this post, but be aware that this option exists.
DirectPayment Parameters
DirectPayment requires different parameters than Express Checkout, as to be expected. While the transaction details parameters are similar (with different key names, to make it more interesting), the method also requires credit-card and address information. DirectPayments basic parameters: METHOD This is DoDirectPayment. IPADDRESS This is the IP address of the payer. In PHP, we can retrieve it using the superglobal $_SERVER['REMOTE_ADDR']. Youll have to do a bit more work to get the IP when dealing with set-ups that have a proxy between the PHP process and the outside network (such as nginx). PAYMENTACTION This is the type of action that we want to perform. A value of Sale indicates an immediate transaction. A value of Authorization indicates that this transaction will not be performed immediately, but rather will be captured later using the Authorization & Capture API mentioned earlier. Credit-card details: CREDITCARDTYPE The credit-card type (Visa, MasterCard, etc.). See the API documentation for the full list. ACCT The credit-card number. (Dont you love these abbreviated key names?) This must conform to the particular format of the cards type. EXPDATE The expiration date, in MMYYYY format (i.e. a two-digit month and a four-digit year, as one string). CVV2 The card verification value, or security code, as its sometimes known. Payer information and address parameters:
11 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
FIRSTNAME, LASTNAME The payers first name and last name, respectively (in separate fields). You can also provide an email address in an EMAIL parameter, but its not required. CITY, STATE, COUNTRYCODE, ZIP The city, state, country code (as a two-letter code) and zip code parts of the address, all required. STREET, STREET2 Two lines for the address (only the first is required). This address will be used in the address verification system (AVS). Youll receive a specific error code if a transaction has failed due to an address verification failure. The payment details parameters are the same as the ones for Express Checkout, but with slightly different names (AMT, ITEMAMT, CURRENCYCODE, SHIPPINGAMT, TAXAMT and DESC) and without the PAYMENTREQUEST_0_ prefix. Refer to the previous section or the API documentation for specific details on those. Similarly, the item details parameters are similar to those of Express Checkout. These include L_NAMEm, L_DESCm, L_AMTm and L_QTYm, giving you granular control of item details in the order summary. The m integer variable is used to account for multiple items (replace with 0, 1 and so on for numbered items in the order). See the API documentation for a comprehensive list of item details.
12 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
11 ); 12 13 $payerDetails = array( 14 15 16 17 18 19 20 21 ); 22 23 $orderParams = array( 24 25 26 27 28 ); 29 30 $item = array( 31 32 33 34 35 ); 36 37 $paypal = new Paypal(); 38 $response = $paypal -> request('DoDirectPayment', 39 40 ); 41 $requestParams + $creditCardDetails + $payerDetails + $orderParams + $item 'L_NAME0' => 'iPhone', 'L_DESC0' => 'White iPhone, 16GB', 'L_AMT0' => '496', 'L_QTY0' => '1' 'AMT' => '500', 'ITEMAMT' => '496', 'SHIPPINGAMT' => '4', 'CURRENCYCODE' => 'GBP' 'FIRSTNAME' => 'John', 'LASTNAME' => 'Doe', 'COUNTRYCODE' => 'US', 'STATE' => 'NY', 'CITY' => 'New York', 'STREET' => '14 Argyle Rd.', 'ZIP' => '10010'
13 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
42 43 44
if( is_array($response) && $response['ACK'] == 'Success') { // Payment successful // We'll fetch the transaction ID for internal bookkeeping $transactionId = $response['TRANSACTIONID'];
Error Handling
In a perfect world, this section would not exist. In reality, you will be referring to it quite a lot. PayPal can fail a transaction for a multitude of reasons, not all of which you can control. The $response variable we returned from our paypalApiRequest() function could contain a different value than Success for the ACK parameter. That value could be: Success Indicates a successful operation. SuccessWithWarning Indicates a successful operation, and that messages were returned in the response that you should examine. Failure Indicates a failed operation, and that the response contains one or more error messages explaining the failure. FailureWithWarning Indicates a failed operation, and that messages were returned in the response that you should examine. This gives us two success statuses and two failure statuses. The mock code above tests for the Success value only, but we could change it to check for SuccessWithWarning as well; and keep in mind that we need to find out what the warning is. A common scenario is that a Direct Payment charge will have been performed successfully, but the credit-card company responds that the transaction has failed, for whatever reason. Errors from PayPal are returned in four parameters in the response: L_ERRORCODE0 A numeric error code, which can referenced against PayPals error code list (there are quite a few). L_SHORTMESSAGE0 A short error message describing the problem. L_LONGMESSAGE0
14 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
A longer error message describing the problem. L_SEVERITYCODE0 The severity code. (I couldnt find any useful documentation on this, and it doesnt really matter, so lets put it aside.) The 0 part of these parameters is an incrementing integer for multiple error message (1, 2, etc.). Here are some common errors youll run into: 10002 Authentication or authorization failed. This usually indicates invalid API credentials, or credentials that do not match the type of environment you are working in (such as a live or sandbox environment). 81*** Missing parameter. There are quite a few of these, all starting with 81. Each refers to a specific required parameter that is missing from the request. 104** Invalid argument. This indicates that one of the supplied parameters has an invalid value. Each argument has specific errors, all starting with 104. A common one is 10413, which means that the total cost of the cart items does not match the orders amount (i.e. the total amount parameter, AMT, does not equal the items total plus shipping, handling, taxes and other charges).
15 sur 17
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
Eran Galperin I'm an entrepreneur and web developer. Formerly started Lionite, a web development shop and incubator, now I'm CTO on Binpress, a discovery service and marketplace for source-code.
05/10/2011 18:33
http://coding.smashingmagazine.com/2011/09/05/getting-started-with-th...
JavaScript & jQuery WordPress Techniques Back-End & Administration HTML5 Tutorials CSS, CSS3 Bored?
17 sur 17
05/10/2011 18:33