npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@agencycoda/ngx-paypal

v7.0.0

Published

Paypal integration for Angular

Downloads

24

Readme

npm version Build Status NPM

Angular PayPal

PayPal integration for Angular. For live example and documentation visit https://enngage.github.io/ngx-paypal/

This Angular library is based on PayPal's Javascript SDK. It does not support each and every feature of the JavaScript SDK so feel free to submit issues or PRs.

I strongly recommend checking out PayPal's docs linked above if you want to learn more about the flow of checkout process and meaning behind certain properties. There are ton of properties you can set within the createOrder method and good IDE will show you these properties so use that, I don't find it particulary useful to list all properties and their description here - PayPal docs is your friend.

Installation

npm install ngx-paypal --save

Import NgxPayPalModule in your module (i.e. AppModule)

Template

import { NgxPayPalModule } from 'ngx-paypal';
@NgModule({
  imports: [
    NgxPayPalModule,
    ...
  ],
})

Html code

<ngx-paypal [config]="payPalConfig"></ngx-paypal>

Creating orders on client

import {
    Component,
    OnInit
} from '@angular/core';
import {
    IPayPalConfig,
    ICreateOrderRequest 
} from 'ngx-paypal';

@Component({
    templateUrl: './your.component.html',
})
export class YourComponent implements OnInit {

    public payPalConfig ? : IPayPalConfig;

    ngOnInit(): void {
        this.initConfig();
    }

    private initConfig(): void {
        this.payPalConfig = {
            currency: 'EUR',
            clientId: 'sb',
            createOrder: (data) => < ICreateOrderRequest > {
                intent: 'CAPTURE',
                purchase_units: [{
                    amount: {
                        currency_code: 'EUR',
                        value: '9.99',
                        breakdown: {
                            item_total: {
                                currency_code: 'EUR',
                                value: '9.99'
                            }
                        }
                    },
                    items: [{
                        name: 'Enterprise Subscription',
                        quantity: '1',
                        category: 'DIGITAL_GOODS',
                        unit_amount: {
                            currency_code: 'EUR',
                            value: '9.99',
                        },
                    }]
                }]
            },
            advanced: {
                commit: 'true'
            },
            style: {
                label: 'paypal',
                layout: 'vertical'
            },
            onApprove: (data, actions) => {
                console.log('onApprove - transaction was approved, but not authorized', data, actions);
                actions.order.get().then(details => {
                    console.log('onApprove - you can get full order details inside onApprove: ', details);
                });

            },
            onClientAuthorization: (data) => {
                console.log('onClientAuthorization - you should probably inform your server about completed transaction at this point', data);
                this.showSuccess = true;
            },
            onCancel: (data, actions) => {
                console.log('OnCancel', data, actions);
                this.showCancel = true;

            },
            onError: err => {
                console.log('OnError', err);
                this.showError = true;
            },
            onClick: (data, actions) => {
                console.log('onClick', data, actions);
                this.resetStatus();
            },
        };
    }
}

Creating orders on server

import {
    Component,
    OnInit
} from '@angular/core';
import {
    IPayPalConfig,
    ICreateOrderRequest 
} from 'ngx-paypal';

@Component({
    templateUrl: './your.component.html',
})
export class YourComponent implements OnInit {

    public payPalConfig?: IPayPalConfig;

    ngOnInit(): void {
        this.initConfig();
    }

    private initConfig(): void {
        this.payPalConfig = {
            clientId: 'sb',
            // for creating orders (transactions) on server see
            // https://developer.paypal.com/docs/checkout/reference/server-integration/set-up-transaction/
            createOrderOnServer: (data) => fetch('/my-server/create-paypal-transaction')
                .then((res) => res.json())
                .then((order) => data.orderID),
            onApprove: (data, actions) => {
                console.log('onApprove - transaction was approved, but not authorized', data, actions);
                actions.order.get().then(details => {
                    console.log('onApprove - you can get full order details inside onApprove: ', details);
                });

            },
            onClientAuthorization: (data) => {
                console.log('onClientAuthorization - you should probably inform your server about completed transaction at this point', data);
                this.showSuccess = true;
            },
            onCancel: (data, actions) => {
                console.log('OnCancel', data, actions);
                this.showCancel = true;

            },
            onError: err => {
                console.log('OnError', err);
                this.showError = true;
            },
            onClick: (data, actions) => {
                console.log('onClick', data, actions);
                this.resetStatus();
            },
        };
    }
}

Authorizing on server

To authorize on payment on server, provide authorizeOnServer. If you do so, client validation is not used and therefore the onClientAuthorization will not be called.

import {
    Component,
    OnInit
} from '@angular/core';
import {
    IPayPalConfig,
    ICreateOrderRequest 
} from 'ngx-paypal';

@Component({
    templateUrl: './your.component.html',
})
export class YourComponent implements OnInit {

    public payPalConfig?: IPayPalConfig;

    ngOnInit(): void {
        this.initConfig();
    }

    private initConfig(): void {
        this.payPalConfig = {
            clientId: 'sb',
            // for creating orders (transactions) on server see
            // https://developer.paypal.com/docs/checkout/reference/server-integration/set-up-transaction/
            createOrderOnServer: (data) => fetch('/my-server/create-paypal-transaction')
                .then((res) => res.json())
                .then((order) => data.orderID),
            authorizeOnServer: (approveData) => {
                fetch('/my-server/authorize-paypal-transaction', {
                    body: JSON.stringify({
                    orderID: approveData.orderID
                    })
                }).then((res) => {
                    return res.json();
                }).then((details) => {
                    alert('Authorization created for ' + details.payer_given_name);
                });
            },
            onCancel: (data, actions) => {
                console.log('OnCancel', data, actions);
                this.showCancel = true;
            },
            onError: err => {
                console.log('OnError', err);
                this.showError = true;
            },
            onClick: (data, actions) => {
                console.log('onClick', data, actions);
                this.resetStatus();
            },
        };
    }
}

Multiple ngx-paypal components on the same page

If you want to have multiple PayPal buttons on the same page, you can do so only if they share some basic properties (e.g. currency, commit flag..) because these are configured via URL query parameters when requesting PayPal's javascript SDK. PayPal does not allow registesting multiple SDKs on the same page.

The key is to inject PayPalScriptService, register script manually and then call customInit with the PayPal API once your component is available. Note that if you use conditions (*ngIf) you will have to adjust the core accordingly because of the timings and call customInit once both PayPalApi has loaded and your component was initialized.

import {
    PayPalScriptService, IPayPalConfig
} from 'ngx-paypal';

export class YourComponent implements OnInit {

    public payPalConfig?: IPayPalConfig;

    @ViewChild('payPalElem1') paypalComponent1?:  NgxPaypalComponent;
    @ViewChild('payPalElem2') paypalComponent2?:  NgxPaypalComponent;

    constructor(
        private payPalScriptService: PayPalScriptService
    ) { }

    ngOnInit(): void {
        this.payPalConfig = {}; // your paypal config

        this.payPalScriptService.registerPayPalScript({
        clientId: 'sb',
        currency: 'EUR'
        }, (payPalApi) => {
            if (this.paypalComponent1) {
                this.paypalComponent1.customInit(payPalApi);
            }

            if (this.paypalComponent2) {
                this.paypalComponent2.customInit(payPalApi);
            }
        });
    }
}
  <ngx-paypal #payPalElem1 [config]="payPalConfig" [registerScript]="false"></ngx-paypal>
  <ngx-paypal #payPalElem2 [config]="payPalConfig" [registerScript]="false"></ngx-paypal>

Unit testing

Unit testing in Angular is possible, but a bit clunky because this component tries to dynamically include paypals's script if its not already loaded. You are not required to include in globally or manually which has a benefit of not loading until you actually use this component. This has a caveat though, since the load callback is executed outside of Angular's zone, performing unit tests might fail due to racing condition where Angular might fail the test before the script has a chance to load and initialize captcha.

A simple fix for this is wait certain amount of time so that everything has a chance to initialize. See example below:

beforeEach(() => {
        fixture = TestBed.createComponent(YourComponent);
        component = fixture.componentInstance;
        setTimeout(function () {
            fixture.detectChanges();
        }, 2000);
});

Breaking v5 release

Versions > 5 represent completely rewrite of the library and switch to latest PayPal JavaScript SDK. Its highly recommended to use this version. If you still wish to use previous version, check v4 branch for previous documentation.

Publishing lib

Under projects\ngx-paypal-lib run

npm run publish-lib

Publishing demo app

Under root, generate demo app with

npm run build-demo-gh-pages
npx ngh --dir=dist-demo