Paypal

PayPal provides a very simple REST API to enable us selling digital products in our website or apps. For example, I integrate it within my website to sell programming tutorials, source code, etc. In this post, I will explain how PayPal REST api works and demonstrate PayPal checkout workflow step by step.

How to Receive Money by Paypal Automatically

To receive money by Paypal REST API automatically, you need a PayPal account first and log in to the Paypal Developer Dashboard. In the dashboard, you can create an App in Sandbox (test) or Live. In this post, I will use my Sandbox app. When the app is ready, you can get the following information of the APP API credentials:

  • App Account
  • Client ID
  • Secret

Sell Product with PayPal REST API

After we get PayPal App ready in PayPal developer website, it’s time to sell your digital work and make money automatically. Here is the simplest workflow to let your customers make the payment:

  1. Get token
  2. Create order
  3. Show PayPal checkout page
  4. Confirm payment and show downloading url

In all above steps, I will use curl to call PayPal REST API. So at the beginning, I create a common function to make curl requests. The function will be used in all the following example code.

function CurlRequest($url,$data=null,$header=null,$auth=null){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	if ( !empty($data) ) {
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}
	
	if ( !empty($header) ) {
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	}
	
	if ( !empty($auth) ) {
		curl_setopt($ch, CURLOPT_USERPWD, $auth);
	}
	
	$str = curl_exec($ch);
	curl_close($ch);
	return $str;
}

#1. Get Token

Before starting to call PayPal REST API to receive money, I will use my app credentials to get the token first. In the following code, please replace your app api client id and secret.

    require_once('paypalfunctions');

    $API_ClientId = "Your app password";
    $API_Secret = "Your app signature";
    $url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";
    $headers = array("Content-Type: application/x-www-form-urlencoded");
    $data = "grant_type=client_credentials";
    $auth = $API_ClientId.":".$API_Secret;
    $result = CurlRequest($url, $data, $headers, $auth);
    $result = json_decode($result);
    $token = $result->{'access_token'};
    print_r($token);

After running above code, I will print the token on the terminal. Please copy and paste the token for further usage.

#2. Create Order

Once gettting the token ready, I can build the simple order request with following information:

  • currency
  • amount
  • custom_id

The following code will call REST api to create an order and the order id will be returned if calling successfully. Please replace the token value by the token string in #1 step.

    $token = "token created by #1 step";
    $url = "https://api-m.sandbox.paypal.com/v2/checkout/orders";
    $headers = array("Content-Type: application/json", "Authorization: Bearer ".$token);
    $data = array(
        "intent" => "CAPTURE",
        "purchase_units" => [
            [
                "amount"=>[
                    "currency_code"=>"USD",
                    "value"=>"1.00"
                ],
                "description"=>"Test Goods",
                "custom_id"=>"123abc"
            ]
        ],
        "application_context" => [
            "brand_namestring" => "James Test Store",
            "cancel_url" => "https://127.0.0.1/",
            "return_url" => "https://127.0.0.1/captureOrder.php"
        ]
    );
    $data = json_encode($data);
    $result = CurlRequest($url, $data, $headers);
    $result = json_decode($result);

    print_r($result);

In the result, the following information is very important:

  • id (this is the order id, which will be used in step #3 and #4)
  • status
  • links (there are 4 urls in the fields, the 2nd one is for you to redirect your customer to PayPal payment page in step #3; the last one is for you to verify the payment and show downloading url in step #4;)

#3. Show PayPal checkout page

In this step, I already created a new order in step 2. Now, I just redirect my customer to PayPal payment page to make the payment.

    $orderId = "Your order Id in Step 2";
    $payURL = "https://www.sandbox.paypal.com/checkoutnow?token=".$orderId;
    header("Location: ".$payURL);

My customer will see the screen like this:

#4. Confirm payment

Once the customers finish the payment in step #3, the PayPal page will bring him/her to the comfirm page with order id and payer id. The comfirm page url is set as return_url in Step #1. Basicaly, I will check the order status by calling PayPal capture order API.

If the customer doesn’t pay the order, capture order API will return something like:

ORDER_NOT_APPROVED

Payer has not yet approved the Order for payment. Please redirect the payer to the ‘rel’:’approve’ url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request.

If the customer makes the payment successfully, capture order API will return order marked as “COMPLETED” and other information such as:

  • Transaction ID
  • payment_source
  • gross_amount
  • paypal_fee
  • net_amount
  • create_time/update_time

Basically, all information you can see in your PayPal transaction details will be return in the response.

Now, I can show the downloading url for my customers to download what they have purchased.

Get Example Source Code at $9.99

With the source code, you can run the whole workflow on your own and fully understand how you can make money without any human operation like receiving money or sending digital products.

The source code includes 5 files:

  • paypalfunctions.php (the common function used by all steps)
  • token.php (for step #1)
  • createOrder.php (for step #2)
  • payOrder.php (for step #3)
  • captureOrder.php (for step #4)
Previous PostNext Post

Leave a Reply

Your email address will not be published. Required fields are marked *