Monday, September 23, 2019



Paypal Subscription Payment In Angular App



Hi Friends today you learn Paypal payment subscription.




Recurring payment system, we can use the following payment services for this,
  1. Paypal
  2. Stripe
  3. Braintree
  4. Amazon Payments 

Introduction

Paypal subscription payment allows as to pay a bill on a regular basis of interval. 
And everything managed by Paypal itself.PayPal Subscriptions lets you accept recurring payments for your service. When you set up Subscriptions, you can offer subscribers a trial period with special introductory rates or a regular rate. Subscribers receive billings according to the terms you specify, so you know automatically which payments you have and have not received.
Let’s start to implementation

Step 1:
we need to create a developer account on paypal developer portal
 URL https://developer.paypal.com

Paypal sandbox have two account for testing purpose one for a buyer and another for the seller.



Step 2
Create App and get credentials for Paypal configuration so Log in your Paypal developer account select My Apps & Credentials choose sandbox and create the app.

Ex. 1




ex 2





Step 3
After the creation of the app, Paypal gives us client id and secret key which are required when we configure Paypal subscription on our application.





Step 4
  1. create product
  2. create plans
  3. subscription implementation

Create Product using Paypal API service

Reference URL : https://developer.paypal.com/docs/subscriptions/integrate/#2-create-a-product
As of now, we create a product using postman so heare we use paypal clientId as username and scret key for password for basic authenticatuin please check below image.

  1. Request API : https://api.sandbox.paypal.com/v1/catalogs/products  
  2.   
  3. Request Payload :   
  4.   
  5. {  
  6.   "name""Audio Streaming Service",  
  7.   "description""Video streaming service",  
  8.   "type""SERVICE",  
  9.   "category""SOFTWARE",  
  10.   "image_url""https://example.com/streaming.jpg",  
  11.   "home_url""https://example.com/home"  
  12. }  

Responce Message


  1. {  
  2.     "id""PROD-6VT064825G2003241",  
  3.     "name""Audio Streaming Service",  
  4.     "description""Video streaming service",  
  5.     "create_time""2019-09-13T18:35:58Z",  
  6.     "links": [  
  7.         {  
  8.             "href""https://api.sandbox.paypal.com/v1/catalogs/products/PROD-6VT064825G2003241",  
  9.             "rel""self",  
  10.             "method""GET"  
  11.         },  
  12.         {  
  13.             "href""https://api.sandbox.paypal.com/v1/catalogs/products/PROD-6VT064825G2003241",  
  14.             "rel""edit",  
  15.             "method""PATCH"  
  16.         }  
  17.     ]  
  18. }  


Ex







Create Plan using Paypal API service

Reference URL - https://developer.paypal.com/docs/subscriptions/integrate/#3-create-a-plan

  1. Request API : https://api.sandbox.paypal.com/v1/billing/plans  
  2.   
  3. Request Payload :  
  4.   
  5. {  
  6.         "product_id""PROD-6VT064825G2003241",  
  7.         "name""Basic Plan",  
  8.         "description""Basic plan",  
  9.         "billing_cycles": [  
  10.           {  
  11.             "frequency": {  
  12.                 "interval_unit""MONTH",  
  13.                 "interval_count": 1  
  14.             },  
  15.             "tenure_type""TRIAL",  
  16.             "sequence": 1,  
  17.             "total_cycles": 1  
  18.           },  
  19.             {  
  20.               "frequency": {  
  21.                 "interval_unit""MONTH",  
  22.                 "interval_count": 1  
  23.               },  
  24.               "tenure_type""REGULAR",  
  25.               "sequence": 2,  
  26.               "total_cycles": 12,  
  27.               "pricing_scheme": {  
  28.                 "fixed_price": {  
  29.                   "value""10",  
  30.                   "currency_code""USD"  
  31.                 }  
  32.               }  
  33.             }  
  34.           ],  
  35.         "payment_preferences": {  
  36.           "service_type""PREPAID",  
  37.           "auto_bill_outstanding"true,  
  38.           "setup_fee": {  
  39.             "value""10",  
  40.             "currency_code""USD"  
  41.           },  
  42.           "setup_fee_failure_action""CONTINUE",  
  43.           "payment_failure_threshold": 3  
  44.         },  
  45.         "quantity_supported"true,  
  46.         "taxes": {  
  47.           "percentage""10",  
  48.           "inclusive"false  
  49.         }  
  50.     }   


Plan API  Responce Message 

  1. {  
  2.     "id""P-20D52460DL479523BLV56M5Y",  
  3.     "product_id""PROD-6VT064825G2003241",  
  4.     "name""Basic Plan",  
  5.     "status""ACTIVE",  
  6.     "description""Basic plan",  
  7.     "create_time""2019-09-13T18:56:55Z",  
  8.     "links": [  
  9.         {  
  10.             "href""https://api.sandbox.paypal.com/v1/billing/plans/P-20D52460DL479523BLV56M5Y",  
  11.             "rel""self",  
  12.             "method""GET"  
  13.         },  
  14.         {  
  15.             "href""https://api.sandbox.paypal.com/v1/billing/plans/P-20D52460DL479523BLV56M5Y",  
  16.             "rel""edit",  
  17.             "method""PATCH"  
  18.         },  
  19.         {  
  20.             "href""https://api.sandbox.paypal.com/v1/billing/plans/P-20D52460DL479523BLV56M5Y/deactivate",  
  21.             "rel""self",  
  22.             "method""POST"  
  23.         }  
  24.     ]  
  25. }  


Same way we can create two or more plans based on our web application services.like MONTHLY | QUARTERLY | HALFYEARLY | YEARLY

Subscription Button implementation

Here I’m using Angular Application you can use any web Application for apply Paypal services.
HTML code
First, we have to add Paypal library file on our page.

<script    src="https://www.paypal.com/sdk/js?client-id=ClientId&vault=true">    </script> 

  1. <div class="row col-md-12 align-items-center justify-content-center">  
  2.   
  3.   <div class="col">   
  4.     <select id="ddlplan" [(ngModel)]="planId">  
  5.       <option value="">Select Plan </option>  
  6.       <option value="P-20D52460DL479523BLV56M5Y">SINGLE DEVICE MONTHLY </option>  
  7.       <option value="P-69V0714408520914GLVT2OWY">SINGLE DEVICE QUARTERLY</option>  
  8.       <option value="P-05879618SP259004GLVT2RQY">SINGLE DEVICE HALFYEARLY</option>  
  9.       <option value="P-4GG19360L3165531MLVT2T3Q">SINGLE DEVICE YEARLY</option>  
  10.       <option value="P-7EY82590S1568242RLVT2WCI">MULTIPLE DEVICE MONTHLY</option>  
  11.       <option value="P-41W43904VD877272YLVT2X4I">MULTIPLE DEVICE QUARTERLY</option>  
  12.       <option value="P-56995822K5295852ELVT2ZMA">MULTIPLE DEVICE HALFYEARLY</option>  
  13.       <option value="P-6LF21374AM914681BLVT22OY">MULTIPLE DEVICE YEARLY</option>  
  14.       <option value="P-3NS34795KB814132ALVTDMKI">Test Daily Plan</option>  
  15.     </select></div>  
  16.   <div class="col">  
  17.     <div #paypal></div>  
  18.   </div>  
  19.   
  20. </div>  

TS Code / Javascript code Ex.
  1. import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';  
  2. declare var paypal;  
  3. @Component({  
  4.   selector: 'app-paypal',  
  5.   templateUrl: './paypal.component.html',  
  6.   styleUrls: ['./paypal.component.css']  
  7. })  
  8. export class PaypalComponent implements OnInit {  
  9.   @ViewChild('paypal') paypalElement: ElementRef;  
  10.   constructor() { }  
  11.   planId: any;  
  12.   subcripId: any;  
  13.   basicAuth = 'Basic QWNWUTBIX05QTVlWMDIzSDhMM3Y2alhNcDRVdaUN2V0M4Mmo4a19hodjdkdS14M3F4dFJ6Y2pNTnRPcGN6OUpPdjU1TW9jTllsEV1p5WURWNm46RUZJRWtJd0dYdDFJSTdFRmlEdVQ3UWExV2ZXWDZnYmw3Z2w5ajgwZVlsVjI1ODdfUTRHSUxCSWxZfOGg1SzRRZTFhMZU1yVgFZGRThIWXAyRjA=';  //Pass your ClientId + scret key
  14.   
  15.   ngOnInit() {     
  16.     const self = this;  
  17.     this.planId = 'P-20D52460DL479523BLV56M5Y';  //Default Plan Id
  18.     paypal.Buttons({  
  19.       createSubscription: function (data, actions) {  
  20.         return actions.subscription.create({  
  21.           'plan_id': self.planId,  
  22.         });  
  23.       },  
  24.       onApprove: function (data, actions) {  
  25.         console.log(data);  
  26.         alert('You have successfully created subscription ' + data.subscriptionID);  
  27.         self.getSubcriptionDetails(data.subscriptionID);  
  28.       },  
  29.       onCancel: function (data) {  
  30.         // Show a cancel page, or return to cart  
  31.         console.log(data);  
  32.       },  
  33.       onError: function (err) {  
  34.         // Show an error page here, when an error occurs  
  35.         console.log(err);  
  36.       }  
  37.   
  38.     }).render(this.paypalElement.nativeElement);  
  39.   
  40.   }  
  41.   // ============Start Get Subcription Details Method============================  
  42.   getSubcriptionDetails(subcriptionId) {  
  43.     const xhttp = new XMLHttpRequest();  
  44.     xhttp.onreadystatechange = function () {  
  45.       if (this.readyState === 4 && this.status === 200) {  
  46.         console.log(JSON.parse(this.responseText));  
  47.         alert(JSON.stringify(this.responseText));  
  48.       }  
  49.     };  
  50.     xhttp.open('GET''https://api.sandbox.paypal.com/v1/billing/subscriptions/' + subcriptionId, true);  
  51.     xhttp.setRequestHeader('Authorization'this.basicAuth);  
  52.   
  53.     xhttp.send();  
  54.   }  
  55.   // ============END Get Subcription Details Method========================  
  56.   
  57. }  


Output Window
Run Angular project and choose your plan and then click on Paypal subscription button .then redirect Paypal payment server login with sandbox buyer account choose to your payment mode and click on subscribe to the service.
For example, check below image.


Paypal Subscription Payment In Angular App



After successfully subscription process Paypal gives us subscription id and buyer details like buyer email, subscription plan details, etc. we can save subscription id on our database.

Now we can log in with developer sandbox Marchant account and check buyer subscription details on Paypal sandbox.PayPal sandbox URL https://www.sandbox.paypal.com/us/signin



Summary

In this write-up, we discussed Paypal subscription payment (Recurring Payments System) with a sample angular application and postman API call example.

In my next article, I will discuss how to deploy .Net and angular Application on IIS server using deployment tools like Jenkins and Teamcity.
Any feedback related to this article is most welcome.