PayPal is the most widely used application for digital payment services in the world. Angular improves PayPal interaction. Due to the global service, it is suitable for a variety of currencies. It accepts payments in Indian Rupees, US Dollars, and other major currencies. It is having a subscription, subscription bundle, and one-time payment options. PayPal operates and connected with payment services via several interfaces, including PayPal payment standards, PayPal subscriptions, payment renewals, invoicing, and payment acceptance and rejection. Working with angular programming requires a different level of imagination. Develop an Angular algorithm to process PayPal payments
Steps to implement Angular for payment flow
Consider the Angular method below, which makes use of the algorithm. It is primarily involved with PayPal developer documentation. It shows how to order, capture, and store server-side operations via the backend. The payment buttons are constructed and managed through series of real-time callbacks. Some requests coincide with their service requests. As a result, we’ll see an Angular model to its full extent.
paypal.Buttons({
style: {
layout: 'vertical',
color: 'blue',
shape: 'rect',
label: 'paypal'
}
}).render('#paypal-button-container');
/*Then that directive is created with several inputs
to set up these style objects in the
Angular component and use them as HTMLElement*/
@Directive({
selector: 'wm-paypal'
})
export class PayPalButtons {
private _buttons: Buttons;
constructor(private paypal: PayPal, private el: ElementRef ) {}
// Style inputs
@Input() label: ButtonsLabel;
@Input() color: ButtonsColor;
@Input() shape: ButtonsShape;
@Input() layout: ButtonsLayout;
@Input() tagline: boolean;
@Input() height: number; // 25..55
ngOnChanges(changes: SimpleChanges) {
// Prepare to render with an arrow function
const render = () =>
(this._buttons = this.buttons()).render(this.el.nativeElement);
// Render the new buttons immediately or right after closing the previous ones
this._buttons && this._buttons.close().then(render) || render();
}
// Creates the Smart Buttons
private buttons(): Buttons {
// Reverts on the PayPal service for rendering the buttons
return this.paypal.Buttons({
// Builds the buttons style based on inputs
style: {
layout: this.layout,
label: this.label,
color: this.color,
shape: this.shape,
tagline: this.layout === 'horizontal' && this.tagline,
height: this.height
},
...
});
}
ngOnDestroy() {
// Closes the buttons
this._buttons && this._buttons.close()
}
}
In the presence of our directives ( ElementRef ), only ElementRef is using to render the buttons. In this case, we used directives rather than components. It provides a control for the ElementRef directive. It should be present in it. We studied how PayPal global objects aim for services during their installation in this investigation of code events. Angularity considers the shape, color, label, and height of an object. The actual implementation is to perform using ngOnChanges(). All inputs are updated when the method is applied. Due to the lack of a specified update() method, use the render() function. When you close it, the same thing happens: it calls the ngOnDestroyer function.
Disablement of buttons:
After our payment has started and progressed, it is necessary to call onInit to enable and disable the processor’s capabilities. Disabling a function is achieved by using the disabled$ process, which defaults to “enabled.” When we use the disabled() return value to create a new status log, the disabled() return value is set to the current disabled. PayPal does not indicate when a payment has been disabled. It uses @Hostbinding() decorators. It displays how component style is created by removing the button structure and events using @Hostbinding() decorators. The buttons enable after the onInit() function callback is completed.
@Directive({ selector: 'wm-paypal' }) export class PayPalButtons { ... constructor(private paypal: PayPal, private el: ElementRef, @Optional() private processor: PayPalProcessor) {} /** Order request to be processed when the button is clicked. */ @Input() request: OrderRequest /** Emits on Approve */ @Output() approve = new EventEmitter(); /** Emits on Cancel */ @Output() cancel = new EventEmitter(); /** Emits on Error */ @Output() error = new EventEmitter(); // Creates the Smart Buttons private buttons(): Buttons { // Reverts on the PayPal service for rendering the buttons return this.paypal.Buttons({ // Builds the style of the buttons based on inputs style: {...}, ... // Handles order creation for checkouts createOrder: (_,actions) => actions.order.create(this.request), // Handles order capturing and subscription activation onApprove: (data: OnApproveData, actions: OnApproveActions) => { // Emits the approve event this.approve.emit(data); // Delegates the PayPalProvessor whenever defined if(!!this.processor && typeof(this.processor.onApprove) == 'function') { return this.processor.onApprove(data, actions); } }, // Simply emits the cancel event onCancel: data => this.cancel.emit(data), // Simply emits the error event onError: data => this.error.emit(data), ... }); } ... }
• The payment process begins with a request() and ends with the creation of the order. It has a difficult step in the second section of the payment flow. This step includes the data that will use to approve the payment. It should be responsive to business needs; it should call back on the same backend services. It uses PayPalProcessor class. This statement defines the control function onApprove(). When the caller provides the processor, they are responsible for implementing payments. These tasks include authorization and settlements. It also provides the backend resource that performs the core payment process and returns the results. Additional functions, such as cancel() and onError(), have been aligned into the system’s overall structure. These functions use when payment cancelation or errors occur. Everything in this section is dependent on the component ‘wm-PayPal. It provides an easy-to-use input and error/cancels function. AppComponent is an alternative to using PayPalProcessor by considering child interactions. It is having interactions with wm-PayPal as a PayPal Processor. This method completes the process of installing and loading the PayPal SDK.
HTML conversion of PayPal activity through Angular
>> ng new `PayPalWithAngular
Now open fresh created set in visual studio code and install bootstrap by using the following command
>> npm install bootstrap –save
Now open styles.css file and add Bootstrap file reference purpose. To include reference in styles.css file, do it as follow,
>> @import ‘~bootstrap/dist/css/bootstrap.min.css’;
Open Index.html file and do as follow in head section
<script src=“https://www.paypal.com/sdk/js?client-id=AYoonm7wJij_oQg63X-0Br0eTgGr5sE-kOVYox49Y8yfyIJUTv6PIZCZqoOo7_BonWlOvl8a9n1Yh6wQN&vault=true”></script>
Furthermore, open app.component.html and add HTML,
<div class="row col-md-12 align-items-center justify-content-center"> <div class="col"> <select id="ddlplan" [(ngModel)]="planId"> <option value="">Select Plan </option> <option value="P-20D52460DL479523BLV56M5Y">SINGLE DEVICE MONTHLY </option> <option value="P-69V0714408520914GLVT2OWY">SINGLE DEVICE QUARTERLY</option> <option value="P-05879618SP259004GLVT2RQY">SINGLE DEVICE HALFYEARLY</option> <option value="P-4GG19360L3165531MLVT2T3Q">SINGLE DEVICE YEARLY</option> <option value="P-7EY82590S1568242RLVT2WCI">MULTIPLE DEVICE MONTHLY</option> <option value="P-41W43904VD877272YLVT2X4I">MULTIPLE DEVICE QUARTERLY</option> <option value="P-56995822K5295852ELVT2ZMA">MULTIPLE DEVICE HALFYEARLY</option> <option value="P-6LF21374AM914681BLVT22OY">MULTIPLE DEVICE YEARLY</option> <option value="P-3NS34795KB814132ALVTDMKI">Test Daily Plan</option> </select> </div> <div class="col"> <div #paypal></div> </div> </div>
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; declare var paypal; @Component({ selector: 'app-paypal', templateUrl: './paypal.component.html', styleUrls: ['./paypal.component.css'] }) export class PaypalComponent implements OnInit { @ViewChild('paypal') paypalElement: ElementRef; constructor() { } planId: any; subcripId: any; basicAuth = 'Basic QWNWUTBIX05QTVlWMDIz SDhMM3Y2alhNcDRVdaUN2V0M4Mmo4a 19hodjdkdS14M3F4dFJ6Y2pNTnRPcGN6OUpPdjU1TW9jTllsEV1p 5WURWNm46RUZJRWtJd0dYdDFJSTdFRmlEdVQ3UWExV2ZXWDZnYmw 3Z2w5ajgwZVlsVjI1ODdfUTRHSUxCSWxZfOGg1SzRRZ TFhMZU1yVgFZGRThIWXAyRjA='; //Pass your ClientId + scret key ngOnInit() { const self = this; this.planId = 'P-20D52460DL479523BLV56M5Y'; //Default Plan Id paypal.Buttons({ createSubscription: function (data, actions) { return actions.subscription.create({ 'plan_id': self.planId, }); }, onApprove: function (data, actions) { console.log(data); alert('You have successfully created subscription ' + data.subscriptionID); self.getSubcriptionDetails(data.subscriptionID); }, onCancel: function (data) { // Show a cancel page, or return to cart console.log(data); }, onError: function (err) { // Show an error page here, when an error occurs console.log(err); } }).render(this.paypalElement.nativeElement); } // ============Start Get Subcription Details Method============= getSubcriptionDetails(subcriptionId) { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log(JSON.parse(this.responseText)); alert(JSON.stringify(this.responseText)); } }; xhttp.open('GET', 'https://api.sandbox.paypal.com/v1/billing/subscriptions/' + subcriptionId, true); xhttp.setRequestHeader('Authorization', this.basicAuth); xhttp.send(); } // ============END Get Subcription Details Method============ }