• Home
  • PHP
  • MySQL
  • Laravel
  • Demos
  • HTML
  • jQuery
  • Framework
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Laravel
  • Demos
  • HTML
  • jQuery
  • Framework
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • RSS
Using the PayPal Payments API with PHP and Guzzle
Home
API

Using the PayPal Payments API with PHP and Guzzle

October 30th, 2025 Ivan Dimov API, PHP 0 comments

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. We are using Guzzle to integrate PayPal API.

You can use the PayPal Payments API, documented at: https://developer.paypal.com/docs/integration/direct/rest-payments-overview/ to let your users make payments to you of dynamically/arbitrarily generated sums.

 

To use the API, first you would need to get your PayPal Client and Secret Id, which are unique strings given to you in exchange for creating an application. You can create an application at: https://developer.paypal.com/developer/applications/create

After you get your client ID and secret key, you would have to get a token (OAuth token) which you would be able to use to manage payments.

The following PHP request with Guzzle can get you a token that you can later use to manage payments:

try {

            $client = new \GuzzleHttp\Client();

            $res = $client->request('POST', 'https://' . $paypalClientId . ':' . $paypalClientSecret . '@'.self::$paypalUrl.'/v1/oauth2/token', [

                'Accept' => 'application/json',

                'Accept-Language' => 'en_US',

                'form_params' => [

                    'grant_type' => 'client_credentials'

                ]

            ]);

            $responseBody = json_decode($res->getBody()->getContents());

            if (!$responseBody || !$responseBody->access_token) {

                // could not get token

            }

           $token =  $responseBody->access_token;

        } catch (\Exception $ex) {

            $error = $ex->getMessage();

        }

    }

It is assumed that you set up your $paypalClientId and $paypalClientSecret variables. The token should be saved in the $token variable.

Afterwards, you can initiate the payment with the following code:

 $saleData = '{

                "intent":"sale",

                "redirect_urls":{

                "return_url":"' . $returnUrl . '",

                "cancel_url": "' . $cancelUrl . '"

                    },

                "payer": {

                "payment_method":"paypal"

                },

                "transactions":[

                    {

                    "amount":{

                        "total":"' . $amountToBePaid . '",

                        "currency":"USD"

                        },

                         "description": "A coffee delivery in the ' . $shopName . ' coffeeshop”                    }

                ]

            }';

        try {

            $client = new \GuzzleHttp\Client();

            $paymentResponse = $client->request('POST', 'https://'.$paypalUrl.'/v1/payments/payment', [

                'headers' => array(

                    'Content-Type' => 'application/json',

                    'Authorization' => "Bearer $accessToken",

                ),

                'body' => $saleData

            ]);

            $paymentBody = json_decode($paymentResponse->getBody()->getContents());

        } catch (\Exception $ex) {

            $error =  $ex->getMessage();

        }

Again, you would need to set up some variables here – the $returnUrl when users confirm the payment, the $cancelUrl when users cancel a payment, you need to pass your access token, and the $amountToBePaid.

After you make this request, you would get a response in the $paymentBody variable. You can use it to redirect the user to the appropriate URL and when he/she comes back, you can execute it and make the actual money transfer. You need to redirect the user to the URL returned in:

$paymentBody->links[1]->href;

When the user returns, you are expected to have a couple of GET parameters – paymentId and PayerID. You can use them to finalize the payment in the following way:

$jsonBody = '{ "payer_id" : "' . $_GET[‘payerID’] . '" }';

        try {

            $client = new \GuzzleHttp\Client();

            $paymentResponse = $client->request('POST', 'https://'.self::$paypalUrl.'/v1/payments/payment/' . $_GET[‘transactionId’]. '/execute/', [

                'headers' => array(

                    'Content-Type' => 'application/json',

                    'Authorization' => "Bearer $accessToken",

                ),

                'body' => $jsonBody

            ]);





            $paymentExecutionBody = json_decode($paymentResponse->getBody()->getContents());

            return $paymentExecutionBody;

        } catch (\Exception $ex) {

            return $ex->getMessage();

        }

You can use the $paymentExecutionBody variable to save the details of the digital transfer in case of need as they will be stored in it.

  • Tags
  • Guzzle
  • Payment API
  • PayPal
Facebook Twitter Google+ LinkedIn Pinterest
Next article Javascript Image Compress using HTML5 Canvas & File API before Upload
Previous article Laravel vs Codeigniter which is better for Development

Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter

Related Posts

Laboratory Management System (LIMS) in PHP MySQL – A Complete Guide MySQL
November 19th, 2025

Laboratory Management System (LIMS) in PHP MySQL – A Complete Guide

Stripe Payment Gateway Charge Credit Card with PHP Example API
November 5th, 2025

Stripe Payment Gateway Charge Credit Card with PHP Example

How to show Image before upload JavaScript & HTML5 FileReader() API
November 4th, 2025

How to show Image before upload JavaScript & HTML5 FileReader()

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe
Get new posts by email:
Powered by follow.it
Advertisement
Like us
Recent Posts
  • Laboratory Management System (LIMS) in PHP MySQL – A Complete Guide
  • WhatsApp chatbot in Python using Dialogflow.com
  • Convert your website into a Desktop App for Windows, Mac, Linux
  • Useful JavaScript globals
  • The Art of Debugging in Software Development: A Comprehensive Guide
Categories
  • API
  • Bootstrap
  • Bot
  • CSS
  • CSS 3
  • Database
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • Laravel
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • Web 3.0
  • WordPress
Weekly Tags
  • PHP
  • javascript
  • How to
  • laravel
  • css
  • HTML to PDF
  • jQuery
  • api
  • Web Development
  • MYSQL
  • About
  • Privacy Policy
  • Back to top
© PHPLift.net. All rights reserved.