The following code uses the PayPal Javascript SDK together with JReviews custom fields to generate dynamic PayPal buy buttons.
Create a new banner custom field and paste the code below in the description field.
The code below uses the following tags which are automatically replaced from the listings' fields. Update them based on your fields' names and requirements.
- {title} - for the product name
- {jr_price|value} - unformatted value for the jr_price field
- {alias} - used for the product unique SKU - fill free to replace with a custom field or the {listing_id}.
Make sure to also update the PPClientID with your actual PayPal Client ID which you need to generate in your PayPal Developer Dashboard under App && Credentials by creating a new App.
Make sure to also update the PPClientID with your actual PayPal Client ID which you need to generate in your PayPal Developer Dashboard under App && Credentials by creating a new App.
The result looks something like this, which may vary based on your account settings and location:
<div
x-data="{
name: '{title}',
price: {jr_price|value},
currency: 'USD',
sku: '{alias}',
PPClientID: 'sb',
init() {
this.$nextTick(() => {
this.loadPaypal().then(() => this.renderButton())
})
},
get formattedPrice() {
return new Intl.NumberFormat(undefined, {
style: 'currency',
currency: this.currency
}).format(this.price);
},
loadPaypal() {
if (window.paypal) return Promise.resolve();
return new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = 'https://www.paypal.com/sdk/js?client-id=' + this.PPClientID + '¤cy=' + this.currency;
s.onload = () => resolve();
s.onerror = () => reject(new Error('PayPal SDK failed to load'));
document.head.appendChild(s);
});
},
renderButton() {
paypal.Buttons({
style: {
color: 'gold'
},
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [{
reference_id: this.sku,
custom_id: this.sku,
description: this.name,
amount: {
currency_code: this.currency,
value: this.price.toFixed(2),
breakdown: {
item_total: {
currency_code: this.currency,
value: this.price.toFixed(2)
}
}
},
items: [{
name: this.name,
unit_amount:{
value: this.price.toFixed(2),
currency_code: this.currency
},
quantity: '1',
sku:this.sku
}]
}]
});
},
onApprove: (data, actions) =>
actions.order.capture().then(details => {
console.log('✅ Transaction completed by', details.payer.name.given_name);
})
}).render(this.$refs.paypalContainer);
}
}"
class="product-pay"
>
<div x-ref="paypalContainer"></div>
</div>