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
}
]
Related
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>
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.
I'm getting an instance.requestpaymentmethod is not a function when I was just following along the tutorial for custom-field integration found here:
https://developers.braintreepayments.com/start/tutorial-hosted-fields-node
The error happens when I click on the "Pay" button.
Did anyone solve this problem? My assumption is that the code isn't updated or the script sources changed somewhat. If anyone from Braintree can actually help, that'll be great.
Thanks!
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
I took a look at the example code snippet in the guide you shared and I was able to find the culprit. First off, the error you're getting is expected as the requestPaymentMethod method actually belongs to our Drop-In UI solution and the Hosted Fields JS library doesn't have such module. I informed our Documentation team to get that code example updated.
That being said, you can find a working example in our Hosted Fields guide. If you check the function (hostedFieldsErr, hostedFieldsInstance) callback function, you'll see that the payment nonce is created by the tokenize function of the hostedFieldsInstance.
I also ran into this issue today. Use the following code in <script> tag. It will work for you.
var form = document.querySelector('#hosted-fields-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: '<YOUR_TOKENIZATION_KEY>'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
console.log('Got a nonce: ' + payload.nonce);
$.ajax({
type: 'POST',
url: '<YOUR_API_URL>',
data: { 'paymentMethodNonce': payload.nonce }
}).done(function (result) {
hostedFieldsInstance.teardown(function (teardownErr) {
if (teardownErr) {
console.error('Could not tear down Drop-in UI!');
} else {
console.info('Drop-in UI has been torn down!');
$('#submit-button').remove();
}
});
if (result.success) {
$('#checkout-message').html('<h1>Success</h1><p>Your Drop-in UI is working! Check your sandbox Control Panel for your test transactions.</p><p>Refresh to try another transaction.</p>');
} else {
console.log(result);
$('#checkout-message').html('<h1>Error</h1><p>Check your console.</p>');
}
});
});
}, false);
});
});
I want to accept payment in Multiple currencies & also autofill the Address/Name in PayPal form using Express Checkout method
I have tried going through various posts, paypal getting started, paypal community, but not able to find if it possible.
Currently, using Express Checkout I'm able to receive payment on changing the get parameter of the script.
<script src="https://www.paypal.com/sdk/js?client-id=valueOfClientID¤cy=GBP"> </script>
Is is possible to pass the currency & name/address details in below code?
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '24'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
});
});
}
}).render('#paypal-button-container');
</script>
Based on the currency dynamically inject the script to the page and pass the address object as mentioned in the link
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