I would like to:
Have the user log into paypal
Fetch the users information (billing&shipping addresses)
Then calculate the shipping fee
Place the payment
But, how can I receive the address and calculate the fee before I place the payment?
<script>
paypal.Button.render({
// Configure environment
env: '<?php echo $paypal->paypalEnv; ?>',
client: {
sandbox: '<?php echo $paypal->paypalClientID; ?>',
production: '<?php echo $paypal->paypalClientID; ?>'
},
// Customize button (optional)
locale: 'de_DE',
style: {
size: 'small',
color: 'gold',
shape: 'rect',
},
// Set up a payment
payment: function (data, actions) {
return actions.payment.create({
transactions: [{
amount: {
total: '10',
currency: 'EUR'
}
}]
});
},
// Execute the payment
onAuthorize: function (data, actions) {
return actions.payment.execute()
.then(function () {
window.location = "process.php?paymentID="+data.paymentID+"&token="+data.paymentToken+"&payerID="+data.payerID+"&pid=<?php echo $productID; ?>";
});
}
}, '#paypal-button');
</script>
Instead of "return actions.payment.execute()" calling the execute directly, I would like to fetch the address, then show the final basket with all the costs and then click on "pay now" - how can I do this?
Your sample is an older version of PayPal's checkout.js
Start by switching to the latest version of the PayPal Checkout: https://developer.paypal.com/docs/checkout/
Demo of client-side pattern: https://developer.paypal.com/demo/checkout/#/pattern/client
In the onApprove function, you can use the data object to get the address and do Javascript calculations about adding shipping before the capture() call with a modified total.
If you want to do the calculations on your server rather than in Javascript (more secure/reliable), use a server-side pattern:
https://developer.paypal.com/demo/checkout/#/pattern/server
thank you! mhhh okay but what has to be in the serverside part? i dont see any example of the actions to receive the buyers adress information before checkout and afterwards. ?
/demo/checkout/api/paypal/order/create
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
I am trying to integrate paypal api with PHP compared to the old button form that I have used to date on my sites. But there is one thing that is not clear to me, is it more correct to integrate paypal with client_id and secret or through the codes provided in the account panel (api username, api password and signature)? I followed the REST API integration guide (version 2) but they require client_id and secret. So what is the data in the account panel for? Anyone can clarify my ideas? Thank you
The API username, password, and signature is used by the classic NVP/SOAP APIs, which are much older than the REST API. They exist only for backwards compatibility with old shopping cart software and such integrations.
The v2/checkout/orders API should be used for current PayPal Checkout integrations. Pair two routes on your server (one for create order, one for capture order) that return/output only JSON data (never any HTML or text) with this JS approval flow.
I would go with JS SDK inline integration - requires client-id only and is more flexible than checkout buttons. Also creates nice user experience as if staying on the page (no redirects to 3rd party site). See all demos here.
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
// note: custom_id (127 chars) will be passed later back in capture
purchase_units: [{
amount: {
value: amtDue.toFixed(2),
currency: 'EUR'
},
description : description,
custom_id : '<?= $encryptedPaymentData ?>'
}]
});
},
onApprove: function(data, actions) {
$("#global-spinner").show();
// set custom capture handler
return actions.order.capture().then(function(details) {
$.ajax({
type: "POST",
url: "/paypal/success",
data: ({
details : details,
ad : amtDue,
desc : description,
_token : '<?= $csrf ?>'
}),
success: function(resp) {
$("#global-spinner").hide();
window.showThankYou(); // some "thank you" function
},
error: function() {
$("#global-spinner").hide();
alert("Connection error.");
}
});
});
},
onError: function (err) {
// some custom function - send error data to server logger
window.handlePaypalError(err, description, amtDue);
}
}).render('#paypal-button-container');
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.
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.
I'm trying to integrate Paypal Express Checkout into simple Shopping Cart. There are different ways to do that. Paypal recommends to choose between Basic or Advanced integration and version 4.0 of checkout.js (with REST API). So far so good.
I created Paypal App in my Paypal account to get credentials and start testing it.
The test was OK, but there are some misunderstandings here.
Checkout.js send the amount ( 1.00 ) and currency ( EUR ) to the Paypal servers via REST API (along with my credentials). And if the payment is finished OK - callback function onAuthorize is triggered and there are two parameters with response (data and actions). Well, here I call my own AJAX function to write transaction response data in my database. BUT... I get here only PaymentID and PayerID of the paid transaction?!! And if I want to search later into web interface of paypal.com - there is no such thing as PaymentID. There is only TransactionID ??? How to get other transaction details in the response in onAutorize callback function? How can I get TransactionID here to write down in my database? May be here I have to call Paypal API, or have to implement Paypal IPN (instant payment notification )? BUT how to call IPN API, if I don't have TransactionID :)
<div style="width: 906px; text-align: right; height: 100px;
margin-top: 50px;">
<div id="paypal-button"></div>
</div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
paypal.Button.render({
env: 'production', // Optional: specify 'sandbox' environment
style: {
size: 'medium',
shape: 'rect'
},
client: {
sandbox: 'xxx-my-credentials-xxx',
production: 'xxx-my-credentials-xxx'
},
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: 'EUR' }
}
]
});
},
commit: true, // Optional: show a 'Pay Now' button in the checkout flow
onAuthorize: function(data, actions) {
// Optional: display a confirmation page here
var EXECUTE_PAYMENT_URL = 'payment-process.php';
paypal.request.post(EXECUTE_PAYMENT_URL, { paymentID: data.paymentID, payerID: data.payerID, transactionID: data.transactionID, data: data }) .then(function(data) { }) .catch(function(err) { });
return actions.payment.execute().then(function() {
// Show a success page to the buyer
});
}
}, '#paypal-button');
</script>
To read the information from the transaction you need to call and save data JSON in database
return actions.payment.execute().then(function() {
actions.payment.get().then(function(data) {
if(data.state === 'approved'){
console.log(data);
var transactionId = data.id;
alert("Transaction ID: "+ transactionId + " \n State: " +data.state);
}else{
console.log(data);
}
});
});