Add GooglePay payment process

This commit is contained in:
Pedro Silva 2023-08-23 11:20:40 +01:00
parent dc81b76f17
commit f3d6da7c29
No known key found for this signature in database
GPG key ID: E2EE20C0669D24B3
4 changed files with 165 additions and 34 deletions

View file

@ -1,9 +1,15 @@
import SingleProductActionHandler from '../../../ppcp-button/resources/js/modules/ActionHandler/SingleProductActionHandler';
import UpdateCart from '../../../ppcp-button/resources/js/modules/Helper/UpdateCart';
import ErrorHandler from '../../../ppcp-button/resources/js/modules/ErrorHandler';
import SimulateCart from "../../../ppcp-button/resources/js/modules/Helper/SimulateCart";
import onApprove from '../../../ppcp-button/resources/js/modules/OnApproveHandler/onApproveForContinue';
class GooglepayManager {
constructor(buttonConfig) {
constructor(buttonConfig, ppcpConfig) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.allowedPaymentMethods = null;
this.merchantInfo = null;
@ -85,7 +91,7 @@ class GooglepayManager {
// add merchant info maybe
paymentDataCallbacks: {
//onPaymentDataChanged: onPaymentDataChanged,
onPaymentAuthorized: this.onPaymentAuthorized,
onPaymentAuthorized: this.onPaymentAuthorized.bind(this),
}
});
@ -102,7 +108,9 @@ class GooglepayManager {
const button =
paymentsClient.createButton({
onClick: this.onButtonClick.bind(this),
allowedPaymentMethods: [this.baseCardPaymentMethod]
allowedPaymentMethods: [this.baseCardPaymentMethod],
buttonType: 'pay',
buttonSizeMode: 'fill',
});
jQuery(this.buttonConfig.button.wrapper).append(button);
}
@ -132,19 +140,54 @@ class GooglepayManager {
const googlePayConfig = await paypal.Googlepay().config();
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = googlePayConfig.allowedPaymentMethods;
paymentDataRequest.transactionInfo = this.transactionInfo();
paymentDataRequest.transactionInfo = await this.transactionInfo();
paymentDataRequest.merchantInfo = googlePayConfig.merchantInfo;
paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];
return paymentDataRequest;
}
transactionInfo() {
return {
countryCode: 'US',
currencyCode: 'USD',
totalPriceStatus: 'FINAL',
totalPrice: '2.01' // Your amount
async transactionInfo() {
//-------------
function form() {
return document.querySelector('form.cart');
}
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
const actionHandler = new SingleProductActionHandler(
null,
null,
form(),
errorHandler,
);
const hasSubscriptions = PayPalCommerceGateway.data_client_id.has_subscriptions
&& PayPalCommerceGateway.data_client_id.paypal_subscriptions_enabled;
const products = hasSubscriptions
? actionHandler.getSubscriptionProducts()
: actionHandler.getProducts();
return new Promise((resolve, reject) => {
(new SimulateCart(
this.ppcpConfig.ajax.simulate_cart.endpoint,
this.ppcpConfig.ajax.simulate_cart.nonce,
)).simulate((data) => {
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str // Your amount
});
}, products);
});
//-------------
}
//------------------------
@ -157,28 +200,64 @@ class GooglepayManager {
return new Promise((resolve, reject) => {
this.processPayment(paymentData)
.then(function (data) {
resolve({ transactionState: "SUCCESS" });
console.log('resolve: ', data);
resolve(data);
})
.catch(function (errDetails) {
console.log('resolve: ERROR', errDetails);
resolve({ transactionState: "ERROR" });
});
});
}
async processPayment(paymentData) {
return new Promise(async function (resolve, reject) {
console.log('processPayment');
return new Promise(async (resolve, reject) => {
try {
// Create the order on your server
const {id} = await fetch(`/orders`, {
method: "POST",
body: ''
// You can use the "body" parameter to pass optional, additional order information, such as:
// amount, and amount breakdown elements like tax, shipping, and handling
// item data, such as sku, name, unit_amount, and quantity
// shipping information, like name, address, and address type
// const {id} = await fetch(`/orders`, {
// method: "POST",
// body: ''
// // You can use the "body" parameter to pass optional, additional order information, such as:
// // amount, and amount breakdown elements like tax, shipping, and handling
// // item data, such as sku, name, unit_amount, and quantity
// // shipping information, like name, address, and address type
// });
//-------------
console.log('ppcpConfig:', this.ppcpConfig);
function form() {
return document.querySelector('form.cart');
}
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
const actionHandler = new SingleProductActionHandler(
this.ppcpConfig,
new UpdateCart(
this.ppcpConfig.ajax.change_cart.endpoint,
this.ppcpConfig.ajax.change_cart.nonce,
),
form(),
errorHandler,
);
const createOrderInPayPal = actionHandler.createOrder();
let id = await createOrderInPayPal(null, null);
console.log('PayPal Order ID:', id);
//-------------
console.log('paypal.Googlepay().confirmOrder : paymentData', {
orderId: id,
paymentMethodData: paymentData.paymentMethodData
});
console.log('paypal.Googlepay().confirmOrder : paymentData', paymentData);
const confirmOrderResponse = await paypal.Googlepay().confirmOrder({
orderId: id,
paymentMethodData: paymentData.paymentMethodData
@ -186,21 +265,59 @@ class GooglepayManager {
console.log('paypal.Googlepay().confirmOrder : confirmOrderResponse', confirmOrderResponse);
/** Capture the Order on your Server */
if(confirmOrderResponse.status === "APPROVED"){
const response = await fetch(`/capture/${id}`,
{
method: 'POST',
}).then(res => res.json());
if(response.capture.status === "COMPLETED")
resolve({transactionState: 'SUCCESS'});
else
if (confirmOrderResponse.status === "APPROVED") {
// const response = await fetch(`/capture/${id}`,
// {
// method: 'POST',
// }).then(res => res.json());
console.log('onApprove', this.ppcpConfig);
let approveFailed = false;
const approveOrderAndContinue = onApprove({
config: this.ppcpConfig
}, errorHandler);
console.log('approveOrderAndContinue', {
order_id: id
});
await approveOrderAndContinue({
order_id: id
}, {
restart: () => new Promise((resolve, reject) => {
approveFailed = true;
resolve();
})
});
console.log('approveFailed', approveFailed);
if (approveFailed) {
resolve({
transactionState: 'ERROR',
error: {
intent: 'PAYMENT_AUTHORIZATION',
message: 'TRANSACTION FAILED',
message: 'FAILED TO APPROVE',
}
})
}
resolve({transactionState: 'SUCCESS'});
// if (response.capture.status === "COMPLETED")
// resolve({transactionState: 'SUCCESS'});
// else
// resolve({
// transactionState: 'ERROR',
// error: {
// intent: 'PAYMENT_AUTHORIZATION',
// message: 'TRANSACTION FAILED',
// }
// })
} else {
resolve({
transactionState: 'ERROR',