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

Using the PayPal Payments API with PHP and Guzzle

January 31st, 2017 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.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • Guzzle
  • Payment API
  • PayPal
Facebook Twitter Google+ LinkedIn Pinterest
Next article Examining variable types in PHP

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

Stripe Payment Gateway Charge Credit Card with PHP API
February 15th, 2021

Stripe Payment Gateway Charge Credit Card with PHP

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry Framework
February 1st, 2021

6 Reasons Laravel is the Top PHP Framework in the Web Development Industry

12 Reasons to Choose PHP for Developing Website Guide
November 17th, 2020

12 Reasons to Choose PHP for Developing Website

Leave a Reply Cancel reply

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

Advertisement
Recent Posts
  • Stripe Payment Gateway Charge Credit Card with PHP
  • How to building responsive WordPress theme using Bootstrap
  • 6 Reasons Laravel is the Top PHP Framework in the Web Development Industry
  • 9 Best Programming languages you should learn in 2021
  • 12 Reasons to Choose PHP for Developing Website
Categories
  • API
  • Bootstrap
  • CSS
  • CSS 3
  • Designing
  • Framework
  • Guide
  • HTML
  • HTML 5
  • JavaScript
  • jQuery
  • MySQL
  • Node.js
  • oAuth
  • Payment
  • PHP
  • Python
  • Social
  • Tips
  • WordPress
Weekly Tags
  • PHP
  • api
  • How to
  • PHP Basics
  • Programming Habits
  • HTML5
  • PHP framework
  • Download
  • laravel
  • css
  • About
  • Privacy Policy
  • Back to top
© PHPLift 2020. All rights reserved.