Skip to content

Instantly share code, notes, and snippets.

@albertojacini
Last active September 20, 2022 08:09
Show Gist options
  • Save albertojacini/c2461617418adc5f18bf07a464aa5a83 to your computer and use it in GitHub Desktop.
Save albertojacini/c2461617418adc5f18bf07a464aa5a83 to your computer and use it in GitHub Desktop.
import * as React from 'react'
import { PayPalButton } from 'react-paypal-button-v2'
import Typography from '@material-ui/core/Typography'
import { PAYMENT_GATEWAYS, YG_EMAIL_BASE } from 'config'
import { Checkout as CheckoutInterface } from 'lib/queries/generatedTypes/Checkout'
interface PaypalOrderParams {
intent?: 'CAPTURE' | 'AUTHORIZE',
purchase_units: [
{
reference_id?
amount: {
currency_code?: string,
value: string
},
payee?: {
email_address
merchant_id?
}
payment_instruction?: {
platform_fees: []
disbursement_mode: string // enum
}
}
],
application_context?: {
brand_name
locale
landing_page
shipping_preference
user_action
payment_method: {
payer_selected,
payee_preferred: 'UNRESTRICTED' | 'IMMEDIATE_PAYMENT_REQUIRED'
}
return_url
cancel_url
}
payer?: {
name?: {
given_name: string
surname: string
},
email_address?
birth_date?
tax_info?: {
tax_id: string
tax_id_type: string // enum
}
address?: {
address_line_1
address_line_2
admin_area_2
admin_area_1
postal_code
country_code
}
}
}
const checkoutToPaypalOrderParams = (checkout: CheckoutInterface): PaypalOrderParams => {
return {
intent: 'CAPTURE',
purchase_units: [
{
reference_id: checkout.id,
amount: {
// Todo: upadate package when solved:
// https://github.com/Luehang/react-paypal-button-v2/issues/18
// used workaround: set currency: 'EUR' in PaypalButton
value: checkout.totalPrice.gross.amount.toString()
},
payee: {
email_address: YG_EMAIL_BASE,
// merchant_id: PAYPAL_CLIENT_ID
},
}
],
payer: {
// name: {
// given_name: string
// surname: string
// },
// email_address
// birth_date
// tax_info: {
// tax_id: string
// tax_id_type: string // enum
// }
address: {
address_line_1: checkout.billingAddress.streetAddress1,
address_line_2: checkout.billingAddress.streetAddress2,
admin_area_2: checkout.billingAddress.city,
admin_area_1: checkout.billingAddress.countryArea,
postal_code: checkout.billingAddress.postalCode,
country_code: checkout.billingAddress.country.code
}
}
}
}
const Paypal = ({
setPayment,
checkout,
// formRef,
// loading,
// paymentClientToken,
processPayment,
// setLoadingState,
}) => {
const gateway = checkout.availablePaymentGateways.find(pg => pg.name === PAYMENT_GATEWAYS.PAYPAL.name)
const clientId = gateway.config.find(item => item.field === 'client_id').value
// // Through the server
// const createOrder = () => {
// return fetch('/my-server/create-paypal-transaction', {
// method: 'post',
// headers: {
// 'content-type': 'application/json'
// }
// }).then((res) => {
// return res.json();
// }).then((data) => {
// return data.orderID; // Use the same key name for order ID on the client and server
// });
// }
// Todo: Call Paypal from the server?
// Note: For the basic integration, you'll do this step on the client. For advanced use cases,
// you can also call from your server to set up a transaction.
// https://developer.paypal.com/docs/checkout/integrate/#4-set-up-the-transaction
//
// Orders Create API reference: https://developer.paypal.com/docs/api/orders/v2/#orders_create
const createPaypalOrder = (data, actions) => {
const orderArgs: PaypalOrderParams = checkoutToPaypalOrderParams(checkout)
return actions.order.create(orderArgs)
// .then((orderID) => {
// console.log(`PAYPAL: createOrder.then => orderID: ${orderID}`)
// return orderID
// })
}
// Through the server: authorize
const onApprove = async (data) => {
const { orderID, payerID } = data
await setPayment({ gateway: gateway.id, data: { orderID, payerID } })
// processPayment calls the createPayment mutation
processPayment(orderID, gateway.id)
}
return (
<div style={{ backgroundColor: '#eee', padding: 16, borderRadius: 4 }}>
<Typography variant="body2" style={{ marginBottom: 16 }}><span style={{ fontWeight: 'bold', textDecoration: 'underline' }}>Importante!</span> Dopo avere dato l'autorizzazione al pagamento, <span style={{ fontWeight: 'bold' }}>verrai reindirizzato alla pagina di riepilogo dove dovrai concludere l'ordine</span>.</Typography>
<PayPalButton
// amount
// onSuccess
// catchError
// See options: https://github.com/Luehang/react-paypal-button-v2#small_blue_diamond-options-prop-fieldnames-or-parameters
options={{
clientId,
currency: 'EUR',
intent: 'capture',
disableFunding: ['card', 'sofort', 'mybank'],
}}
// onButtonReady
// onError
createOrder={createPaypalOrder}
onApprove={onApprove}
// onApprove={clientOnApprove}
// style
// onShippingChange
// onCancel
disableCard
/>
</div>
);
};
export default Paypal
@ChinnakornP
Copy link

Thank you. very helpful. can you guide how to add provider into checkout.availablePaymentGateways from saleor

@albertojacini
Copy link
Author

Hi, I'm sorry but I'm a bit rusty about this. I think you can paste it in your React client and adapt it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment