Chapter 2. PayPal Express Checkout

Express Checkout is PayPal’s premier checkout solution. It allows a customer to check out on your site, log into his PayPal account, and purchase your goods or services. Express Checkout puts PayPal in charge of data security with regard to the customer’s billing and credit card information and removes that liability from the merchant. In this chapter, we will look at generic versus Express Checkout workflows, Express Checkout API operations, a simple Express Checkout integration, as well as an in-depth integration method.

Checkout Process Workflows

Let’s start by looking at the process flow of a typical checkout and an Express Checkout.

Generic Checkout Workflow

Figure 2-1 shows the typical checkout flow a user experiences when buying goods or services online, which includes the following steps:

  1. Customer clicks the checkout button on your shopping cart page.

  2. Customer enters all shipping information.

  3. Customer chooses her payment method and provides all the relevant billing and payment information.

  4. Customer reviews order and pays.

  5. Customer receives her order confirmation.

As you can see, this typical checkout method requires the customer to provide a lot of information at the time of purchase. This is where PayPal’s Express Checkout can be a real time saver for your customers.

Generic checkout workflow
Figure 2-1. Generic checkout workflow

Express Checkout Workflow

Figure 2-2 shows the checkout workflow a user experiences when using PayPal’s Express Checkout:

  1. Customer chooses Express Checkout by clicking the “Check out with PayPal” button on your site.

  2. Customer logs into PayPal.

  3. Customer reviews the transaction on PayPal.

  4. Customer confirms the order and pays from your site.

  5. Customer receives an order confirmation.

PayPal Express Checkout workflow
Figure 2-2. PayPal Express Checkout workflow

With Express Checkout, the customer does not need to enter his billing and shipping information each time. Consequently, customers can make purchases and move on to other tasks much more quickly.

Generic Versus Express Checkout Workflow

Table 2-1 outlines the process steps required to complete a payment during a generic checkout and Express Checkout. As you can see, Express Checkout saves both time and processing steps.

Table 2-1. Generic checkout versus Express Checkout
Checkout stepGeneric checkoutExpress Checkout
Select the checkout button
Enter shipping info-
Select payment method-
Enter payment information-
Review order
Confirm order

Express Checkout Flow

To fully implement Express Checkout, you must allow your customers two entry points into the Express Checkout payment process. Figure 2-3 outlines the complete checkout flow for Express Checkout.

Complete Express Checkout flow
Figure 2-3. Complete Express Checkout flow

As you can see, customers can enter into the Express Checkout flow at either the Shopping Cart Checkout entry point (dotted arrow) or the Payment Methods entry point (solid arrow). Including both methods in your checkout routines is easy to implement.

Figure 2-4 outlines the Checkout Entry Point, which requires the following steps:

  1. Customer clicks the “Check out with PayPal” button.

  2. Customer logs into PayPal.

  3. Customer confirms shipping and billing information on PayPal’s site.

  4. Customer is returned to your application for final review and clicks the Purchase button.

  5. Customer is returned to a confirmation screen related to the purchase.

Checkout Entry Point
Figure 2-4. Checkout Entry Point

Figure 2-5 outlines the Payment Method Entry Point, which requires the following steps:

  1. Customer clicks the checkout button on your application.

  2. Customer inputs shipping information into your application.

  3. Customer chooses PayPal from the list of payment methods.

  4. Customer logs into PayPal.

  5. Customer reviews payment information on PayPal’s site.

  6. Customer is returned to your application for final review and clicks the Purchase button.

  7. Customer is returned to a confirmation screen related to the purchase.

A token is a value assigned by PayPal that associates the execution of API operations and commands with a specific instance of a user experience flow. Tokens are not shown in Figures 2-1 through 2-5.

Payment Method Entry Point
Figure 2-5. Payment Method Entry Point

PayPal Express Checkout API Operations

The PayPal NVP API provides four key methods related to Express Checkout. These operations initialize the transaction, obtain the buyer information and handle the payment, and then complete the transaction. Table 2-2 outlines these methods.

Table 2-2. Express Checkout API operations
API operationDescription
SetExpressCheckoutSets up the Express Checkout transaction. You can specify information to customize the look and feel of the PayPal site and the information it displays. You must include the following information:
  • URL to the page on your website to which PayPal redirects after the buyer logs into PayPal and approves the payment successfully

  • URL to the page on your website to which PayPal redirects if the buyer cancels the transaction

  • Total amount of the order or your best estimate of the total (this should be as accurate as possible)

GetExpressCheckoutDetailsObtains information about the buyer from PayPal, including shipping information.
DoExpressCheckoutPaymentCompletes the Express Checkout transaction, including the actual total amount of the order.
CallbackUpdates the PayPal Review page with the relevant shipping options, insurance, and tax information.

Let’s break down each API operation into its smaller components and outline the related request and response fields.

SetExpressCheckout

SetExpressCheckout initializes the Express Checkout session. It allows you to pass variables that format how the PayPal pages look and specify where to redirect the buyer’s browser based upon success of the payment transaction.Table 2-3 outlines the fields required for SetExpressCheckout requests, and Table 2-4 outlines the field required for SetExpressCheckout responses.

Table 2-3. SetExpressCheckout request fields
FieldDescriptionRequired?
METHODMust be SetExpressCheckoutYes
RETURNURLURL to which the customer’s browser is returned after choosing to pay with PayPal. PayPal recommends that the value be the final review page on which the customer confirms the order and payment or billing agreement.

Limitation: Up to 2,048 characters.

Yes
CANCELURLURL to which the customer is returned if he does not approve the use of PayPal to pay you. PayPal recommends that the value be the original page on which the customer chose to pay with PayPal or establish a billing agreement.

Limitation: Up to 2,048 characters.

Yes
PAYMENTREQUEST_n_AMTThe total cost of the transaction to the customer. If shipping and tax charges are known, include them in this value; if not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must equal the sum of the purchases.

Set this field to 0 if the transaction does not include a one-time purchase, for example, when you set up a billing agreement for a recurring payment that is not charged immediately. Purchase-specific fields will be ignored.

Limitations: Must not exceed $10,000 USD in any currency. No currency symbol. Must have two decimal places, the decimal separator must be a period (.), and the optional thousands separator must be a comma (,).

Yes
PAYMENT_n_PAYMENTACTIONHow you want to obtain your payment. When implementing parallel payments, this field is required and must be set to Order.
  • Sale indicates that this is a final sale for which you are requesting payment (this is the default).

  • Authorization indicates that this payment is a basic authorization subject to settlement with PayPal Authorization and Capture.

  • Order indicates that this payment is an order authorization subject to settlement with PayPal Authorization and Capture.

If the transaction does not include a one-time purchase, this field is ignored. You cannot set this value to Sale in SetExpressCheckout request and then change this value to Authorization or Order on the final API DoExpressCheckoutPayment request. If the value is set to Authorization or Order in SetExpressCheckout, the value may be set to Sale or the same value (either Authorization or Order) in DoExpressCheckoutPayment.

Limitation: Up to 13 single-byte alphabetic characters.

Yes

A complete list of all fields allowed for the SetExpressCheckout request method can be found in the online documentation located at http://www.x.com/community/ppx/documentation.

Table 2-4. SetExpressCheckout response fields
FieldDescription
TOKENA time-stamped token by which you identify to PayPal that you are processing this payment with Express Checkout.

The token expires after three hours. If you set the token in the SetExpressCheckout request, the value of the token in the response is identical to the value in the request.

Limitation: Up to 20 single-byte characters.

A complete list of all fields allowed for the SetExpressCheckout response method can be found in the online documentation located at http://www.x.com/community/ppx/documentation.

GetExpressCheckoutDetails

GetExpressCheckoutDetails obtains information about an Express Checkout transaction. Only the request has required fields, as the response just echoes back the information and values enabled in SetExpressCheckout. Table 2-5 describes the required GetExpressCheckoutDetails fields.

Table 2-5. GetExpressCheckoutDetails request fields
FieldDescription
METHODMust be GetExpressCheckoutDetails
TOKENA time-stamped token, limited to 20 single-byte characters, the value of which was returned by the SetExpressCheckout response

A full listing of the GetExpressCheckoutDetails response fields can be found in the online documentation located at http://www.x.com/community/ppx/documentation.

DoExpressCheckoutPayment

DoExpressCheckoutPayment completes the Express Checkout transaction and returns the payment response. If you set up a billing agreement in your SetExpressCheckout API call, the billing agreement is created when you call the DoExpressCheckoutPayment API operation. Table 2-6 lists the DoExpressCheckoutPayment request fields, and Table 2-7 describes the response fields.

Table 2-6. DoExpressCheckoutPayment request fields
FieldDescription
METHODMust be DoExpressCheckoutPayment.
TOKENA time-stamped token, the value of which was returned by the SetExpressCheckout response and passed on to the GetExpressCheckoutDetails request.

Limitation: Up to 20 single-byte characters.

PAYERIDUnique PayPal customer account identification number as returned by the GetExpressCheckoutDetails response.

Limitation: Up to 13 single-byte alphanumeric characters.

PAYMENTREQUEST_n_AMTThe total cost of the transaction to the customer (required). If shipping and tax charges are known, include them in this value; if not, this value should be the current subtotal of the order.

If the transaction includes one or more one-time purchases, this field must equal the sum of the purchases.

Set this field to 0 if the transaction does not include a one-time purchase, for example, when you set up a billing agreement for a recurring payment that is not charged immediately. Purchase-specific fields will be ignored.

Limitations: Must not exceed $10,000 USD in any currency. No currency symbol. Must have two decimal places, the decimal separator must be a period (.), and the optional thousands separator must be a comma (,).

PAYMENTREQUEST_n_PAYMENTACTIONHow you want to obtain your payment. When implementing parallel payments, this field is required and must be set to Order.
  • Sale indicates that this is a final sale for which you are requesting payment (this is the default).

  • Authorization indicates that this payment is a basic authorization subject to settlement with PayPal Authorization and Capture.

  • Order indicates that this payment is an order authorization subject to settlement with PayPal Authorization and Capture.

If the transaction does not include a one-time purchase, this field is ignored.

You cannot set this value to Sale in SetExpressCheckout request and then change this value to Authorization or Order on the final API DoExpressCheckoutPayment request. If the value is set to Authorization or Order in SetExpressCheckout, the value may be set to Sale or the same value (either Authorization or Order) in DoExpressCheckoutPayment.

Limitation: Up to 13 single-byte alphabetic characters.

PAYMENTREQUEST_n_PAYMENTREQUESTIDA unique identifier of the specific payment request, which is required for parallel payments.

Limitation: Up to 127 single-byte character limit.

A full listing of the DoExpressCheckoutPayment request fields can be found in the online documentation located at http://www.x.com/community/ppx/documentation.

Table 2-7. DoExpressCheckoutPayment response fields
FieldDescription
TOKENA time-stamped token, the value of which was returned by the SetExpressCheckout response and passed on to the GetExpressCheckoutDetails request.

Limitation: Up to 20 single-byte characters.

PAYMENTTYPEInformation about the payment.
SUCCESSPAGEREDIRECTREQUESTEDFlag that indicates whether you need to redirect the customer to back to PayPal after completing the transaction.
PAYMENTINFO_n_TRANSACTIONIDUnique transaction ID of the payment. If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization and Capture APIs.

Limitation: Up to 19 single-byte characters.

PAYMENTINFO_n_TRANSACTIONTYPEThe type of transaction. Valid values are cart and express-checkout.

Limitation: Up to 15 single-byte characters.

PAYMENTINFO_n_PAYMENTTYPEIndicates whether the payment is instant or delayed. Valid values are none, echeck, and instant.

Limitation: Up to 7 single-byte characters.

PAYMENTINFO_n_ORDERTIMEThe time/date stamp of the payment.
PAYMENTINFO_n_AMTThe final amount charged, including any shipping and taxes from your Merchant Profile.

Limitations: Does not exceed $10,000 USD in any currency. No currency symbol. Regardless of currency, the decimal separator is a period (.), and the optional thousands separator is a comma (,). Equivalent to nine characters maximum for USD.

PAYMENTINFO_n_FEEAMTPayPal fee amount charged for the transaction.

Limitations: Does not exceed $10,000 USD in any currency. No currency symbol. Regardless of currency, the decimal separator is a period (.), and the optional thousands separator is a comma (,). Equivalent to nine characters maximum for USD.

PAYMENTINFO_n_TAXAMTTax charged on the transaction.

Limitations: Does not exceed $10,000 USD in any currency. No currency symbol. Regardless of currency, the decimal separator is a period (.), and the optional thousands separator is a comma (,). Equivalent to nine characters maximum for USD.

PAYMENTINFO_n_EXCHANGERATEExchange rate if a currency conversion occurred. Relevant only if you are billing in the customer’s nonprimary currency. If the customer chooses to pay with a currency other than the primary currency, the conversion occurs in the customer’s account.

Limitations: A decimal value that does not exceed 17 characters, including decimal points.

PAYMENTINFO_n_PAYMENTSTATUSThe status of the payment, which will be one of the following:
  • None: No status.

  • Canceled-Reversal: A reversal has been canceled, for example, when you win a dispute and the funds for the reversal are returned to you.

  • Completed: The payment has been completed and the funds have transferred successfully to your account.

  • Denied: You denied the payment. This will occur only if the payment was previously pending because of reasons described in the PendingReason field.

  • Expired: The authorization period for the payment has expired.

  • Failed: The payment failed. This occurs only when the payment was made from your customer’s bank draft account.

  • In-Progress: Transaction has not terminated, most likely due to an authorization awaiting completion.

  • Partially-Refunded: Payment has been partially refunded.

  • Pending: Payment is still pending for reasons described in the PendingReason field.

  • Refunded: You refunded the payment.

  • Reversed: Payment was reversed due to a charge back or other reversal. The funds have been removed from your account balance and returned to the buyer. The reason will be described in the ReasonCode field.

  • Processed: Payment has been accepted.

  • Voided: Authorization for the transaction has been voided.

PAYMENTINFO_n_PROTECTIONELIGIBILITYThe type of seller protection in force for the transaction, which is one of the following values:
  • Eligible: Seller is protected by PayPal’s Seller protection policy for Unauthorized Payments and Item Not Received.

  • PartiallyEligible: Seller is protected by PayPal’s Seller Protection Policy for Item Not Received.

  • Ineligible: Seller is not protected under the Seller Protection Policy.

PAYMENTREQUEST_n_PAYMENTREQUESTIDThe unique identifier of the specific payment request. The value should match the one passed in the DoExpressCheckout request.

Limitation: Up to 127 single-byte characters.

L_PAYMENTINFO_n_FMFfilterIDnFilter ID, including the filter type (PENDING, REPORT, or DENY), the filter ID, and the entry number, n, starting from 0. Filter ID is one of the following values:
  • 1 = AVS No Match

  • 2 = AVS Partial Match

  • 3 = AVS Unavailable/Unsupported

  • 4 = Card Security Code (CSC) Mismatch

  • 5 = Maximum Transaction Amount

  • 6 = Unconfirmed Address

  • 7 = Country Monitor

  • 8 = Large Order Number

  • 9 = Billing/Shipping Address Mismatch

  • 10 = Risky Zip Code

  • 11 = Suspected Freight Forwarder Check

  • 12 = Total Purchase Price Minimum

  • 13 = IP Address Velocity

  • 14 = Risky Email Address Domain Check

  • 15 = Risky Bank Identification Number (BIN) Check

  • 16 = Risky IP Address Range

  • 17 = PayPal Fraud Model

L_PAYMENTINFO_n_FMFfilterNAMEnFilter name, including the filter type (PENDING, REPORT, or DENY), the filter NAME, and the entry number, n, starting from 0.
PAYMENTREQUEST_n_SHORTMESSAGEPayment error short message.
PAYMEMNTREQUEST_n_LONGMESSAGEPayment error long message.
PAYMENTREQUEST_n_ERRORCODEPayment error code.
PAYMENTREQUEST_n_SEVERITYCODEPayment error severity code.
PAYMENTREQUEST_n_ACKApplication-specific error values indicating more about the error condition.
SHIPPINGCALCULATIONMODEDescribes how the options that were presented to the user were determined, and is one of the following values:
  • API - Callback

  • API - Flatrate

INSURANCEOPTIONSELECTEDThe Yes/No option that you chose for insurance.
SHIPPINGOPTIONISDEFAULTIs true if the buyer chose the default shipping option. Value will be either TRUE or FALSE.
SHIPPINGOPTIONAMOUNTThe shipping amount that was chosen by the buyer. Limitations: Must not exceed $10,000 USD in any currency. No currency symbol. Must have two decimal places, the decimal separator must be a period (.), and the optional thousands separator must be a comma (,).
SHIPPINGOPTIONNAMEThis is true if the buyer chose the default shipping option.
PAYMENTREQUEST_n_SELLERPAYPALACCOUNTIDUnique identifier for the merchant. For parallel payments, this field contains either the Payer ID or the email address of the merchant.

Callback

Callback allows you to return any relevant shipping information to the PayPal review page.Table 2-8 outlines the required Fields for Callback requests and Table 2-9 outlines the required fields for Callback responses.

Table 2-8. Callback request fields
FieldDescription
METHODMust be Callback (required).
CURRENCYCODEThe three-character currency code for the transaction from the Express Checkout API (required). Default is USD.
L_NAMEnItem name from the Express Checkout API. Parameters must be numbered sequentially starting with 0 (e.g., L_NAME0, L_NAME1).
L_NUMBERnItem number from the Express Checkout API. Parameters must be numbered sequentially starting with 0 (e.g., L_NUMBER0, L_NUMBER1).
L_DESCnItem description from the Express Checkout API. Parameters must be numbered sequentially starting with 0 (e.g., L_DESC0, L_DESC1).
L_AMTnItem unit price from the Express Checkout API. Parameters must be numbered sequentially starting with 0 (e.g., L_AMT0, L_AMT1).
L_QTYnItem unit quantity from the Express Checkout API. Parameters must be numbered sequentially starting with 0 (e.g., L_QTY0, L_QTY1).
L_ITEMWEIGHTVALUEn L_ITEMWEIGHTUNITnThe weight of the item. You can pass this data to the shipping carrier as is, with no additional database query. Parameters must be numbered sequentially starting with 0 (e.g., L_ITEMWEIGHTVALUE0, L_ITEMWEIGHTVALUE1).
L_ITEMHEIGHTVALUEn L_ITEMHEIGHTUNITnThe height of the item. You can pass this data to the shipping carrier as is, with no additional database query. Parameters must be numbered sequentially starting with 0 (e.g., L_ITEMHEIGHTVALUE0, L_ITEMHEIGHTVALUE1).
L_ITEMWIDTHVALUEn L_ITEMWIDTHUNITnThe width of the item. You can pass this data to the shipping carrier as is, with no additional database query. Parameters must be numbered sequentially starting with 0 (e.g., L_ITEMWIDTHVALUE0, L_ITEMWIDTHVALUE1).
L_ITEMLENGTHVALUEn L_ITEMLENGTHUNITnThe length of the item. You can pass this data to the shipping carrier as is, with no additional database query. Parameters must be numbered sequentially starting with 0 (e.g., L_ITEMLENGTHVALUE0, L_ITEMLENGTHVALUE1).
SHIPTOSTREETThe first street address. This is required if using a shipping address. Limitation: Up to 100 single-byte characters.
SHIPTOSTREET2The second street address. Limitation: Up to 100 single-byte characters.
SHIPTOCITYThe name of the city. This is required if using a shipping address. Limitation: Up to 40 single-byte characters.
SHIPTOSTATEThe state or province. Required if using a shipping address. Limitation: Up to 40 single-byte characters.
SHIPTOZIPU.S. postal zip code or other country-specific postal code. Required if using a U.S. shipping address; may be required for other countries. Limitation: Up to 20 single-byte characters.
SHIPTOCOUNTRYCountry code. Required if using a shipping address. Limitation: Up to two single-byte characters.

A complete list of all fields allowed for the Callback request method and response method can be found in the online documentation at http://www.x.com/community/ppx/documentation.

Table 2-9. Callback response fields
FieldDescription
METHODMust be CallbackResponse (required).
CURRENCYCODEThe three-character currency code for the transaction from the Express Checkout API (required).
L_SHIPPINGOPTIONNAMEnThe internal/system name of a shipping option (e.g., Air, Ground, Expedited). This field is required. Parameters must be ordered sequentially starting with 0 (e.g., L_SHIPPINGOPTIONNAME0, L_SHIPPINGOPTIONNAME1). Limitation: Up to 50 characters.
L_SHIPPINGOPTIONLABELnThe label for the shipping options displayed to the buyer (e.g., Air: Next Day, Expedited: 3-5 days, Ground: 5-7 days). This field is required. Labels can be localized based on the buyer’s locale. Parameters must be numbered sequentially starting with 0 (e.g., L_SHIPPINGOPTIONLABEL0, L_SHIPPINGOPTIONLABEL1). Limitation: Up to 50 characters.
L_SHIPPINGOPTIONAMOUNTnAmount of the shipping option. Parameters must be numbered sequentially starting with 0 (e.g., L_SHIPPINGOPTIONAMOUNT0, L_SHIPPINGOPTIONAMOUNT1). Limitations: Must not exceed $10,000 USD in any currency. No currency symbol allowed. The decimal separator must be a period (.), regardless of currency, and the optional thousands separator must be a comma(,). Equivalent to nine characters maximum for USD.
L_SHIPPINGOPTIONISDEFAULTThe default option selected for the buyer; this is also reflected in the “default” total (required).

Simple Express Checkout Integration

The simplest Express Checkout integration requires execution of only two PayPal API operations: SetExpressCheckout and DoExpressCheckoutPayment. For example, optionally, you can call GetExpressCheckoutDetails to error check the information provided to SetExpressCheckout against the form values and provide the customer a Confirm Transaction screen before finalizing the payment.

Setting Up the Transaction

To set up an Express Checkout transaction, you must first invoke the SetExpressCheckout API to provide sufficient information to initiate the payment flow and redirect your customer to PayPal if the operation is successful.

When you initiate the Express Checkout transaction, you specify values in the SetExpressCheckout request, and then call the API. The values you specify control the PayPal page flow and options available to your customers.

Let’s look at setting up a simple Express Checkout transaction.

  1. First we need to specify the total dollar amount of the transaction, if known; otherwise, specify the subtotal. Refer to Table 2-3’s PAYMENTREQUEST_n_AMT field description for requirements and restrictions.

    AMT=amount

    CURRENCYCODE=currencyID

  2. Specify the return URL. This is the page on your site that you want PayPal to redirect the customer to after the customer logs into PayPal and approves the payment. Typically, the customer is redirected to a secure page on your site via SSL (https://).

    RETURNURL=return_url

  3. Specify the cancel URL. This is the page on your site you want PayPal to redirect the customer to if the buyer does not approve the payment. Typically, the customer is redirected to a secure page on your site via SSL (https://).

    CANCELURL=cancel_url

  4. Specify the payment action. Even though the action is a Sale, it is best to explicitly set the payment action. Refer to Table 2-3’s PAYMENT_n_PAYMENTACTION field description for allowed values.

  5. Execute the SetExpressCheckoutAPI operation and test that the response was successful. To test for success, check to see whether the API returns a TOKEN and other variables.

Tip

You can piggyback parameters between pages on your site in the return URL call as well as the cancel URL call. For example, you can set your return URL to specify additional parameters using something like https://your.domain.ext/returnpage.php?param1=val1&param2=val2, etc. This allows you to pass parameters from the transaction without making a GetExpressCheckoutDetails API call, or pass custom parameters not provided by the SetExpressCheckout API.

To execute the transaction, you must invoke the DoExpressCheckoutPayment operation. This is accomplished through the following steps:

  1. Specify the TOKEN value returned by PayPal when it redirects the buyer’s browser to your site.

    TOKEN=tokenValue

  2. Specify the payer ID returned by PayPal when it redirects the customer’s browser to your site.

    PAYERID=id

  3. Specify the total amount of the payment, including shipping, handling, and tax, and include the currency if not in U.S. dollars.

    AMT=amount

    CURRENCYCODE=currencyID

  4. Specify the payment action. Even though the action is a Sale, it is best to explicitly set the payment action. Refer to Table 2-3’s PAYMENT_n_PAYMENTACTION field description for allowed values.

  5. Execute the DoExpressCheckoutAPI operation, and test that the response was successful.

Express Checkout Integration

PayPal Express Checkout is the quickest and best solution for straight-out shopping cart checkouts. PayPal’s Integration Wizard, found at https://www.paypal-labs.com/integrationwizard/ecpaypal/main.php, helps you implement Express Checkout on your site. The wizard takes you through five configuration steps, described next.

The Integration Wizard starts by presenting a basic overview of what the tool will do. You can choose to watch the introduction or skip it at this point (Figure 2-6).

Express Checkout Integration Wizard opening screen
Figure 2-6. Express Checkout Integration Wizard opening screen

Step 1 allows you to choose the programming language you want to use for the integration (see Figure 2-7). For the purposes of this example we are going to use PHP, but you can choose any of the following options:

  • Active Server Pages (ASP)

  • ASP.NET-C#(ASPX)

  • ASP.NET-VB.NET(ASPX)

  • Java Server Pages (JSP)

  • Java SDK

  • PHP

You also are asked to specify the return and cancel URLs. The return URL is where the purchaser will be returned to once the transaction is completed. The cancel URL is where the purchaser is sent to if she cancels the checkout, typically back to your site’s shopping cart. The payment type will be one of the following:

  • Sale

  • Authorization

  • Order

Express Checkout Integration Wizard step 1
Figure 2-7. Express Checkout Integration Wizard step 1

The Currency Code section contains a list of currencies, both foreign and domestic, from which to choose. For this example, we will choose U.S. Dollar [USD].

The form element generated in step 2 (see Figure 2-8) wraps around your shopping cart order form, and allows you to submit the payment via PayPal (see Example 2-6). It will also generate a button on-screen. You must be sure to enable a PHP $_SESSION and set the variable $_SESSION['Payment_Amount'] that contains the amount of the purchase; otherwise, the generated code will not work properly.

Express Checkout Integration Wizard step 2
Figure 2-8. Express Checkout Integration Wizard step 2

You now have the option to download expresscheckout.php (see Example 2-1), and paypalfunctions.php (see Example 2-2). You will need to modify the paypalfunction.php file with your API credentials. For instructions on creating those credentials, refer to Creating an API Signature. Additionally, after you have completed testing and are ready to go live, change $SandboxFlag='true' to $SandboxFlag='false'. This will change the endpoints to the live PayPal endpoint.

Note

For security reasons, I recommend putting your paypalfunctions.php file in a location accessible to expresscheckout.php and the other generated files, but outside your main webroot. This will help to prevent anyone from potentially obtaining your API credentials.

Step 3 generates code for your billing page that will be used if someone chooses PayPal from the billing options page instead of the main shopping cart page (see Figure 2-9).

Express Checkout Integration Wizard step 3
Figure 2-9. Express Checkout Integration Wizard step 3

You must be sure to enable a PHP $_SESSION and set the variable $_SESSION['Payment_Amount']that contains the amount of the purchase; otherwise, the generated code will not work properly. You can copy the code from the box generated by the Wizard, and paste it into your billing handler (see Example 2-3).

Step 4 (Figure 2-10) generates code to add to your shipping page. You can copy the code from the box generated by the Wizard and paste it into your shipping handler (see Example 2-4). Step 5 (Figure 2-11) generates code for your order confirmation page. You can copy the code from the box generated by the Wizard and paste it into your order confirmation handler (see Example 2-5). Step 6 completes the Integration Wizard, as shown in Figure 2-12.

Express Checkout Integration Wizard step 4
Figure 2-10. Express Checkout Integration Wizard step 4
Express Checkout Integration Wizard step 5
Figure 2-11. Express Checkout Integration Wizard step 5
Express Checkout Integration Wizard step 6
Figure 2-12. Express Checkout Integration Wizard step 6
Example 2-1. paypalfunctions.php

<?php
 /********************************************
 PayPal API Module
  
 Defines all the global variables and the wrapper functions 
 ********************************************/
 $PROXY_HOST = '127.0.0.1';
 $PROXY_PORT = '808';

 $SandboxFlag = true;

 //'------------------------------------
 //' PayPal API Credentials
 //' Replace <API_USERNAME> with your API Username
 //' Replace <API_PASSWORD> with your API Password
 //' Replace <API_SIGNATURE> with your Signature
 //'------------------------------------
 $API_UserName="mdbald_1287976381_biz_api1.michaelbalderas.com";
 $API_Password="1287976406";
 $API_Signature="APOxIKm-Fx0tSYmLLbuPFN42APwdAhhNTtvJ8YhTD2ALC9poKmbhBaf6";

 // BN Code is only applicable for partners
 $sBNCode = "PP-ECWizard";


 /*
 ' Define the PayPal Redirect URLs.  
 ' This is the URL where the buyer is first sent to authorize payment with their 
 ' PayPal account. Change the URL depending on whether you are testing on the sandbox 
 ' or the live PayPal site.
 '
 ' For the sandbox, the URL is
 ' https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
 ' For the live site, the URL is
 ' https://www.paypal.com/webscr&cmd=_express-checkout&token=
 */
 
 if ($SandboxFlag == true) 
 {
  $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
  $PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
 }
 else
 {
  $API_Endpoint = "https://api-3t.paypal.com/nvp";
  $PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
 }

 $USE_PROXY = false;
 $version="64";

 if (session_id() == "") 
  session_start();

 /* An express checkout transaction starts with a token that identifies
    to PayPal your transaction. In this example, when the script sees
    a token, the script knows that the buyer has already authorized
    payment through PayPal.  If no token was found, the action is
    to send the buyer to PayPal to first authorize payment.
    */

 /*   
 '----------------------------------------------------------------------------------
 ' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
 ' Inputs:  
 '  paymentAmount:  Total value of the shopping cart
 '  currencyCodeType: Currency code value the PayPal API
 '  paymentType:   paymentType has to be one of the following values: 
 '                 Sale or Order or Authorization
 '  returnURL:     The page where buyers return to after they are done 
 '                 with the payment review on PayPal
 '  cancelURL:     The page where buyers return to when they cancel the
 '                 payment review on PayPal
 '----------------------------------------------------------------------------------
 */
 function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, 
          $paymentType, $returnURL, $cancelURL) 
 {
  //--------------------------------------------------------------------------------
  // Construct the parameter string that describes the SetExpressCheckout 
  // API call in the shortcut implementation

  $nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
  $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
  $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;

  $_SESSION["currencyCodeType"] = $currencyCodeType;  
  $_SESSION["PaymentType"] = $paymentType;

  //'------------------------------------------------------------------------------- 
  //' Make the API call to PayPal
  //' If the API call succeeded, then redirect the buyer to PayPal to begin to 
  //' authorize payment.  
  //' If an error occurred, show the resulting errors.
 //'--------------------------------------------------------------------------------
    $resArray=hash_call("SetExpressCheckout", $nvpstr);
  $ack = strtoupper($resArray["ACK"]);
  if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
  {
   $token = urldecode($resArray["TOKEN"]);
   $_SESSION['TOKEN']=$token;
  }
   
    return $resArray;
}

 /*   
 '----------------------------------------------------------------------------------
 ' Purpose: Prepares the parameters for the SetExpressCheckout API Call.
 ' Inputs:  
 '  paymentAmount:  Total value of the shopping cart
 '  currencyCodeType: Currency code value the PayPal API
 '  paymentType: paymentType has to be one of the following values: Sale or Order or
 '               Authorization
 '  returnURL:   The page where buyers return to after they are done with the payment 
 '               review on PayPal
 '  cancelURL:   The page where buyers return to when they cancel the payment review 
 '               on PayPal
 '  shipToName:  The Ship to Name entered on the merchant's site
 '  shipToStreet: The Ship to Street entered on the merchant's site
 '  shipToCity:   the Ship to City entered on the merchant's site
 '  shipToState:  The Ship to State entered on the merchant's site
 '  shipToCountryCode: The Code for Ship to Country entered on the merchant's site
 '  shipToZip:   The Ship to ZipCode entered on the merchant's site
 '  shipToStreet2: The Ship to Street2 entered on the merchant's site
 '  phoneNum:   The phoneNum  entered on the merchant's site
'------------------------------------------------------------------------------------
 */
 function CallMarkExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, 
           $returnURL, $cancelURL, $shipToName, $shipToStreet, $shipToCity, 
           $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
         ) 
 {
  //---------------------------------------------------------------------------------
  // Construct the parameter string that describes the SetExpressCheckout API call in
  // the shortcut implementation

  $nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
  $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
  $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
  $nvpstr = $nvpstr . "&ADDROVERRIDE=1";
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
  $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOPHONENUM=" . $phoneNum;

  $_SESSION["currencyCodeType"] = $currencyCodeType;
  $_SESSION["PaymentType"] = $paymentType;

  //'--------------------------------------------------------------------------------- 
  //' Make the API call to PayPal
  //' If the API call succeeded, then redirect the buyer to PayPal to begin to 
  //' authorize payment.  
  //' If an error occurred, show the resulting errors.
  //'----------------------------------------------------------------------------------
    $resArray=hash_call("SetExpressCheckout", $nvpstr);
  $ack = strtoupper($resArray["ACK"]);
  if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
  {
   $token = urldecode($resArray["TOKEN"]);
   $_SESSION['TOKEN']=$token;
  }
   
    return $resArray;
}

 /*
 '-------------------------------------------------------------------------------------
 ' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
 '
 ' Inputs:  
 '  None
 ' Returns: 
 '  The NVP Collection object of the GetExpressCheckoutDetails Call Response.
 '-------------------------------------------------------------------------------------
 */
 function GetShippingDetails( $token )
 {
  //'--------------------------------------------------------------
  //' At this point, the buyer has finished authorizing the payment
  //' on PayPal.  The function will call PayPal to obtain the details
  //' of the authorization, including any of the buyer's shipping information.
  //' Remember, the authorization is not a completed transaction
  //' at this stage - the buyer still needs an additional step to finalize
  //' the transaction.
  //'--------------------------------------------------------------
    
     //'---------------------------------------------------------------------------
  //'  Build a second API request to PayPal, using the token as the
  //'  ID to get the details on the payment authorization
  //'---------------------------------------------------------------------------
    $nvpstr="&TOKEN=" . $token;

  //'---------------------------------------------------------------------------
  //' Make the API call and store the results in an array.  
  //' If the call was a success, show the authorization details, and provide
  //' an action to complete the payment.  
  //' If failed, show the error.
  //'---------------------------------------------------------------------------
     $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
     $ack = strtoupper($resArray["ACK"]);
 if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING")
  {
   $_SESSION['payer_id'] = $resArray['PAYERID'];
  } 
  return $resArray;
 }

 /*
 '-------------------------------------------------------------------------------------
 ' Purpose: Prepares the parameters for the GetExpressCheckoutDetails API Call.
 '
 ' Inputs:  
 '  sBNCode: The BN code used by PayPal to track the transactions 
 '  from a given shopping cart.
 ' Returns: 
 '  The NVP Collection object of the GetExpressCheckoutDetails Call Response.
 '--------------------------------------------------------------------------------------
 */
 function ConfirmPayment( $FinalPaymentAmt )
 {
  /* Gather the information to make the final call to
     finalize the PayPal payment. The variable nvpstr
     holds the name-value pairs.
     */
  

  //Format the other parameters that were stored in the session from the previous calls	
  $token = urlencode($_SESSION['TOKEN']);
  $paymentType = urlencode($_SESSION['PaymentType']);
  $currencyCodeType = urlencode($_SESSION['currencyCodeType']);
  $payerID = urlencode($_SESSION['payer_id']);

  $serverName = urlencode($_SERVER['SERVER_NAME']);

  $nvpstr  = '&TOKEN=' . $token . '&PAYERID=' . $payerID . 
           '&PAYMENTREQUEST_0_PAYMENTACTION='.
           $paymentType . '&PAYMENTREQUEST_0_AMT=' . $FinalPaymentAmt .
           '&PAYMENTREQUEST_0_CURRENCYCODE=' . $currencyCodeType .'&IPADDRESS='.
           $serverName; 

   /* Make the call to PayPal to finalize payment
      If an error occurred, show the resulting errors.
      */
  $resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);

  /* Display the API response back to the browser.
     If the response from PayPal was a success, display the response parameters.
     If the response was an error, display the errors received using APIError.php.
     */
  $ack = strtoupper($resArray["ACK"]);

  return $resArray;
 }

 /*
 '-----------------------------------------------------------------------------------
 ' Purpose: This function makes a DoDirectPayment API call
 '
 ' Inputs:  
 '  paymentType:  paymentType has to be one of the following values: Sale or Order or 
 '                Authorization
 '  paymentAmount:  Total value of the shopping cart
 '  currencyCode: Currency code value in the PayPal API
 '  firstName: first name as it appears on credit card
 '  lastName: Last name as it appears on credit card
 '  street: Buyer's street address line as it appears on credit card
 '  city: Buyer's city
 '  state: Buyer's state
 '  countryCode: Buyer's country code
 '  zip: Buyer's zip
 '  creditCardType: Buyer's credit card type (e.g., Visa, MasterCard ... )
 '  creditCardNumber: Buyer's credit card number without any spaces, dashes, or any other 
 '                    characters
 '  expDate: Credit card expiration date
 '  cvv2: Card Verification Value 
 '
 '-----------------------------------------------------------------------------------
 '
 ' Returns: 
 '  The NVP Collection object of the DoDirectPayment Call Response.
 '-----------------------------------------------------------------------------------
 */


 function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
       $expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip, 
       $countryCode, $currencyCode )
 {
  //Construct the parameter string that describes DoDirectPayment
  $nvpstr = "&AMT=" . $paymentAmount;
  $nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
  $nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
  $nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
  $nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
  $nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
  $nvpstr = $nvpstr . "&CVV2=" . $cvv2;
  $nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
  $nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
  $nvpstr = $nvpstr . "&STREET=" . $street;
  $nvpstr = $nvpstr . "&CITY=" . $city;
  $nvpstr = $nvpstr . "&STATE=" . $state;
  $nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
  $nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];

  $resArray=hash_call("DoDirectPayment", $nvpstr);

  return $resArray;
 }


 /**
   '---------------------------------------------------------------------------------
   * hash_call: Function to perform the API call to PayPal using API signature
   * @methodName is name of API  method.
   * @nvpStr is nvp string.
   * Returns an associative array containing the response from the server.
   '---------------------------------------------------------------------------------
 */
 function hash_call($methodName,$nvpStr)
 {
  //declaring of global variables
  global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
  global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
  global $gv_ApiErrorURL;
  global $sBNCode;

  //setting the curl parameters.
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
  curl_setopt($ch, CURLOPT_VERBOSE, 1);

  //turning off the server and peer verification(TrustManager Concept).
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_POST, 1);

   //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
  if($USE_PROXY)
   curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT); 

  //NVPRequest for submitting to server
  $nvpreq = "METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . 
          "&PWD=".
          urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=".
          urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);

  //setting the nvpreq as POST FIELD to curl
  curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

  //getting response from server
  $response = curl_exec($ch);

  //converting NVPResponse to an Associative Array
  $nvpResArray=deformatNVP($response);
  $nvpReqArray=deformatNVP($nvpreq);
  $_SESSION['nvpReqArray']=$nvpReqArray;

  if (curl_errno($ch)) 
  {
   // moving to display page to display curl errors
     $_SESSION['curl_error_no']=curl_errno($ch) ;
     $_SESSION['curl_error_msg']=curl_error($ch);

     //Execute the error-handling module to display errors. 
  } 
  else 
  {
    //closing the curl
     curl_close($ch);
  }

  return $nvpResArray;
 }

 /*'-------------------------------------------------------------------------------
  Purpose: Redirects to PayPal.com site.
  Inputs:  NVP string.
  Returns: 
 ----------------------------------------------------------------------------------
 */
 function RedirectToPayPal ( $token )
 {
  global $PAYPAL_URL;

  // Redirect to paypal.com here
  $payPalURL = $PAYPAL_URL . $token;
  header("Location: ".$payPalURL);
 }


/*'----------------------------------------------------------------------------------
   * This function will take NVPString and convert it to an Associative Array and
   * then will decode the response.
   * It is useful to search for a particular key and display the arrays.
   * @nvpstr is NVPString.
   * @nvpArray is Associative Array.
   ----------------------------------------------------------------------------------
   */
 function deformatNVP($nvpstr)
 {
  $intial=0;
   $nvpArray = array();

  while(strlen($nvpstr))
  {
   //position of Key
   $keypos= strpos($nvpstr,'='),
   //position of value
   $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

   /*getting the Key and Value values and storing in a Associative Array*/
   $keyval=substr($nvpstr,$intial,$keypos);
   $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
   //decoding the respose
   $nvpArray[urldecode($keyval)] =urldecode( $valval);
   $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
      }
  return $nvpArray;
 }

?>
Example 2-2. expresscheckout.php

<?php

require_once ("paypalfunctions.php");
// ==================================
// PayPal Express Checkout Module
// ==================================

//'------------------------------------
//' The paymentAmount is the total value of 
//' the shopping cart, which was set 
//' earlier in a session variable 
//' by the shopping cart page.
//'------------------------------------
$paymentAmount = $_SESSION["Payment_Amount"];

//'------------------------------------
//' The currencyCodeType and paymentType 
//' are set to the selections made in the Integration Assistant.
//'------------------------------------
$currencyCodeType = "USD";
$paymentType = "Sale";

//'------------------------------------
//' The returnURL is the location where buyers return to when a
//' payment has been succesfully authorized.
//'
//' This is set to the value entered in the Integration Assistant. 
//'------------------------------------
$returnURL = "http://www.michaelbalderas.com/paypal/expresscheckout/OrderConfirm.php";

//'------------------------------------
//' The cancelURL is the location buyers are sent to when they hit the
//' cancel button during authorization of payment during the PayPal flow.
//'
//' This is set to the value entered in the Integration Assistant.
//'------------------------------------
$cancelURL = "http://www.michaelbalderas.com/paypal/expresscheckout/shoppingcart.php";

//'------------------------------------
//' Calls the SetExpressCheckout API call
//'
//' The CallShortcutExpressCheckout function is defined in the file PayPalFunctions.php,
//' which is included at the top of this file.
//'-------------------------------------------------
$resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, 
            $returnURL, $cancelURL);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
 RedirectToPayPal ( $resArray["TOKEN"] );
} 
else  
{
 //Display a user-friendly Error on the page using any of the following error information 
 //returned by PayPal.
 $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
 $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
 $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
 $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
 
 echo "SetExpressCheckout API call failed. ";
 echo "Detailed Error Message: " . $ErrorLongMsg;
 echo "Short Error Message: " . $ErrorShortMsg;
 echo "Error Code: " . $ErrorCode;
 echo "Error Severity Code: " . $ErrorSeverityCode;
}
?>
Example 2-3. billing.php

<?php

require_once ("paypalfunctions.php");

if ( $PaymentOption == "PayPal")
{ // ==================================
 // PayPal Express Checkout Module
 // ==================================

 //'------------------------------------
 //' The paymentAmount is the total value of 
 //' the shopping cart, which was set 
 //' earlier in a session variable 
 //' by the shopping cart page.
 //'------------------------------------
 $paymentAmount = $_SESSION["Payment_Amount"];

 //'------------------------------------
 //' When you integrate this code, 
 //' set the following variables with 
 //' shipping address details 
 //' entered by the user on the 
 //' Shipping page.
 //'------------------------------------
 $shipToName = "<<ShiptoName>>";
 $shipToStreet = "<<ShipToStreet>>";
 $shipToStreet2 = "<<ShipToStreet2>>"; //Leave it blank if there is no value
 $shipToCity = "<<ShipToCity>>";
 $shipToState = "<<ShipToState>>";
 $shipToCountryCode = "<<ShipToCountryCode>>"; // Please refer to the PayPal country 
                                               //codes in the API documentation.
 $shipToZip = "<<ShipToZip>>";
 $phoneNum = "<<PhoneNumber>>";

 //'------------------------------------
 //' The currencyCodeType and paymentType 
 //' are set to the selections made in the Integration Assistant. 
 //'------------------------------------
 $currencyCodeType = "USD";
 $paymentType = "Sale";

 //'------------------------------------
 //' The returnURL is the location where buyers return to when a
 //' payment has been succesfully authorized.
 //'
 //' This is set to the value entered in the Integration Assistant. 
 //'------------------------------------
 $returnURL = "http://www.michaelbalderas.com/paypal/expresscheckout/OrderConfirm.php";

 //'------------------------------------
 //' The cancelURL is the location buyers are sent to when they hit the
 //' cancel button during authorization of payment during the PayPal flow.
 //'
 //' This is set to the value entered in the Integration Assistant. 
 //'------------------------------------
 $cancelURL = "http://www.michaelbalderas.com/paypal/expresscheckout/shoppingcart.php";

 //'------------------------------------
 //' Calls the SetExpressCheckout API call
 //'
 //' The CallMarkExpressCheckout function is defined in the file PayPalFunctions.php,
 //' it is included at the top of this file.
 //'-------------------------------------------------
 $resArray = CallMarkExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, 
            $returnURL, $cancelURL, $shipToName, $shipToStreet, $shipToCity, 
            $shipToState, $shipToCountryCode, $shipToZip, $shipToStreet2, $phoneNum
 );

 $ack = strtoupper($resArray["ACK"]);
 if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
 {
  $token = urldecode($resArray["TOKEN"]);
  $_SESSION['reshash']=$token;
  RedirectToPayPal ( $token );
 } 
 else  
 {
  //Display a user-friendly Error on the page using any of the  
  //following error information returned by PayPal.
  $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
  $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
  $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
  $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
 
  echo "SetExpressCheckout API call failed. ";
  echo "Detailed Error Message: " . $ErrorLongMsg;
  echo "Short Error Message: " . $ErrorShortMsg;
  echo "Error Code: " . $ErrorCode;
  echo "Error Severity Code: " . $ErrorSeverityCode;
 }
}
else
{
 if ((( $PaymentOption == "Visa") || ( $PaymentOption == "MasterCard") || 
   ($PaymentOption == "Amex") || ($PaymentOption == "Discover")) 
   && ( $PaymentProcessorSelected == "PayPal Direct Payment"))

 //'------------------------------------
 //' The paymentAmount is the total value of 
 //' the shopping cart, which was set 
 //' earlier in a session variable 
 //' by the shopping cart page.
 //'------------------------------------
 $paymentAmount = $_SESSION["Payment_Amount"];

 //'------------------------------------
 //' The currencyCodeType and paymentType 
 //' are set to the selections made in the Integration Assistant. 
 //'------------------------------------
 $currencyCodeType = "USD";
 $paymentType = "Sale";
 
 //' Set these values based on what was selected by the user on the 
 //' Billing page Html form
 
 $creditCardType = "<<Visa/MasterCard/Amex/Discover>>"; //' Set this to one of the 
                    // acceptable values (Visa/MasterCard/Amex/Discover) match it to 
                    // what was selected on your Billing page.
 $creditCardNumber = "<<CC number>>"; //' Set this to the string entered as the 
                   // credit card number on the Billing page.
 $expDate = "<<Expiry Date>>"; //' Set this to the credit card expiry date 
                   // entered on the Billing page.
 $cvv2 = "<<cvv2>>"; //' Set this to the CVV2 string entered on the Billing page 
 $firstName = "<<firstName>>"; //' Set this to the customer's first name that was entered 
                   // on the Billing page.
 $lastName = "<<lastName>>"; //' Set this to the customer's last name that was entered on 
                   // the Billing page. 
 $street = "<<street>>"; //' Set this to the customer's street address that was entered on 
                  // the Billing page. 
 $city = "<<city>>"; //' Set this to the customer's city that was entered on 
                  // the Billing page.
 $state = "<<state>>"; //' Set this to the customer's state that was entered 
                  // on the Billing page. 
 $zip = "<<zip>>"; //' Set this to the zip code of the customer's address that was 
                  // entered on the Billing page. 
 $countryCode = "<<PayPal Country Code>>"; //' Set this to the PayPal code for the 
                  //Country of the customer's address that was entered on the Billing page. 
 $currencyCode = "<<PayPal Currency Code>>"; //' Set this to the PayPal code for 
                  // the Currency used by the customer. 
 
 /*
 '------------------------------------------------
 ' Calls the DoDirectPayment API call
 '
 ' The DirectPayment function is defined in PayPalFunctions.php, included at the top of 
 ' this file.
 '-------------------------------------------------
 */
 
 $resArray = DirectPayment ( $paymentType, $paymentAmount, $creditCardType, 
       $creditCardNumber, $expDate, $cvv2, $firstName, $lastName, $street, 
       $city, $state, $zip, $countryCode, $currencyCode ); 

 $ack = strtoupper($resArray["ACK"]);
 if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
 {
  //Getting transaction ID from API response. 
  $TransactionID = urldecode9$resArray["TRANSACTIONID"]);

  echo "Your payment has been successfully processed";
 }
 else
 {
  //Display a user-friendly Error on the page using any of the following error information 
  //returned by PayPal.
  $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
  $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
  $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
  $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
 
  echo "Direct credit card payment API call failed. ";
  echo "Detailed Error Message: " . $ErrorLongMsg;
  echo "Short Error Message: " . $ErrorShortMsg;
  echo "Error Code: " . $ErrorCode;
  echo "Error Severity Code: " . $ErrorSeverityCode;
 }
}
?>
Example 2-4. shipping.php

<?php
/*==================================================================
 PayPal Express Checkout Call
 ===================================================================
*/
// Check to see whether the Request object contains a variable named 'token'.
$token = "";
if (isset($_REQUEST['token']))
{
 $token = $_REQUEST['token'];
}

// If the Request object contains the variable 'token', then it means that the 
// user is coming from the PayPal site.
if ( $token != "" )
{

 require_once ("paypalfunctions.php");

 /*
 '------------------------------------
 ' Calls the GetExpressCheckoutDetails API call
 '
 ' The GetShippingDetails function is defined in PayPalFunctions.jsp,
 ' included at the top of this file.
 '-------------------------------------------------
 */
 

 $resArray = GetShippingDetails( $token );
 $ack = strtoupper($resArray["ACK"]);
 if( $ack == "SUCCESS" || $ack == "SUCESSWITHWARNING") 
 {
  /*
  ' The information that is returned by the GetExpressCheckoutDetails call should be 
  ' integrated by the partner into his Order Review page.
  */
  $email = $resArray["EMAIL"]; // ' Email address of payer.
  $payerId = $resArray["PAYERID"]; // ' Unique PayPal customer account 
                                   // identification number.
  $payerStatus = $resArray["PAYERSTATUS"]; // ' Status of payer. 
                                   // Limited to 10 single-byte alphabetic 
                                   // characters.
  $salutation = $resArray["SALUTATION"]; // ' Payer's salutation.
  $firstName = $resArray["FIRSTNAME"]; // ' Payer's first name.
  $middleName = $resArray["MIDDLENAME"]; // ' Payer's middle name.
  $lastName = $resArray["LASTNAME"]; // ' Payer's last name.
  $suffix = $resArray["SUFFIX"]; // ' Payer's suffix.
  $cntryCode = $resArray["COUNTRYCODE"]; // ' Payer's country of residence in the form of 
                                   // ISO standard 3166 two-character country codes.
  $business = $resArray["BUSINESS"]; // ' Payer's business name.
  $shipToName = $resArray["SHIPTONAME"]; // ' Person's name associated with this address.
  $shipToStreet = $resArray["SHIPTOSTREET"]; // ' First street address.
  $shipToStreet2 = $resArray["SHIPTOSTREET2"]; // ' Second street address.
  $shipToCity = $resArray["SHIPTOCITY"]; // ' Name of city.
  $shipToState = $resArray["SHIPTOSTATE"]; // ' State or province.
  $shipToCntryCode = $resArray["SHIPTOCOUNTRYCODE"]; // ' Country code. 
  $shipToZip = $resArray["SHIPTOZIP"]; // ' U.S. Zip code or other country-specific 
                                   // postal code.
  $addressStatus = $resArray["ADDRESSSTATUS"]; // ' Status of street address on file 
                                  // with PayPal.   
  $invoiceNumber = $resArray["INVNUM"]; // ' Your own invoice or tracking number, as set 
                                  // by you in the element of the same name. 
                                  //in SetExpressCheckout request.
  $phoneNumber = $resArray["PHONENUM"]; // ' Payer's contact telephone number. Note:  
                                 // PayPal returns a contact telephone number only 
                                 // if your Merchant account profile settings require 
                                 // that the buyer enter one. 
 } 
 else  
 {
  //Display a user-friendly Error on the page using any of the following error 
  //information returned by PayPal.
  $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
  $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
  $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
  $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);

  echo "GetExpressCheckoutDetails API call failed. ";
  echo "Detailed Error Message: " . $ErrorLongMsg;
  echo "Short Error Message: " . $ErrorShortMsg;
  echo "Error Code: " . $ErrorCode;
  echo "Error Severity Code: " . $ErrorSeverityCode;
 }
}
 
?>
Example 2-5. orderconfirmation.php

<?php
/*==================================================================
 PayPal Express Checkout Call
 ===================================================================
*/
require_once ("paypalfunctions.php");

if ( $PaymentOption == "PayPal" )
{ /*
 '------------------------------------
 ' The paymentAmount is the total value of 
 ' the shopping cart, which was set 
 ' earlier in a session variable 
 ' by the shopping cart page.
 '------------------------------------
 */
 
 $finalPaymentAmount =  $_SESSION["Payment_Amount"];
 
 /*
 '------------------------------------
 ' Calls the DoExpressCheckoutPayment API call
 '
 ' The ConfirmPayment function is defined in the file PayPalFunctions.jsp,
 ' included at the top of this file.
 '-------------------------------------------------
 */

 $resArray = ConfirmPayment ( $finalPaymentAmount );
 $ack = strtoupper($resArray["ACK"]);
 if( $ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING" )
 {
  /*
  '************************************************************************************
  '
  ' THE PARTNER SHOULD SAVE THE KEY TRANSACTION-RELATED INFORMATION SUCH AS 
  '                    transactionId & orderTime 
  '  IN THEIR OWN DATABASE AND THE REST OF THE INFORMATION
  '  CAN BE USED TO UNDERSTAND THE STATUS OF THE PAYMENT 
  '
  '************************************************************************************
  */

  $transactionId = $resArray["TRANSACTIONID"]; // ' Unique transaction ID of the payment. 
  // Note:  If the PaymentAction of the request was Authorization or Order, 
  // this value is your AuthorizationID for use with the Authorization & 
  // Capture APIs. 
 $transactionType = $resArray["TRANSACTIONTYPE"]; //' The type of transaction Possible 
                                                 // values: l  cart l  express-checkout 
  $paymentType = $resArray["PAYMENTTYPE"];  //' Indicates whether the payment is instant 
                                            // or delayed. Possible values: none,    
                                            // echeck, instant 
  $orderTime = $resArray["ORDERTIME"];  //' Time/date stamp of payment.
  $amt = $resArray["AMT"];  //' The final amount charged, including any shipping and  
                            // taxes from your Merchant Profile.
  $currencyCode = $resArray["CURRENCYCODE"];  //' A three-character currency code for  
                                              // one of the currencies listed in 
                                              // PayPal-Supported Transactional 
                                              // Currencies. Default: USD. 
  $feeAmt = $resArray["FEEAMT"];  //' PayPal fee amount charged for the transaction
  $settleAmt = $resArray["SETTLEAMT"];  //' Amount deposited in your PayPal account  
                                        // after a currency conversion.
  $taxAmt = $resArray["TAXAMT"];  //' Tax charged on the transaction.
  $exchangeRate = $resArray["EXCHANGERATE"];  //' Exchange rate if a currency conversion 
                                              // occurred. Relevant only if you are  
                                              // billing in their non-primary currency.  
                                              // If the customer chooses to pay with a  
                                              // currency other than the non-primary 
                                              // currency, the conversion occurs 
                                              // in the customer's account.

  /*
    'Status of the payment: 
    'Completed: The payment has been completed, and the funds have been added  
    'successfully to your account balance.
    'Pending: The payment is pending. See the PendingReason element for more information. 
  */

  $paymentStatus = $resArray["PAYMENTSTATUS"]; 

  /*
  'The reason the payment is pending:
  '  none: No pending reason. 
  '  address: The payment is pending because your customer did not include a 
  '           confirmed shipping address and your Payment Receiving Preferences 
  '           is set such that you want to manually accept or deny each of these 
  '           payments. To change your preference, go to the Preferences section 
  '           of your Profile. 
  '  echeck: The payment is pending because it was made by an eCheck that has 
  '          not yet cleared. 
  '  intl: The payment is pending because you hold a non-U.S. account and 
  '        do not have a withdrawal mechanism. You must manually accept or
  '        deny this payment from your Account Overview.
  '  multi-currency: You do not have a balance in the currency sent, 
  '                  and you do not have your Payment Receiving 
  '                  Preferences set to automatically convert and 
  '                  accept this payment. You must manually accept 
  '                  or deny this payment. 
  '  verify: The payment is pending because you are not yet verified. 
  '          You must verify your account before you can accept this payment. 
  '  other: The payment is pending for a reason other than those listed above. 
  '         For more information, contact PayPal customer service. 
  */
  
  $pendingReason = $resArray["PENDINGREASON"];  

  /*
  'The reason for a reversal if TransactionType is reversal:
  '  none: No reason code. 
  '  chargeback: A reversal has occurred on this transaction due to a 
  '              chargeback by your customer. 
  '  guarantee: A reversal has occurred on this transaction due to 
  '             your customer triggering a money-back guarantee. 
  '  buyer-complaint: A reversal has occurred on this transaction 
  '                   due to a complaint about the transaction 
  '                   from your customer. 
  '  refund: A reversal has occurred on this transaction because 
  '          you have given the customer a refund. 
  '  other: A reversal has occurred on this transaction due to 
  '         a reason not listed above. 
  */

  $reasonCode = $resArray["REASONCODE"];   
 }
 else  
 {
  //Display a user-friendly Error on the page using any of the 
  //following error information returned by PayPal.
  $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
  $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
  $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
  $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
  
  echo "GetExpressCheckoutDetails API call failed. ";
  echo "Detailed Error Message: " . $ErrorLongMsg;
  echo "Short Error Message: " . $ErrorShortMsg;
  echo "Error Code: " . $ErrorCode;
  echo "Error Severity Code: " . $ErrorSeverityCode;
 }
}

?>
Example 2-6. shoppingcart.php

<form action='expresscheckout.php' METHOD='POST'>
<input type='image' name='submit' 
src='https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif' 
border='0' align='top' alt='Check out with PayPal'/>
</form>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.214.215