braintree.paypalCheckout.create add dynamical amount to the paypal button - paypal

I use HostedFields for credit card and paypal web for paypal.
So inside of braintree.client.create i have braintree.hostedFields.create and braintree.paypalCheckout.create.
Code example of paypal:
braintree.paypalCheckout.create({
client: clientInstance
}, function (paypalCheckoutErr, paypalCheckoutInstance) {
if (paypalCheckoutErr) {
console.error('Error creating PayPal Checkout:', paypalCheckoutErr);
return;
}
paypal.Button.render({
env: 'sandbox',
commit: true,
buttonStyle: {
color: 'blue',
shape: 'rect',
size: 'medium'
},
payment: function () {
return paypalCheckoutInstance.createPayment({
flow: 'checkout',
locale: ''+langanalytics+'',
amount: '10.00',
currency: 'EUR'
});
},
onAuthorize: function (data, actions) {
return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
document.getElementById("paynonce").value = payload.nonce;
document.getElementById("paymentform").submit();
});
},
onCancel: function (data) {
console.log('checkout.js payment cancelled', JSON.stringify(data, 0, 2));
},
onError: function (err) {
console.error('checkout.js error', err);
}
}, '#paypal-button').then(function () {
});
});
The problem is according to my client he want a single page checkout, where the amount get generated dynamically.
For example if someone change the country or payment method the price can change for some €. A click EventListener start the calculation and changes the total sum in real time.
My Problem:
I cant change the amount of my paypal intialization of this part:
return paypalCheckoutInstance.createPayment({
flow: 'checkout',
locale: ''+langanalytics+'',
amount: '10.00',
currency: 'EUR'
});
Is there any way to update the amount outsite of the function as soon as total sum changes (i have full control of this).
I already tried to intialize the whole braintree.client.create new on total sum change but i get errors from hosted fields a instance is already created and for paypal i recieve multiple buttons.

Related

PayPal Checkout JS SDK onError not triggering when cards not processed

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.

Can i get payments to my paypal account with help of paypal api

Is it possible to sell some non-physical product and get its payment directly into your personal paypal account? Has anyone did something like this?
It is certainly possible, and actually very easy. What kind of integration are you looking for? Maybe one of the buttons at http://www.paypal.com/buttons would be a good start for you.
Here is a sample of a VERY Simple checkout Script using REST API (Client Side Only Code)
First add this line to "head" of your HTML page:
{
<script src="https://www.paypal.com/sdk/js?client-
id=YOUR USER ID GOES HEREg&disable-funding=credit,card"></script>
}
Then add this to where you want your PayPal Button(s) to be on your HTML Page:
'<div style="width:30%" id="paypal-button-container"><p style="font-size:small">
<b>Checkout using your PayPal Acount <br>
or if you do not have a PayPal Account, you can pay with your Debit or Credit
Card (option at bottom of Pop-up Window).</b></p></div>
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
onError: function (err) {
alert('An Error Occured, returning you to the Form. Please Check that you
are not submitting a Zero Amount and have Filled out the Form');
},
style: {
layout: 'horizontal',
color: 'gold',
shape: 'pill',
label: 'checkout',
size: 'responsive',
tagline: 'true',
},
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
description: 'GnG Order',
amount: {
value: cartTotal
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name +
'!');
});
if (details.error === 'INSTRUMENT_DECLINED') {
return actions.restart();
};
}
}).render('#paypal-button-container');
</script>'
That should do it for you. Be sure to login to the Developer Panel to set up your API credentials.

How to dynamically change currency & pass other data in PayPal Express Checkout

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&currency=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

Paypal webhooks events are not triggered in sandbox

Hello I am using the following setup
Created paypal merchant and customer sandbox accounts
Configured paypal REST API app
Added a webhook url to my server and have validated that it works using the webhook simulator
Used the Express Checkout javascript implementation found here
I am able to make successful payments when viewing the notifications in sandbox but no webhook is ever triggered???
Below is a sample of my javascript implementation that I have used, please not that it's embedded in a coldfusion script file hence the use hashtags.
`
var items = #paypalItems#;
// Render the PayPal button
paypal.Button.render({
env: '#application.config.paypal.bSandbox ? "sandbox" : "production"#', // sandbox | production
commit: true,
//style the button
style: {
label: 'pay'
},
// PayPal Client IDs - replace with your own
client: {
sandbox: '#application.config.paypal.sandbox_key#',
production: '#application.config.paypal.live_key#'
},
// Wait for the PayPal button to be clicked
payment: function(data, actions) {
// Make a client-side call to the REST api to create the payment
return actions.payment.create({
payment: {
transactions: [{
amount: {
total: #trim(numberFormat( application.oCart.getTotal(bDiscount=1,bShipping=1) , "99999999.99" ))#,
currency: "AUD",
details: {
subtotal: #trim(numberFormat( application.oCart.getTotal() - application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
tax: #trim(numberFormat(application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
shipping: #trim(numberFormat( application.oCart.oShipping.getCartShippingAmount(country=session.fcbshoppingCart.order.shippingCountry), "99999999.99" ))#
}
},
invoice_number: "#orderNumber#",
item_list: {
items: items,
shipping_address: {
recipient_name: "#session.fcbshoppingCart.customer.firstName# #session.fcbshoppingCart.customer.lastName#",
line1: "#session.fcbshoppingCart.order.shippingAddress1#",
line2: "#session.fcbshoppingCart.order.shippingAddress2#",
city: "#session.fcbshoppingCart.order.shippingSuburb#",
country_code: "#paypalCountryCode#",
postal_code: "#session.fcbshoppingCart.order.shippingPostCode#",
state: "#session.fcbshoppingCart.order.shippingState#"
}
}
}]
}
});
},
// Wait for the payment to be authorized by the customer
onAuthorize: function(data, actions) {
console.log( "Paypal Authorize:", data );
// Execute the payment
return actions.payment.execute().then(function(payment) {
console.log( "Paypal Response:", payment );
//payment has been accepted so we can now generate an order
$.ajax({
type: "get",
url: "/apps/paypal/createOrder.cfm",
data: {
transactionNumber: "#orderNumber#",
payPalPaymentId: data.paymentID
},
dataType: "json",
success: function( res ) {
console.log('edharry create order data', res);
if( res.BPAYMENTPROCEED ) {
$('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
//lets redirect to the checkout success page.
window.location.href = window.location.origin + '/shop/checkout/confirmation?productOrder=' + res.PRODUCTORDER.OBJECTID;
} else {
//need to handle a failed transaction
$('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
}
},
error: function() {
//lets show an error
$('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
}
})
$('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
});
},
onCancel: function(data) {
console.log('The payment was cancelled!');
}
}, '##paypal-button-container');`
This is an ongoing issue with Paypal. They are aware of this issue and are currently working to resolve this.

PayPal client-side? What is minimum code required for multiple buttons?

I'm working with .Net, trying to implement multiple buttons.
I'm getting an answer from PayPal (payment id, payer-id, etc.), but everything is client-side. How can I check the payment on server-side?
Do I need to implement all this code for each button?
<script>
paypal.Button.render({
env: 'production', // Optional: specify 'sandbox' environment
client: {
sandbox: 'xxxxxxxxx',
production: 'xxxxxxxxx'
},
payment: function() {
var env = this.props.env;
var client = this.props.client;
return paypal.rest.payment.create(env, client, {
transactions: [
{
amount: { total: '1.00', currency: 'USD' }
}
]
});
},
commit: true, // Optional: show a 'Pay Now' button in the checkout flow
onAuthorize: function(data, actions) {
// Optional: display a confirmation page here
return actions.payment.execute().then(function() {
// Show a success page to the buyer
});
}
}, '#paypal-button');
</script>
To get the information on the server side, you can pass data.paymentID to your server side and use it to make a REST call to paypal: https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/advanced-payments-api/show-payment-details/
To render multiple buttons you do need to call paypal.Button.render() multiple times, but if you need to you can do this in a for loop, or something.