Note : Incomplete Code
The PayPal is one the most popular and reliable mode of the payment transaction in mobile and web technology. In Ionic, we can easily integrate PayPal and other transaction modes in ionic apps. The Ionic framework provides Cordova plugin to implement PayPal in ionic.
In this example, we will learn how to integrate PayPal sandbox method in the ionic app backend supported by Woocommerce site.
We have to follow certain steps to achieve our task.
- First, we need to have a PayPal account. In the PayPal developer account, we need to create an app in PayPal. Click on the dashboard, we have the option to create a new REST API app.
- Every app has a Client ID, we will use the sandbox API credential. We need to use sandbox client API later. For the real application, we have to use live credentials.
- In the Account section, we can create any number of an account with a balance to test the working of PayPal through the sandbox method.
- We have to install the following plugin.
$ ionic cordova plugin add com.paypal.cordova.mobilesdk
$ npm install --save @ionic-native/paypal
We have to register the PayPal provider in app.module.ts file.
import { PayPal } from '@ionic-native/paypal';
providers: [
...
PayPal,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
In HTML template we have to add, following code
<ion-header>
<ion-navbar color="primary">
<ion-title>Paypal</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item>
<ion-label>Payment Method</ion-label>
<ion-select [(ngModel)]="paymentMethod">
<ion-option *ngFor="let p of paymentMethods" value="{{p.method_id}}">
{{ p.method_title}}
</ion-option>
</ion-select>
</ion-item>
</ion-list>
</ion-content>
<ion-footer>
<button ion-button block color="danger" (click)="placeOrder()">Place Order</button>
</ion-footer>
Add the following code in paymentPage.ts
import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import * as WC from 'woocommerce-api';
import { HomePage } from '../home/home';
import { PayPal, PayPalPayment, PayPalConfiguration } from '@ionic-native/paypal';
@Component({
selector: 'page-checkout',
templateUrl: 'checkout.html',
})
export class CheckoutPage {
WooCommerce: any;
newOrder: any;
paymentMethods: any[];
paymentMethod: any;
billing_shipping_same: boolean;
userInfo : any;
constructor(public navCtrl: NavController, public navParams: NavParams,
public storage: Storage, public alertCtrl: AlertController, public payPal: PayPal) {
this.newOrder = {};
this.newOrder.billing_address = {};
this.newOrder.shipping_address = {}
this.billing_shipping_same = false;
this.paymentMethods = [
{ method_id: "bacs", method_title: "Direct Bank Transfer"},
{ method_id: "cheque", method_title: "Cheque Payment"},
{ method_id: "chod", method_title: "Cash on Delivery"},
{ method_id: "paypal", method_title: "Paypal" }];
this.WooCommerce = WC({
url: "http://*****************.us",
consumerKey: "********************************",
consumerSecret: "****************************"
});
}
placeOrder(){
let orderItems: any[] = [];
let data: any = {};
let paymentData: any = {};
this.paymentMethods.forEach( (element, index) => {
if(element.method_id == this.paymentMethod ){
paymentData = element;
}
});
data = {
payment_details : {
method_id: paymentData.method_id,
method_title : paymentData.method_title,
paid: true
},
billing_address : this.newOrder.billing_address,
shipping_address : this.newOrder.shipping_address,
customer_id : this.userInfo.id || '',
line_items: orderItems
};
if(paymentData.method_id == "paypal"){
this.payPal.init({
PayPalEnvironmentProduction: 'YOUR_PRODUCTION_CLIENT_ID',
PayPalEnvironmentSandbox: '******************************'
}).then(() => {
// Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction
this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({
// Only needed if you get an "Internal Service Error" after PayPal login!
//payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal
})).then(() => {
this.storage.get("cart").then((cart) => {
let total = 0.00;
cart.forEach((element, index) =>{
orderItems.push({ product_id: element.product.id, quantity: element.qty });
total = total + (element.product.price * element.qty);
});
let payment = new PayPalPayment(total.toString(), 'USD', 'Description', 'sale');
this.payPal.renderSinglePaymentUI(payment).then(( response ) => {
// Successfully paid
alert(JSON.stringify(response));
data.line_items = orderItems;
let orderData: any = {};
orderData.order = data;
this.WooCommerce.postAsync('orders', orderData, (err, data, res) => {
alert("Order placed successfully !");
let response = (JSON.parse(data.body).order);
this.alertCtrl.create({
title: "Order Placed Successfully",
message: "Your order has been placed successfully. Your order number is " + response.order_number,
buttons: [{
text: "OK",
handler: () => {
this.navCtrl.setRoot(HomePage);
}
}]
}).present();
})
})
}, () => {
// Error or render dialog closed without being successful
});
}, () => {
// Error in configuration
});
}, () => {
// Error in initialization, maybe PayPal isn't supported or something else
});
} else {
this.storage.get("cart").then( (cart) => {
cart.forEach( (element, index) => {
orderItems.push({
product_id: element.product.id,
quantity: element.qty
});
});
data.line_items = orderItems;
let orderData: any = {};
orderData.order = data;
this.WooCommerce.postAsync("orders", orderData).then( (data) => {
let response = (JSON.parse(data.body).order);
this.alertCtrl.create({
title: "Order Placed Successfully",
message: "Your order has been placed successfully. Your order number is " + response.order_number,
buttons: [{
text: "OK",
handler: () => {
this.navCtrl.setRoot(HomePage);
}
}]
}).present();
})
})
}
}
ionViewDidLoad() {
console.log('ionViewDidLoad CheckoutPage');
}
}
Implement PayPal in Ionic WooCommerce