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
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 :
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.