I've adapated the client-side example from Paypal's docs and my code works fine if I add it directly to a page, but I want to create a reusable component, and when I try to do that and import the component, it just doesn't render. When I try to inspect the element in Chrome's dev tools, all I get is <div class></div>. Here is the code:
---
const clientId = import.meta.env.PAYPAL_CLIENT_ID;
---
<!-- Replace "test" with your own sandbox Business account app client ID -->
<script is:inline src={`https://www.paypal.com/sdk/js?client-id=${clientId}¤cy=USD`}></script>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<script is:inline>
paypal.Buttons({
// Sets up the transaction when a payment button is clicked
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [{
amount: {
value: '77.44' // Can also reference a variable or function
}
}]
});
},
// Finalize the transaction after payer approval
onApprove: (data, actions) => {
return actions.order.capture().then(function(orderData) {
// Successful capture! For dev/demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
const transaction = orderData.purchase_units[0].payments.captures[0];
alert(`Transaction ${transaction.status}: ${transaction.id}\n\nSee console for all available details`);
// When ready to go live, remove the alert and show a success message within this page. For example:
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
Related
With the below code, along with the PayPal button a "PayPal Credit" button is shown. But I want to display Debit or Credit card black button instead of that PayPal Credit button. Please help me to find out the solution. I don't want to change anything in script tag, is there any change to be made?
<form class="form-horizontal">
<div class="form-group">
<!-- PayPal Shortcut Checkout -->
<div id="paypalCheckoutContainer"></div>
</div>
</form>
//Javascript
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script type="text/javascript">
paypal.Button.render({
// Set your environment
env: '<?= PAYPAL_ENVIRONMENT ?>',
// Set style of buttons
style: {
layout: 'vertical', // horizontal | vertical
size: 'medium', // medium | large | responsive
shape: 'pill', // pill | rect
color: 'gold', // gold | blue | silver | black,
fundingicons: false, // true | false,
tagline: false, // true | false,
},
// Set allowed funding sources
funding: {
allowed: [
paypal.FUNDING.CARD,
paypal.FUNDING.CREDIT
],
disallowed: [ ]
},
// Show the buyer a 'Pay Now' button in the checkout flow
commit: false,
// payment() is called to start the payment flow when a button is clicked
payment: function() {
const postData = {
'original': JSON.parse('<?= json_encode($orderDetails) ?>'),
'update': null,
'flow': 'shortcut'
};
return request.post(
'<?= $rootPath.URL['services']['orders']['create'] ?>',
postData
).then(function(returnObject) {
return returnObject.data.id;
});
},
// onAuthorize() is called when the buyer approves the payment
onAuthorize: function(data) {
const postData = {
key: "order_id",
value: data.orderID
};
submitForm('<?= $baseUrl.URL['redirect']['orders']['return_url'] ?>?flow=shortcut', postData);
},
// onCancel() is called when the buyer cancels payment authorization
onCancel: function(data) {
let url = "<?= $baseUrl ?>pages/orders/error?type=error",
postData = {
key: "error",
value: data
};
submitForm(url, postData);
},
// onError() is called when there is an error in this Checkout.js script
onError: function (error) {
let url = "<?= $baseUrl ?>pages/orders/error?type=error",
postData = {
key: "error",
value: error
};
submitForm(url, postData);
}
}, '#paypalCheckoutContainer');
</script>
You are using the old "v4" checkout.js (old demo site). Upgrade to a current PayPal Checkout integration (which uses the "v5" JS SDK), and the black button will be available.
Since you appear to be using a backend for initial payment/order creation and later execution/capture , this front-end approval code has the best sample to work from: https://developer.paypal.com/demo/checkout/#/pattern/server
Since you ask about disabling the PayPal Credit button, for v5 the simplest way is to add &disable-funding=credit on the SDK src line
My current working solution.
<template>
<div>
<div ref="paypal"></div>
</div>
</template>
<script>
export default {
mounted: function () {
const script = document.createElement("script");
script.src = "https://www.paypal.com/sdk/js?client-id=SECRET";
script.addEventListener("load", this.setLoaded);
document.body.appendChild(script);
},
methods: {
openPaymentAmountModal() {
this.isPaymentAmountModalVisible = true;
},
closePaymentAmountModal() {
this.isPaymentAmountModalVisible = false;
},
setLoaded: function () {
window.paypal.Buttons({
createOrder: function (data, actions) {
// This function sets up the details of the transaction, including the amount and line item details.
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function (data, actions) {
// This function captures the funds from the transaction.
return actions.order.capture().then(function (details) {
// This function shows a transaction success message to your buyer.
alert('Transaction completed by ' + details.payer.name.given_name);
});
}
}).render(this.$refs.paypal);
}
}
}
</script>
In modals, I had to load the script again.
How to load this Paypal script globally in the NuxtJs application on components or pages level?
I had the same integration in my project, and import the script in my page:
head() {
return {
script: [{
src: 'https://www.paypal.com/sdk/js?client-id=<CLIENT_ID>'
}],
}
},
Then put PayPal's .render() method in the mounted().
You can always add the script to the head, in the SPA index.htm - this means it will always be available and you do not need to wait for the load.
This means you can call the button creation against a known div element anytime. If it is in a modal, the same would apply, although you might wish to adjust the render target then.
you can also put the script in the script array in nuxt.config.js, by doing this the script is made available globally in your application.
Like this:
script: [
{
src: 'ttps://www.paypal.com/sdk/js?client-id=<CLIENT_ID>',
async: true
}
]
While setting up, PayPal client code to test server integration, from https://developer.paypal.com/docs/archive/checkout/how-to/server-integration/
My code is as follows:
<html>
<head>
<title>TEST PAYMENT</title>
</head>
<body>
<div id="paypal-button"></div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
paypal.Button.render({
env: 'sandbox', // Or 'production'
// Set up the payment:
// 1. Add a payment callback
payment: function(data, actions) {
// 2. Make a request to your server
return actions.request.post('/api/paypal/create-payment')
.then(function(res) {
console.log(res);
// 3. Return res.id from the response
return res.id;
});
},
// Execute the payment:
// 1. Add an onAuthorize callback
onAuthorize: function(data, actions) {
// 2. Make a request to your server
return actions.request.post('/api/paypal/execute-payment', {
paymentID: data.paymentID,
payerID: data.payerID
})
.then(function(res) {
// 3. Show the buyer a confirmation message.
});
}
}, '#paypal-button');
</script>
</body>
</html>
When I open the page.
When I click the button, a modal window shows up for a second and closed with the following errors.
The checkout.js integration you're attempting to use is deprecated.
Here is the current JS SDK to call your server with: https://developer.paypal.com/demo/checkout/#/pattern/server
I am trying to redirect customers to an error page for my website if their card cannot be processed. It not working and all I can get is the standard PayPal alert that says "Things don't appear to be working at the moment."
What confuses me especially is that I have a redirect page for purchase approval that IS working correctly in the onApprove function (seen below).
PayPal JavaScript SDK says this is the code to redirect customers to a customer URL:
paypal.Buttons({
onError: function (err) {
// For example, redirect to a specific error page
window.location.href = "/your-error-page-here";
}
}).render('#paypal-button-container');
This is what my onError function looks like:
onError: function (err) {
//My Redirect Page
window.location.href = "https://www.fitnessbydylan.com/error-page.html";
}
This is my full Javascript for my PayPal button.
<script>
function initPayPalButton() {
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'paypal',
},
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{"description":"1 MONTH DIGITAL COACHING","amount":{"currency_code":"USD","value":0.06,"breakdown":{"item_total":{"currency_code":"USD","value":0.06},"shipping":{"currency_code":"USD","value":0},"tax_total":{"currency_code":"USD","value":0.00}}}}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Simulate a mouse click:
window.location.href = "http://www.fitnessbydylan.com/purchase-page.html";
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
},
onError: function (err) {
// My Redirect Page
window.location.href = "https://www.fitnessbydylan.com/error-page.html";
},
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
onError is only triggered when there is a technical problem with loading or using the buttons, which is a very rare situation. It is not triggered for card processing problems.
What is "/checkout" in the below line ?. Actually it referring localpath.
Can you please suggest me the appropriate action URL ?
Also, Can you suggest me where do I give the IPN URL / Syntax ?
<form id="myContainer" method="post" action="/checkout"></form>
<script>
window.paypalCheckoutReady = function () {
paypal.checkout.setup('<Your-Merchant-ID>', {
environment: 'sandbox',
container: 'myContainer'
});
};
</script>
[paypal Integration] https://developer.paypal.com/docs/classic/express-checkout/in-context/integration/
Thanks,
Raja K
This describes it:
A basic Express Checkout integration assumes that you are sending the
API calls from your own server using a <form> or <a>.
Essentially, your existing call to SetExpressCheckout (that would obtain a Paypal token) that you use to redirect (in the "standard" Paypal Express Checkout flow).
The linked sample should hopefully clear things up - you'll see the form action (and a link) POST (GET for the a) to some server implementation (the ip address in the sample) of SetExpressCheckout.
Hth..
I can help you with single page PayPal pay now button actually I use this one of my projects
<script src="https://www.paypal.com/sdk/js?client-id=XXXXXXXXXXXXXXXXX">
</script>
<div id="paypal-button-container"> </div>
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '1230'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed');
// Call your server to save the transaction
return fetch('codes/paypalapi.php?invo=123', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
amount: data.amount
})
});
});
}
}).render('#paypal-button-container');
</script>
change codes/paypalapi.php?invo=123 with your callback url