Skip to content
pakainfo

Pakainfo

Web Development & Good Online education

Guest Posting Sites
  • Home
  • Blog
  • Categories
  • Tools
  • Full Form
  • Guest Post
  • Advertise
  • About
  • Contact Us

Paypal Recurring Payments PHP REST API Example

December 3, 2019 Pakainfo Technology, Laravel, php, Programming Leave a comment

Today, We want to share with you Paypal Recurring Payments PHP REST API Example.In this post we will show you wordpress plugin require another plugin, hear for paypal recurring payment integration in codeigniter we will give you demo and example for implement.In this post, we will learn about PHP Setting up subscriptions and recurring payments for your business with an example paypal payment gateway integration in php source code download.

Paypal Recurring Payments PHP REST API Example

Contents

  • Paypal Recurring Payments PHP REST API Example
    • Handling Recurring Payments in PHP Source code
    • MySQL Database structure
    • Read
    • Summary
    • Related posts

There are the Following The simple About Paypal Recurring Payments PHP REST API Example Full Information With Example and payment gateway in php source code.

As I will cover this Post with live Working example to develop Paypal Recurring Payments for Installment Plan in PHP, so the Recurring payments using Paypal Merchant SDK or Paypal REST API is used for this example is following below.

Handling Recurring Payments in PHP Source code

app_name/index.php

<?php 
require 'src/init_model.php';


if (!empty($_GET['status'])) {
    if($_GET['status'] == "success") {



        $plan_id = $db->prepare("
            SELECT plan_id
            FROM user_transactions_dtl
            WHERE hash = :hash
            ");
        $plan_id->execute([
            'hash' => $_SESSION['tamil_hash']
        ]);

        $plan_id = $plan_id->fetchObject()->plan_id;


        $token = $_GET['token'];
        $agreement = new \PayPal\Api\Agreement();
        
        try {
            // Execute agreement
            $agreement->execute($token, $devApiData);



            //Update transaction

            $updateTransaction = $db->prepare("
                UPDATE user_transactions_dtl
                SET complete = 1
                WHERE plan_id = :plan_id
                ");

            $updateTransaction->execute([
                'plan_id' => $plan_id
            ]);

            // Set the user as broker
            $setMember = $db->prepare("
                UPDATE users
                SET broker = 1
                WHERE id = :broker_id
                ");

            $setMember->execute([
                'broker_id' => $_SESSION['broker_id']
            ]);

            //Unset paypal Hash
            unset($_SESSION['tamil_hash']);
            header('Location: ../app_name/paypal/complete.php');

        } catch (PayPal\Exception\PayPalConnectionException $ex) {
            header("Location: ../app_name/paypal/error.php");
            echo $ex->getCode();
            echo $ex->getData();
            die($ex);
        } catch (Exception $ex) {
            header("Location: ../app_name/paypal/error.php");
            die($ex);
        }
    } else {
        echo "user canceled agreement";
        header('Location: ../app_name/paypal/cancelled.php');
    }
    exit;
}

if (! empty($_POST["subscribe"])) {
    require_once "./src/createSubscriptionPlan.php";
}

?>


<!DOCTYPE html>
<html>
<head>
<title>how to setup recurring payments in paypal</title>
<style>
    body {
        font-family: Arial;
        color: #212121;
    }

    #subscription-plan {
        padding: 20px;
        border: #E0E0E0 2px solid;
        text-align: center;
        width: 200px;
        border-radius: 3px;
        margin: 40px auto;
    }

    .plan-info {
        font-size: 1em;
    }

    .plan-desc {
        margin: 10px 0px 20px 0px;
        color: #a3a3a3;
        font-size: 0.95em;
    }

    .price {
        font-size: 1.5em;
        padding: 30px 0px;
        border-top: #f3f1f1 1px solid;
    }

    .btn-subscribe {
        padding: 10px;
        background: #e2bf56;
        width: 100%;
        border-radius: 3px;
        border: #d4b759 1px solid;
        font-size: 0.95em;
    }
</style>
</head>
<body>
<div id="pakainfo subscription-plan">
    <div class="plan-info">Golden</div>
    <div class="plan-desc">Read Golden.</div>
    <div class="price">$45 / month</div>

    <div>
        <form method="post">

            <input type="hidden" name="plan_name"
                value="golden" /> <input type="hidden"
                name="plan_description"
                value="simple Web PHP flexify Example." />

            <?php if($user->broker): ?>
                <p>You are a broker!</p>
            <?php else: ?>
                <p>You are not a broker!</p>
                <input type="submit" name="subscribe" value="Subscribe"
                class="btn-subscribe" />
            <?php endif; ?> 


        </form>
    </div>
</div>
</body>
</html>

app_name/composer.json

{
    "require": {
        "paypal/rest-api-sdk-php": "*"
    }
}

run bellow Commands

cd/app_name> composer update

app_name/src/init_model.php

<?php

use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

session_start();

$_SESSION['broker_id'] = 1;

require __DIR__ . '/../vendor/autoload.php';

// API
$devApiData = new ApiContext(
  new OAuthTokenCredential(
    'KLn3rLlkDFGHcCpTytgRRn_K692qwc4dd3yFGxOzedrwFFhj-DMA4866qaRwurhgA1QE7jyTtfjbgEDX',
    'FJDD8DFDRuEsmL3HelvjE0CmqscVKG9eM3jYY9GoxYDd75YUY5CacZSITwVgxWED8Di_TbFHuTiNCy-U'
  )
);

/*$devApiData->setConfig([
	'mode' => 'sandbox',
	'http.ConnectionTimeOut' => 30,
	'log.LogEnabled' => false,
	'log.FileName' => '',
	'log.LogLevel' => 'FINE',
	'validation.level' => 'log'
]);*/

$db = new PDO('mysql:host=localhost;dbname=paypal_site', 'root', '');

$user = $db->prepare("select * from users where id= :broker_id");

$user->execute(['broker_id' => $_SESSION['broker_id']]);
$user = $user->fetchObject();

app_name/src/createSubscriptionPlan.php

<?php

use PayPal\Api\ChargeModel;
use PayPal\Api\Currency;
use PayPal\Api\MerchantPreferences;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\Plan;
use PayPal\Api\Patch;
use PayPal\Api\PatchRequest;
use PayPal\Common\PayPalModel;

require 'init_model.php';
// Create a new billing plan
if (! empty($_POST["plan_name"]) && ! empty($_POST["plan_description"])) {

$plan = new Plan();
$plan->setName($_POST["plan_name"])
    ->setDescription($_POST["plan_description"])
    ->setType('FIXED');

// Set billing plan definitions
$paymentDefinition = new PaymentDefinition();
$paymentDefinition->setName('Regular Payments')
    ->setType('REGULAR')
    ->setFrequency('DAY')
    ->setFrequencyInterval('1')
    ->setCycles('3')
    ->setAmount(new Currency(array(
    'value' => 3,
    'currency' => 'USD'
)));

// Set charge models
$chargeModel = new ChargeModel();
$chargeModel->setType('SHIPPING')->setAmount(new Currency(array(
    'value' => 1,
    'currency' => 'USD'
)));
$paymentDefinition->setChargeModels(array(
    $chargeModel
));

// Set merchant preferences
$merchantPreferences = new MerchantPreferences();
$merchantPreferences->setReturnUrl('http://localhost/app_name/index.php?status=success')
    ->setCancelUrl('http://localhost/app_name/index.php?status=cancel')
    ->setAutoBillAmount('yes')
    ->setInitialFailAmountAction('CONTINUE')
    ->setMaxFailAttempts('0')
    ->setSetupFee(new Currency(array(
    'value' => 1,
    'currency' => 'USD'
)));

$plan->setPaymentDefinitions(array(
    $paymentDefinition
));

$plan->setMerchantPreferences($merchantPreferences);

    try {
        $livePlan = $plan->create($devApiData);
        
        //Generate and store hash
        $hash = md5($livePlan->getId());
        $_SESSION['tamil_hash'] = $hash; 

            //transaction storage
        $store = $db->prepare("
            INSERT INTO user_transactions_dtl (broker_id, plan_id, hash, complete)
            VALUES (:broker_id, :plan_id, :hash, 0)
            ");

        $store->execute([
            'broker_id' => $_SESSION['broker_id'],
            'plan_id' => $livePlan->getId(),
            'hash' => $hash
        ]);

        try {
            $patch = new Patch();
            $value = new PayPalModel('{"state":"ACTIVE"}');
            $patch->setOp('replace')
                ->setPath('/')
                ->setValue($value);
            $patchRequest = new PatchRequest();
            $patchRequest->addPatch($patch);
            $livePlan->update($patchRequest, $devApiData);
            $patchedPlan = Plan::get($livePlan->getId(), $devApiData);
            
            require_once "createSubscriptionAgreement.php";
        } catch (PayPal\Exception\PayPalConnectionException $ex) {
            echo $ex->getCode();
            echo $ex->getData();
            die($ex);
        } catch (Exception $ex) {
            die($ex);
        }
    } catch (PayPal\Exception\PayPalConnectionException $ex) {
        echo $ex->getCode();
        echo $ex->getData();
        die($ex);
    } catch (Exception $ex) {
        die($ex);
    }
}
?>

app_name/src/createSubscriptionAgreement.php

<?php
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\ShippingAddress;
use PayPal\Api\Plan;

// Create a simple new agreement
$startDate = date('c', time() + 3600);
$agreement = new Agreement();
$agreement->setName('Pakainfo Golden Plan Subscription Agreement')
    ->setDescription('Pakainfo Golden Plan Subscription Billing Agreement')
    ->setStartDate($startDate);

//here choose or Set plan id
$plan = new Plan();
$plan->setId($patchedPlan->getId());
$agreement->setPlan($plan);

// here Add payer type
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$agreement->setPayer($payer);

//simple Adding shipping details
$shippingAddress = new ShippingAddress();
$shippingAddress->setLine1('9, swati park')
    ->setCity('Rajkot')
    ->setState('IN')
    ->setPostalCode('360001')
    ->setCountryCode('US');
$agreement->setShippingAddress($shippingAddress);

try {
    // Create a simple main user agreement
    $agreement = $agreement->create($devApiData);
    
    // Extract success approval URL to redirect user
    $approvalUrl = $agreement->getApprovalLink();
    
    header("Location: " . $approvalUrl);
    exit();
} catch (PayPal\Exception\PayPalConnectionException $ex) {
    echo $ex->getCode();
    echo $ex->getData();
    die($ex);
} catch (Exception $ex) {
    die($ex);
}
?>

app_name/paypal/cancelled.php
<!DOCTYPE html>
<html>
<head><title>Recurring payment in paypal every month in php</title></head>
<body>
 <p>You Cancelled.</p>
</body>
</html>

app_name/paypal/complete.php

<!DOCTYPE html>
<html>
<head><title>Setting up PayPal Recurring Payments in PHP</title></head>
<body>
 <p>Payment complete. <a href="../index.php">Go Home</a></p>
</body>
</html>

app_name/paypal/error.php

<!DOCTYPE html>
<html>
<head><title>PayPal recurring payments API</title></head>
<body>
 <p>Something Went Wrong.</p>
</body>
</html>

MySQL Database structure

Table structure for table `trans_details`

CREATE TABLE `trans_details` (
  `id` int(10) UNSIGNED NOT NULL,
  `broker_id` int(11) NOT NULL,
  `plan_id` varchar(255) NOT NULL,
  `hash` varchar(255) NOT NULL,
  `complete` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Indexes for table `trans_details`

ALTER TABLE `trans_details`
  ADD PRIMARY KEY (`id`);

Table structure for table `users_dtl`

CREATE TABLE `users_dtl` (
  `id` int(10) UNSIGNED NOT NULL,
  `username` varchar(20) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `broker` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Dumping data for table `users_dtl`

INSERT INTO `users_dtl` (`id`, `username`, `email`, `broker`) VALUES
(1, 'modi124', '[email protected]_name.com', 0);

Indexes for table `users_dtl`

ALTER TABLE `users_dtl`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `users_dtl`
--

ALTER TABLE `users_dtl`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;  

Web Programming Tutorials Example with Demo

Read :

  • Jobs
  • Make Money
  • Programming
Also Read This 👉   subtract hours - How to Subtract Hours from DateTime in PHP?

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about How to Manage Recurring Payments using PayPal Subscriptions in PHP.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Related posts:

  1. PayPal Subscriptions(recurring payments) Payment Gateway Integration in PHP Source Code Download
  2. PayPal Payment Gateway with PHP MySQL Database
  3. How to Integration PayPal Payment Gateway in PHP?
  4. laravel paypal integration Tutorial from Scratch for Beginners
  5. PHP Laravel 6 PayPal Payment Gateway API integration step by step
  6. Paypal Payment Gateway Integration using Java
  7. How to Integrate PayPal Payment Gateway in PHP?
  8. PayPal Payment Gateway PHP Source Code
Also Read This 👉   create rest api php mysql - PHP 8 CRUD REST API with MySQL & PHP PDO Example
cancel recurring payment paypal phpHandling Recurring PaymentsHow subscription billing cycles workHow to Manage Recurring Payments using PayPal Subscriptions in PHPpaypal billing agreement apipaypal express checkout php sdkpaypal php sdkpaypal recurring payment integration in codeigniterpaypal recurring payments api php examplepaypal recurring payments cancelPaypal Recurring Payments for Installment Plan in PHPpaypal recurring payments html formpaypal recurring payments personal accountPayPal REST API Samplespaypal rest sdkpaypal sdk phppaypal subscription ipnpaypal subscriptions apipaypal subscriptions cancelpaypal subscriptions using php sdkpaypal/rest-api-sdk-php laravelRecurring payments using Paypal Merchant SDK or Paypal REST APISetting up subscriptions and recurring payments for your business. paypal recurring payments feessubscription payment

Post navigation

Previous Post:PayPal Payment Gateway with PHP MySQL Database
Next Post:PHP Secure Session Management System

Advertise With Us

Increase visibility and sales with advertising. Let us promote you online.
Click Here
Guest Posting Sites

Write For Us

We’re accepting well-written informative guest posts and this is a great opportunity to collaborate.
Submit a guest post to [email protected]
Contact Us

Freelance web developer

Do you want to build a modern, lightweight, responsive website quickly?
Need a Website Or Web Application Contact : [email protected]
Note: Paid Service
Contact Me

Categories

3movierulz (64) Ajax (464) AngularJS (377) ASP.NET (61) Bio (109) Bollywood (108) Codeigniter (175) CSS (98) Earn Money (69) Education (61) Entertainment (130) fullform (86) Google Adsense (63) Highcharts (77) History (40) Hollywood (109) JavaScript (1357) Jobs (42) jQuery (1423) Laravel (1088) LifeStyle (53) movierulz4 (63) Mysql (1029) Mysqli (890) php (2121) Programming (2332) Python (97) Software (166) Software (88) Stories (98) tamilrockers (104) Tamilrockers kannada (64) Tamilrockers telugu (61) Tech (141) Technology (2392) Tips and Tricks (119) Tools (203) Top10 (477) Trading (89) Trending (71) VueJs (250) Web Technology (104) webtools (191) wordpress (166) World (322)

A To Z Full Forms

Access a complete full forms list with the meaning, definition, and example of the acronym or abbreviation.
Click Here
  • Home
  • About Us
  • Terms And Conditions
  • Write For Us
  • Advertise
  • Contact Us
  • Youtube Tag Extractor
  • Info Grepper
  • Guest Posting Sites
  • Increase Domain Authority
  • Social Media Marketing
  • Freelance web developer
  • Tools
Pakainfo 9-OLD, Ganesh Sco, Kothariya Ring Road, Chokadi, Rajkot - 360002 India
E-mail : [email protected]
Pakainfo

© 2023 Pakainfo. All rights reserved.

Top
Subscribe On YouTube : Download Source Code
We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype Guest Posting Sites