GithubHelp home page GithubHelp logo

luehang / react-paypal-button-v2 Goto Github PK

View Code? Open in Web Editor NEW
273.0 273.0 81.0 243 KB

An easy and simple to use React button component to implement PayPal Checkout with Smart Payment Buttons V2 (Version 2).

Home Page: https://luehangs.site/lue_hang/projects/react-paypal-button-v2

License: MIT License

TypeScript 64.63% HTML 2.76% CSS 0.11% JavaScript 32.50%

react-paypal-button-v2's Introduction

๐Ÿ”ท react-paypal-button-v2

An easy and simple to use React button component to implement PayPal's Checkout with Smart Payment Buttons V2 (Version 2).

Check out the docs for a complete documentation.

โ„น๏ธ This PayPal Checkout integration uses the PayPal JavaScript SDK. Starting at the beginning of February 2019, all new users must use PayPal's version 2 integration as version 1 is now depreciated.




LueHsoft LueH LABS Lue Hang luehang


Index

5. API

6. ๐Ÿ“š Props








๐Ÿ”ท Prerequisites

To use PayPal's Smart Payment Buttons in prodution, you must have a PayPal Business account set up and verified. After this is done, you'll have access to your API credentials to use with this button.

Once you have your account set up, you will have 2 different sets of credentials for sandbox mode and production mode. You will also be able to create sandbox business and customer accounts to be tested on.




LueHsoft LueH LABS Lue Hang luehang


๐Ÿ”ท Install

Type in the following to the command line to install the dependency.

$ npm install react-paypal-button-v2 --save

or

$ yarn add react-paypal-button-v2







๐Ÿ”ท Usage Example

Add an import to the top of the file. At minimal, declare the PayPalButton component in the render() method providing a string for the amount prop and a function to the onSuccess prop.

If you like react-paypal-button-v2, please be sure to give it a star at GitHub. Thanks.

import { PayPalButton } from "react-paypal-button-v2";

export default class Example Component {
  render() {
    return (
      <PayPalButton
        amount="0.01"
        // shippingPreference="NO_SHIPPING" // default is "GET_FROM_FILE"
        onSuccess={(details, data) => {
          alert("Transaction completed by " + details.payer.name.given_name);

          // OPTIONAL: Call your server to save the transaction
          return fetch("/paypal-transaction-complete", {
            method: "post",
            body: JSON.stringify({
              orderID: data.orderID
            })
          });
        }}
      />
    );
  }
}

For alternative usage, go to the Alternative Usage Example Section.

To create subscriptions, go to the Subscriptions Example Section.








๐Ÿ”ท Production Example

At minimal, declare the options prop and include your business production Client ID in the clientId fieldname value.

If you like react-paypal-button-v2, please be sure to give it a star at GitHub. Thanks.

import { PayPalButton } from "react-paypal-button-v2";

export default class Example Component {
  render() {
    return (
      <PayPalButton
        amount="0.01"
        // shippingPreference="NO_SHIPPING" // default is "GET_FROM_FILE"
        onSuccess={(details, data) => {
          alert("Transaction completed by " + details.payer.name.given_name);

          // OPTIONAL: Call your server to save the transaction
          return fetch("/paypal-transaction-complete", {
            method: "post",
            body: JSON.stringify({
              orderId: data.orderID
            })
          });
        }}
        options={{
          clientId: "PRODUCTION_CLIENT_ID"
        }}
      />
    );
  }
}

For alternative usage, go to the Alternative Production Example Section.

To create subscriptions, go to the Subscriptions Example Section.



LueHsoft LueH LABS Lue Hang luehang

๐Ÿ”ท API

<PayPalButton /> component accepts the following props...


๐Ÿ”ท Props

Props Description Type Default
amount The amount value of the transaction. string or number
currency The currency of the transaction. string "USD"
shippingPreference The shipping preference: Displays the shipping address to the customer. Enables the customer to choose an address on the PayPal site. Restricts the customer from changing the address during the payment-approval process. Options: NO_SHIPPING, GET_FROM_FILE, SET_PROVIDED_ADDRESS string "NO_SHIPPING"
onSuccess The successful completion of the transaction. (details: object, data: object) => void Function
catchError Transaction declined or errored. (err: object) => void Function
options You can customize the integration by passing different query parameters/fieldnames into the options prop object which will pass it to https://paypal.com/sdk/js. These parameters help PayPal decide the optimal funding sources and buttons to show to your buyers. Before configuring the options prop, make sure you haven't manually added the script tag for https://paypal.com/sdk/js. For a list of parameters/fieldnames, go to section options Prop Fieldnames/Parameters. object {clientId: "sb", currency: "USD"}
onButtonReady A function called when PayPal's API is loaded. () => void Function
onError If an error prevents buyer checkout. This error handler is a catch-all. Errors at this point are not expected to be handled beyond showing a generic error message or page. (err: object) => void Function
createOrder A function called when the buyer clicks the PayPal button. Calls PayPal using the actions.order.create() to set up the details of the transaction. (data: object, actions: object) => void Function
onApprove A function called when the buyer approves the transaction on paypal.com. Calls PayPal using the actions.order.capture() to capture the funds from the transaction. Optionally calls PayPal using actions.order.get() to get the transaction details. (data: object, actions: object) => void Function
createSubscription A function that calls the PayPal subscription using the actions.subscription.create() to set up the details of the transaction. Subscriptions Example Section. (data: object, actions: object) => void Function
createBillingAgreement A function that calls the PayPal billing agreement using the paypal.billingAgreement.create() to set up the details of the transaction. (data: object, actions: object) => void Function
style PayPal Checkout offers several style options that you can use to customize the look and feel of your Smart Payment Button. You can also display multiple funding sources to the buyer, when appropriate. See more on what to input in the style object at Customize the PayPal Buttons page. object {}
onShippingChange A function called when the buyer initially logs into their account, submits their billing/payment information, or makes a change to their shipping address on the review your payment page. (data: { paymentToken: string, shipping_address: object, selected_shipping_method: string }, actions: { resolve: Function, reject: Function, order: Function }) => Function Function
onClick A function called on PayPal button click. Can be used for validation. (data: object, actions: object) => void Function
onCancel Show a cancellation page or return to the shopping cart. (data: object) => void Function

โ„น๏ธ Learn more about the integration proccess along with more props and advance use cases starting at PayPal's docs.








๐Ÿ”น options Prop Fieldnames or Parameters

You can customize the integration by passing different query parameters/fieldnames into the options prop object which will pass it to https://paypal.com/sdk/js. These parameters help PayPal decide the optimal funding sources and buttons to show to your buyers. Before configuring the options prop, make sure you haven't manually added the script tag for https://paypal.com/sdk/js.

Option Description Type Default
clientId Your PayPal REST client ID. While you're testing in sandbox, you can use client-id=sb as a shortcut. string "sb"
currency The currency of the transaction. string "USD"
merchantId The merchant for who you are facilitating a transaction. string automatic
intent The intent of the payment. string "capture"
commit Set to true if the transaction is Pay Now, or false if the amount captured changes after the buyer returns to your site. boolean or string true
vault Set to true if the transaction sets up a billing agreement, or uses a vault. boolean or string false
components A comma-separated list of components to enable. Defaults to allow Smart Payment Buttons. Other components are optional. string buttons
disableFunding Funding sources to disallow from showing in the Smart Payment Buttons. string none
disableCard Cards to disable from showing in the Smart Payment Buttons. string none
integrationDate The date of integration. Used to ensure backwards compatibility. string automatic
locale The locale used to localize any components. PayPal recommends not setting this parameter, as the buyer's locale is automatically set by PayPal. string automatic
buyerCountry The buyer country. For testing purposes only. string automatic
debug Enable debug mode for ease of debugging. Do not enable for production traffic. boolean or string false

โ„น๏ธ To see a detail and complete list of available parameters and values, go to PayPal's Customization page.




LueHsoft LueH LABS Lue Hang luehang


๐Ÿ”ท Alternative Usage Example


Usage Example 1

import { PayPalButton } from "react-paypal-button-v2";

export default class Example Component {
  render() {
    return (
      <PayPalButton
        createOrder={(data, actions) => {
          return actions.order.create({
            purchase_units: [{
              amount: {
                currency_code: "USD",
                value: "0.01"
              }
            }],
            // application_context: {
            //   shipping_preference: "NO_SHIPPING" // default is "GET_FROM_FILE"
            // }
          });
        }}
        onApprove={(data, actions) => {
          // Capture the funds from the transaction
          return actions.order.capture().then(function(details) {
            // Show a success message to your buyer
            alert("Transaction completed by " + details.payer.name.given_name);

            // OPTIONAL: Call your server to save the transaction
            return fetch("/paypal-transaction-complete", {
              method: "post",
              body: JSON.stringify({
                orderID: data.orderID
              })
            });
          });
        }}
      />
    );
  }
}

Usage Example 2

Add the PayPal script to your web page, then add your sandbox or production client-id to the script tag. While you're testing in sandbox, you can use client-id=sb as a shortcut.

<script src="https://www.paypal.com/sdk/js?client-id=sb" />

Query Parameters

Option Description Type Default
client-id Your PayPal REST client ID. While you're testing in sandbox, you can use client-id=sb as a shortcut. string "sb"
currency The currency of the transaction. string "USD"

To see a detail and complete list of available parameters and values, go to PayPal's Customization page.


import { PayPalButton } from "react-paypal-button-v2";

export default class Example Component {
  render() {
    return (
      <PayPalButton
        amount="0.01"
        // shippingPreference="NO_SHIPPING" // default is "GET_FROM_FILE"
        onSuccess={(details, data) => {
          alert("Transaction completed by " + details.payer.name.given_name);

          // OPTIONAL: Call your server to save the transaction
          return fetch("/paypal-transaction-complete", {
            method: "post",
            body: JSON.stringify({
              orderID: data.orderID
            })
          });
        }}
      />
    );
  }
}

Subscription Example Usage

To create subscriptions you must first create a product and create a plan using the PayPal REST API.


import { PayPalButton } from "react-paypal-button-v2";

export default class Example Component {
  render() {
    return (
      <PayPalButton
        options={{vault: true}}
        createSubscription={(data, actions) => {
          return actions.subscription.create({
            plan_id: 'P-XXXXXXXXXXXXXXXXXXXXXXXX'
          });
        }}
        onApprove={(data, actions) => {
          // Capture the funds from the transaction
          return actions.subscription.get().then(function(details) {
            // Show a success message to your buyer
            alert("Subscription completed");

            // OPTIONAL: Call your server to save the subscription
            return fetch("/paypal-subscription-complete", {
              method: "post",
              body: JSON.stringify({
                orderID: data.orderID,
                subscriptionID: data.subscriptionID
              })
            });
          });
        }}
      />
    );
  }
}







๐Ÿ”ท Alternative Production Example

At minimal, add the PayPal script to your web page, then add your production client-id to the script tag.

<script src="https://www.paypal.com/sdk/js?client-id=PRODUCTION_CLIENT_ID" />

Query Parameters

Option Description Type Default
client-id Your PayPal REST client ID. string "sb"
currency The currency of the transaction. string "USD"

To see a detail and complete list of available parameters and values, go to PayPal's Customization page.


import { PayPalButton } from "react-paypal-button-v2";

export default class Example Component {
  render() {
    return (
      <PayPalButton
        amount="0.01"
        // shippingPreference="NO_SHIPPING" // default is "GET_FROM_FILE"
        onSuccess={(details, data) => {
          alert("Transaction completed by " + details.payer.name.given_name);

          // OPTIONAL: Call your server to save the transaction
          return fetch("/paypal-transaction-complete", {
            method: "post",
            body: JSON.stringify({
              orderID: data.orderID
            })
          });
        }}
      />
    );
  }
}



LueHsoft LueH LABS Lue Hang luehang


๐Ÿ”ท Example Project

Perform steps 1-2 to run locally:

  1. Clone the Repo
  2. Install and Run

๐Ÿ”น 1. Clone the Repo

Clone react-paypal-button-v2 locally. In a terminal, run:

$ git clone https://github.com/Luehang/react-paypal-button-v2.git react-paypal-button-v2

๐Ÿ”น 2. Install and Run

$ cd react-paypal-button-v2/
$ npm install
$ npm run start



LueHsoft LueH LABS Lue Hang luehang


๐Ÿ”ท Contribute

Pull requests are welcomed.


๐Ÿ”น Beginners

Not sure where to start, or a beginner? Take a look at the issues page.








๐Ÿ”ท License

Apache 2.0 ยฉ Lue Hang, as found in the LICENSE file.

react-paypal-button-v2's People

Contributors

cloudpower97 avatar farriere avatar holdmytea avatar jericopulvera avatar jonasfranz avatar luehang avatar santiher avatar tomtwo avatar v01d3tr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-paypal-button-v2's Issues

[BUG] Must pass vault=true to sdk to use createSubscription

To Do First

  • [x ] Did you try latest release?
  • [ x] Did you look for existing matching issues?

Software Package Version:
latest

Describe the bug
Must pass vault=true to sdk to use createSubscription

Just trying to set up a Paypal Smart button, but getting this error, even though i am passing vault=true in the options prop

<PayPalButton
        options={{
        	'client-id': '/*...*/',
        	vault: true
        }}
        createSubscription={(data, actions) => {
	        return actions.subscription.create({
	            plan_id: 'P-XXXXXXXXXXXXXXX'
	        });
        }}
        onApprove={(data, actions) => {
        	// Capture the funds from the transaction
        	return actions.subscription.get().then(function(details) {
        	      // Show a success message to your buyer
        	      alert("Subscription completed");
                });
        }}
/>

ReferenceError: window is not defined

Thank you very much for taking the time to write this package.

I am getting

ReferenceError: window is not defined

using this with SSR (Razzle)

Have you tested this with SSR? Please let me know if you want some more information on my setup.

[QUESTION]

Ask your Question
Hi there, I'm trying to implement the react-paypal-button-v2 for paypal sandbox subscription. I think I've done it correctly and I've read all the docs I could find, I don't understand why I'm getting POST https://www.sandbox.paypal.com/v1/billing/subscriptions 404 (Not Found) shortly after clicking any of the paypal buttons that are rendered.

I may be wrong on this, but that notice This PayPal Checkout integration uses the PayPal JavaScript SDK. Starting at the beginning of February 2019, all new users must use PayPal's version 2 integration as version 1 is now depreciated. PayPal Checkout would not also include Subscriptions would it?

Here is my button, I've only changed the options object and of course I added my sandbox plan id.

I must be missing something.

Thanks for taking a look at this.

<PayPalButton
  options={{ vault: true, clientId: "sb", currency: "USD" }}
  createSubscription={(data, actions) => {
    return actions.subscription.create({
      plan_id: 'blah blah blah'
    });
  }}
  onApprove={(data, actions) => {
    // Capture the funds from the transaction
    return actions.subscription.get().then(function (details) {
      // Show a success message to your buyer
      alert("Subscription completed");

      // OPTIONAL: Call your server to save the subscription
      return fetch("/paypal-subscription-complete", {
        method: "post",
        body: JSON.stringify({
          orderID: data.orderID,
          subscriptionID: data.subscriptionID
        })
      });
    });
  }}
/>

Tags
404
paypal smart button
sandbox api
subscriptions

[FEATURE REQUEST]Add a disableShipping prop

I think it would be easier to add a disableShipping prop than manually disable it as in #9

The proposed solution is to add

  application_context: {
    shipping_preference: 'NO_SHIPPING',
   }

manually when disableShipping prop is provided.

Let me know if you are okay with this, @Luehang , so I can open a P.R :)

Capturing incorrect clientId?

If I pass an incorrect clientId the PayPal button doesn't display, but can I capture this state and know the clientId is incorrect?

[QUESTION] How do I know if the payment is loading?

I am trying to use the paypal button for payments on my website, and I have two issued regarding loading.

  1. When the component is loading, the first button "pay with paypal" loads first, and the "pay with credit card" takes a while to fully display with text on it. If I click on "pay with credit card" before it is fully loaded, it opens the paypal page. I tried creating a "loading" state boolean, that I set to false when "onButtonReady" is called, but this does not work, as it seems to be considered "ready" once the paypal button is ready. Is there a way around this?

  2. Once the payment is done, we get a loading spinner on the paypal component, however, it then turns back to the black "payment by card" button for a few seconds before the "onSuccess" is called. This can be confusing for users as they will think it has finished loading, but it is in fact still loading (I do a redirect on Success and it isn't immediate because of this). How can I handle it in a user-friendly way?

Wrong button behavior

When you press on checkout button with chrome dev console opened button do not work or if onSuccess method was set proceed to execution of it.

Spotted on demo from repository
Chrome 73.0.3683.103

[BUG] Contingency: NEED_CREDIT_CARD

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
2.4.0

Describe the bug
Clicking on "Pay Now" on the pop-up redirects users to the login screen, and nothing happens after clicking "Log In to Paypal"

To Reproduce

  1. Click on PayPal checkout button
  2. Pop up shows the logged in user and credit card info properly
  3. Click "Pay Now" button on the popup
  4. Error occurs on dev console
  5. Popup is redirected to Paypal Login screen
  6. Type username and password and click "Log In to Paypal" button
  7. Nothing happens

Expected behavior
"Pay Now" shouldn't redirect users to the login page

Screenshots
image

Desktop (please complete the following information):

  • OS: Mac OSX 10.14.6
  • Browser: Chrome
  • React Version: 16.8.6

Additional context
Actually that error screenshot was captured on react-paypal-button-v2 2.3.2 version.
I updated the package to 2.4.0 and the behavior has changed after step 3 (Click "Pay Now" button on the popup). It's not openning the login popup anymore, but it throws an error saying
"Expected window to be same domain"

AbortController

To Do First

  • [X ] Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
2.6.1

Describe the bug
Love this package firstly... thank-you very much!!!

Using 2 React Components. One does a Paypal Subscription & the other does a Paypal standard payment. I find if I move between the 2 components quickly the Network call to paypal https://www.paypal.com/sdk/js?client-id=etc fails the complete. (eg: one network call started but then another starts and the first fails).

Its extremely minor isssue.

Could be fixed by added the AbortController() - https://developer.mozilla.org/en-US/docs/Web/API/AbortController - this could be used to cancel any existing network calls.

To Reproduce
Quickly load the component a second time before the first network call has completed.

Expected behavior
Preferred behavior is any existing network calls to 'www.paypal.com' be cancelled.

Desktop (please complete the following information):

  • OS: latest

Additional context
Its a very minor issue but I thought I would add it as it would make the software/npm a little more robust :)

[QUESTION]

To Do First

  • Take a look in the README
  • Take a look in the docs

Ask your Question

I'm getting a 404 error when calling my server to save the transaction onSuccess even using get requests. How to fix this issue?
Tags

[BUG] Country Dropdown Alignment

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
v2.6.0

Describe the bug
Choosing the Debit or Credit Card item reveals an improperly-styled country-select dropdown. The caret overlays the flag icon.

To Reproduce

  1. Click on Debit or Credit Card

Screenshots
Bildschirmfoto 2019-11-25 um 11 51 13 AM

Desktop (please complete the following information):

  • OS: macOS 10.15, Windows 10
  • Browser: macOS Chrome v78.0.3904.97, Windows Chrome v77.0.3865.120
  • React Version: v16.8.5

[FEATURE REQUEST] CreateOrder to return the orderID

Is your feature request related to a problem? Please describe.
Yes. OnCancel returns a orderID, but there is no means to check this orderID as the library does not return orderID when createOrder is called.

Describe the solution you'd like

I hope createOrder will return the orderId as PayPal provides this.

Describe alternatives you've considered

No alternative. Worse Case i have to develop another library to call Paypal directly to get Order details.

Additional context

[BUG] Missing default props on sdk request, when option prop

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
2.6.1

Describe the bug
Missing default props on sdk request, when option prop specified

To Reproduce

  1. Pass option prop to component without default option props clientId or currency
  2. Try to run component

Expected behavior
Correct component run: button is shown && clickable

Actual behavior
Component can't get Paypal SDK

Desktop (please complete the following information):

  • OS: Ubuntu, LinuxMint 19.2 (64-bit)
  • Browser: Chrominum Version 77.0.3865.90 (Official Build)
  • React Version: 16 latest

[BUG]

To Do First

  • [ yes] Did you try latest release?
  • [yes ] Did you look for existing matching issues?

Software Package Version:

Describe the bug

To Reproduce

Expected behavior

Screenshots

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser: [e.g. chrome, safari]
  • React Version: [e.g. 22]

Additional context

Unable to import this dependency in windows environment

Hello,

thank you to provide this dependency, for now i've meet sth unexpected when i try to import your project into my local dependencies.

`npm WARN deprecated @babel/[email protected]: ๐Ÿšจ As of Babel 7.4.0, this
npm WARN deprecated package has been deprecated in favor of directly
npm WARN deprecated including core-js/stable (to polyfill ECMAScript
npm WARN deprecated features) and regenerator-runtime/runtime
npm WARN deprecated (needed to use transpiled generator functions):
npm WARN deprecated
npm WARN deprecated > import "core-js/stable";
npm WARN deprecated > import "regenerator-runtime/runtime";

[email protected] preinstall C:\Users\xiaolinma\Desktop\findmycook-frontend\Frontend\node_modules\react-paypal-button-v2
rm -rf dist`

and this "rm -rf dist " could not be accepted by windows commandline, thus my install failed

[BUG] 'rm' is not recognized as an internal or external command on Windows 10

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
Latest Release

Describe the bug
When installing the npm package on a windows machine there is the following error:

> rm -rf dist

'rm' is not recognized as an internal or external command,
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] preinstall: `rm -rf dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] preinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\patrick\AppData\Roaming\npm-cache\_logs\2019-08-06T11_38_56_956Z-debug.log

To Reproduce

  1. Go to project on a windows machine
  2. Run the following command:
    npm install npm install react-paypal-button-v2

Expected behavior
Expected the npm module to install without breaking or needing os specific commands...

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: NA
  • React Version: NA

Additional context
Thanks for looking at this bug. Have a good day.

[BUG] Set platform_fees returned status: 422

createOrder={(data, actions) => {
	return actions.order.create({
		purchase_units: [{
			description: 'Payment for ' + name + '.',
			payee: {
				email_address: '[email protected]',
			},
			amount: {
				currency_code: 'EUR,
				value: (amount * 0.9).toFixed(2),
			},
			payment_instruction : {
				disbursement_mode: 'INSTANT',
				platform_fees: [
					{
						amount: {
							currency_code: currency,
							value: (amount * 0.1).toFixed(2),
						},
					}
				],
			},
		}],
	});
}}

[FEATURE REQUEST] createOrder should check return value

Is your feature request related to a problem? Please describe.
Currently we would like to make a last-minute validation before clicking the PayPal button, and in case a problem arises stop the process and show a message showing for instance "Please fill all fields before proceeding".

Describe the solution you'd like
I don't know if it will work as expected, but it would be nice for createOrder at index.tsx:184 to check the return of the createOrder prop function, and in case it's empty stop the process.

Describe alternatives you've considered

  1. I Tried onClick={(e) => {e.preventDefault(); window.alert('Clicked button'); return false;}}. Function is indeed called and alert box is shown, but an error appears Uncaught TypeError: e.preventDefault is not a function and PayPal popup still appears.
  2. What we have done is do our validation checks within createOrder, and return null if it doesn't validate. This shows the PayPal popup briefly and closes immediatelly. It's far from ideal but it does the trick for the time being.
  /*
   * Handles the front-end behavior after paypal returns error
   */
  onError = (error) => {
    // TODO: We need to test this. Haven't found a way in sandbox
    // https://developer.paypal.com/docs/checkout/integration-features/handle-errors/
    if (error.message.indexOf('Expected an order id to be passed') >= 0)
      return;

    return this.handleError(error.message, error);
  };

  /*
   * Main render function
   */
  render() {
    return (
          <PayPalButton
            createOrder={(data, actions) => {
              // This will produce a Console error, unfortunately
              if (!this.props.prePayCheck())
                return;

              this.setState({ in_progress: true });

              return actions.order.create(PaypalOrder);
            }}
            onApprove={this.onApprove}
            onCancel={this.onCancel}
            onError={this.onError}
            options={....}
          />
    );
  }
}

Disable shipping

I can't seem to be able to disable shipping for the order when checking out with a credit card. The items I'm selling are not going to be shipped and the field confuses the users. I've been looking into the documentation and tried to add the NOSHIPPING option and it still shows up.

Any ideas?

Screen Shot 2019-05-09 at 11 21 56 AM

[BUG]

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
2.6.2

Describe the bug
I use the component as said in the documentation, with minimum configuration:

import React from 'react';
import { PayPalButton } from "react-paypal-button-v2";

const PayPalBtn = (props) => (
  <PayPalButton
    amount="1.00"
    shippingPreference="NO_SHIPPING"
    onSuccess={(details, data) => {
      alert("Transaction completed by " + details.payer.name.given_name);
      return fetch("/paypal-transaction-complete", {
        method: "post",
        body: JSON.stringify({
          orderID: data.orderID
        })
      });
    }}
  />     
);

export default PayPalBtn;

It is working. However, I get this error in the browser's console:

index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of a which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://fb.me/react-strict-mode-find-node in div (created by a) in a (created by PayPalButton) in PayPalButton (at PayPalBtn.js:5)

Expected behavior
I expect not to see that error! :)

Desktop (please complete the following information):

  • OS: macOS
  • Browser: Chrome Version 81.0.4044.122 (Official Build) (64-bit)
  • React Version: v16.13.1

[BUG] the 'currency' prop is only working for USD

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:

Describe the bug
the prop 'currency' does not work if we use a value like "EUR". Paypal now requires that we indicate the currency when getting the Paypal script.

To Reproduce
use template code in the documentation and try to set EUR for the prop "currency"

Expected behavior
If a 'currency' property exists, people will set the 'currency' with this property.
The other solution is to remove the 'currency' prop, and let people set the currency in the options prop, which is working just fine at the moment.
You would need to update the documentation and the templates provided in the package description.

Current working workaround / other way to set currency
At the moment, we can only set the currency in the options prop. Which is fine.

options={{
            clientId: "############"
            ,currency:"EUR"
          }}

[BUG]

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
2.6.1

Describe the bug
When add options props
Error: Paypal SDK could not be loaded.

To Reproduce
<PayPalButton
...
options={{ vault: true }}
...
/>
Desktop (please complete the following information):

  • OS: Ubuntu 18.04
  • Browser: Chrome
  • React Version: v16.8.5

Does not support OnCancel

Hi,

Can you consider adding the OnCancel event handler?
Currently when I close the PayPal popup I do not get an event that the PayPal window closed.

sam

[FEATURE REQUEST] Exchange Rate on Callback?

Great library!

I'm wondering if there's a solution to the following issue I'm having (which I'm sure others will encounter).

My PayPal is in GBP, but my app accepts international payments using their local currency. PayPal automatically converts incoming payments using an exchange rate, which is amazing.

However I want to process the exchanged value in the callback from paypal, but it only offers me the amount that was entered in the original currency.

I've seen somewhere there may be an option to get the exchange rate used in the callback, but I find PayPals documentation a little hard to follow, and someone here may have a better idea.

Willing to help with the work and pull request in if guided in the right direction!

remove the Polyfill

Thank you for the component, the code looks very clean ๐Ÿ‘

I was surprised to see that you import babel polyfill in the component. The polyfills are generally added in the beginning of an app, it is not included in the components.

Usually if a library needs a polyfill, it will be mentioned in the Readme/documentation. A good example of this is React:
https://reactjs.org/docs/javascript-environment-requirements.html

What do you think ?

passing custom parameters

Is it possible to pass custom parameter such as product-id to paypal while calling CreateOrder and receive it back when approved or error encountered?

[FEATURE REQUEST] PayPal button was unable to be loaded

Is your feature request related to a problem? Please describe.
It is something between a bug and a feature request. We want the handle the case "PayPal button was unable to be loaded". Currently it throws console error "Paypal SDK could not be loaded." (index.tsx:221).

Describe the solution you'd like
Do not throw a Javascript error. Use the already provided prop onError or catchError (which I don't know exactly their difference)

Describe alternatives you've considered
I believe the proposed solution is good enough.

[FEATURE REQUEST] Support createSubscription Function

Is your feature request related to a problem? Please describe.
PayPal's checkout buttons support a createSubscription function for recurring payments. Currently, the PayPalButton component in this repo does not support the createSubscription function. It only supports createOrder, for one-time payments.

Describe the solution you'd like
Allow the PayPalButton component to take in a createSubscription prop that then gets passed into PayPal's button component. The user should be able to pass in createSubscription or createOrder as a prop to the button component, but not both.

Describe alternatives you've considered

  1. I tried passing in createSubscription (instead of createOrder) as a prop to this repo's PayPalButton component. This didn't work, because the PayPalButton component does not accept createSubscription as a prop.
  2. I tried using the regular createOrder function, but calling actions.subscription.create() instead of actions.order.create(). This didn't work, because the action object that gets passed into createOrder does not support the actions.subscription.create() function.

Additional context
See more information about the createSubscription function here: https://developer.paypal.com/docs/subscriptions/integrate/#4-create-a-subscription.

You should be able to pass in createSubscription like so:

  createSubscription: function(data, actions) {
    return actions.subscription.create({
      'plan_id': 'P-2UF78835G6983425GLSM44MA'
    });
  },

  onApprove: function(data, actions) {
    alert('You have successfully created subscription ' + data.subscriptionID);
  }

How to use onShippingChange to update shipping in order based on customer country code

I am trying to update the shipping after the customer has logged in to Paypal and I know their country code, but I can't fathom the data format that Paypal wants. I can see that there is a patch function returned, which is what I'm using.

Can I have an example please? This is my code so far:

onShippingChange={
    (data, actions) => {
        const { shipping_address: { country_code } } = data;
        if (Config.zeroShippingCountries.includes(country_code)) {
            console.log(`${ country_code } is eligible for free shipping`);
            actions.order.patch({
                purchase_units: [{
                    amount: {
                        breakdown: {
                            item_total: {
                                currency_code: Config.currency,
                                value: total
                            },
                            shipping: {
                                currency_code: Config.currency,
                                value: 0
                            },
                            tax_total: {
                                currency_code: Config.currency,
                                value: 0
                            },
                            discount: {
                                currency_code: Config.currency,
                                value: 0
                            }
                        },
                        currency_code: Config.currency,
                        value: (+total).toFixed(2)
                    }
                }];
            }
        }
    }

[BUG] Rimraf Dependency Breaks Some Machines

Ran into using CodeBuild's NodeJS 10.x Images. May PR a fix tonight if I have time.

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version: 2.4.1

Describe the bug
Use of "rimraf" in 2.4.1 accidently creates global dependency for "rimraf".

If "rimraf" is not installed on machine, npm install/rebuild commands will fail with message like:

> [email protected] preinstall /home/jon/src/rsm/robinsnestdesigns.com/node_modules/react-paypal-button-v2
> rimraf dist

sh: rimraf: command not found

To Reproduce

  1. sudo npm uninstall -g rimraf
  2. cd <project which has dep of [email protected]>
  3. rm -rf node_modules/ && rm -f package-lock.json
  4. npm install
  5. Install fails
  6. sudo npm install -g rimraf
  7. npm install
  8. Install succeeds

Expected behavior
rimraf calls should use node node_modules/rimraf/bin.js to ensure package is using proper rimraf package and not global installed version

Desktop (please complete the following information):

  • OS: Fedora 29
  • Browser: N/A
  • React Version: N/A

paypal-button-v2 keeps on redirecting to sandbox

Hello, i implemented the paypal-button-v2 on my app and included the clientId in the options prop as shown below. The clientId is set to live in paypal developer dashboard, however, the app still always redirects to sandbox for payment.

see below:
`return (
<PayPalButton
amount="11.00"
onSuccess={(details, data) => {

      //Send transaction details to backend api
      // let tempPayRecords = {};
      // tempPayRecords.payer_email = details.payer.email_address;
      // tempPayRecords.payer_name = details.payer.name;
      // tempPayRecords.payer_phone = details.payer.phone;
      // tempPayRecords.payer_address = details.payer.address;
      // tempPayRecords.status = details.status;
      // tempPayRecords.user_email = this.state.paymentRecords.email;
      // tempPayRecords.user_firstname = this.state.paymentRecords.fname;
      // tempPayRecords.user_lastname = this.state.paymentRecords.lname;
      // tempPayRecords.user_phone = this.state.paymentRecords.phone;
      // tempPayRecords.payment_ref = data.orderID;
      // tempPayRecords.amount_paid = this.state.paymentRecords.amount;

     
      return this.completePurchase(tempPayRecords);

    }}
    options={{
      clientId:
        "AdZE9s3sEAYws0EqSJp9lSqe6umA67yuaMq0KbU_RTEpvj61a8Sf5nDs4a32Llnc3VtBKVieoFRkZkGL"
    }}
  />
);`

[BUG] not exported types

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version: 2.4.1

Excuse me, for removing the issue schema, but I noticed that even tough you do use typescript, the types aren't properly builded/exported into npm.

Can you fix it?

[QUESTION] Receiving error: "onApprove is not a function."

To Do First

  • Take a look in the README
  • Take a look in the docs

Ask your Question
Hey there, I'm trying to implement a Paypal button on my react site. It's going well right through until the user confirms the payment (On the new window that the Paypal API brings up). They log in, select their payment method and then click Doorgaan which is Dutch for continue. I'm getting the error:

Uncaught TypeError: onApprove is not a function at Object._react.default.createElement._extends.onApprove (http://localhost:3000/static/js/0.chunk.js:83915:18) at https://www.paypal.com/sdk/js?client-id=Aa7sc9WnfeRzS-HtZHcWKC-KenotGUIR9QgvjqPYfHdI1bfu7XqVRJ2GmqFWL40iCBtBdubpl_coFqCN&currency=GBP&commit=true&intent=capture:1:54538...
It then proceeds to say basically the same thing over and over again. Not in a loop, just a really long error.

Am I right in saying that I don't even need the onApprove function? When the user clicks this button, I want it to skip right to my onSuccess function. As you can see I have tried to bypass this by adding:
options={{ ... commit: true, intent: 'capture' }}
to my button component, but I am still getting the same error.

I'm a little out of my depth with this issue! I hope somebody can help me.
I should point out that I'm still in sandbox mode of the PayPal API.
Please and thank you in advance! ;)

Tags

onApprove error intermediate wtf

PaymentButton in Dialog

Hello.
I have been rendering PaymentButton in modal dialog.
When close modal dialog it crashed even though never clicking PayPal button.
image
image
Please let me know how can I fix this crash.
Thank you.

[QUESTION]

I click on the cutton, and pay from Sand-Box buyer account.
The paypal accepts the payment, and deduct it from the buyer account.
But

  1. It doesn't add it to the seller account.
  2. it does not get back to the component (onResult or onError), so I assume it crashed somewhere.
    But when it closes PayPal window, it does remove the "opaque" efect from my client.

class MyPayPal extends React.Component { render() { return ( <PayPalButton options={{ clientId:"XXX", currency:"ILS" }} loacle= "he_IL" amount="10.0" shippingPreference="NO_SHIPPING" // default is "GET_FROM_FILE" onSuccess={(details, data) => { log('onSuccess: details=',details); log('onSuccess: data=',data); }} onError={(details, data) => { log('onError: details=',details); log('onError: data=',data); }} onApprove={(details, data) => { log('onApprove: details=',details); log('onApprove: data=',data); }} onCancel={(details, data) => { log('onApprove: details=',details); log('onApprove: data=',data); }} /> ); } }

'rm' is not recognized as an internal or external command,

image

'rm' is not recognized as an internal or external command,

[4/4] Building fresh packages...
[1/3] โ ‚ node-sass
[2/3] โ ‚ styled-components
error e:\projects\GVS%20System%20Rebuild\src\GVS.VoucherSales\UI\gvs-vouchersales-public-app\node_modules\react-paypal-button-v2: Command failed.
Exit code: 1
Command: rm -rf dist
Arguments:
Directory: e:\projects\GVS%20System%20Rebuild\src\GVS.VoucherSales\UI\gvs-vouchersales-public-app\node_modules\react-paypal-button-v2
Output:
'rm' is not recognized as an internal or external command,

Error: Unexpected currency: JPY passed to order.create. Please ensure you are passing /sdk/js?currency=JPY in the paypal script tag.

Hi, Good day. I've followed your examples, but i seem to stumble across an error whenever i try to change the currency. We're using React 15.6.2 with Redux 4.4.9.

Error: Unexpected currency: JPY passed to order.create. Please ensure you are passing /sdk/js?currency=JPY in the paypal script tag.

Here's my code for our page.

import { PayPalButton } from "react-paypal-button-v2";

import { toast } from 'react-toastify'

class PaymentTest extends Component {
  constructor (props) {
    super(props)

    this.state = {
      
    }
  }

  componentDidMount () {

  }

  componentWillReceiveProps (nextProps) {
    let { } = nextProps
  }

  render() {
    
    return (
      <PayPalButton
      amount="0.01"
      options={{currency:'JPY'}}
      
      onSuccess={(details, data) => {
        alert("Transaction completed by " + details.payer.name.given_name);

        // OPTIONAL: Call your server to save the transaction
        return fetch("/paypal-transaction-complete", {
          method: "post",
          body: JSON.stringify({
            orderID: data.orderID
          })
        });
      }}
    />
    );
  }
}

PaymentTest.propTypes = {

}

export default PaymentTest

Even then if i try to place it inside the <PayPalButton>, it returns with the same error.

<PayPalButton
      amount="0.01"
      currency='PHP'
      onSuccess={(details, data) => {
        alert("Transaction completed by " + details.payer.name.given_name);
        // OPTIONAL: Call your server to save the transaction
        return fetch("/paypal-transaction-complete", {
          method: "post",
          body: JSON.stringify({
            orderID: data.orderID
          })
        });
      }}
    /> 

[BUG] 'p24' value for disableFunding option produces a 400 response

To Do First

  • Did you try latest release?
  • Did you look for existing matching issues?

Software Package Version:
react-paypal-button-v2: 2.4.1
Describe the bug

I am trying to disable the Przelewy24 funding source which can be disabled by giving the value p24 in disableFunding option. This value is obtained by the official documentation. When I try to load the buttons using this value, unfortunately the PayPalButton component doesn't load at all producing a 400 error on the request. I am attaching a snapshot below.

Note 1.

Other options are working as expected. For example if I use card value as an option the paypal default button is rendered and the cards are not rendered.

Note 2.

I am basically trying to disable all funding sources as I only want to show the default paypal button for now. If there is an option to disable all funding sources it would work for me.
To Reproduce
Steps to reproduce the behavior:

  1. Try to load PayPalButton with the options prop seen bellow
options={{clientId: configLocal.PAYPAL_SANDBOX_CLIENT_ID,
              buyerCountry: 'PL',
              disableFunding: 'p24'}}

I am using buyerCountry: 'PL' as Poland is the country where Przelewy24 funding source is shown.

Expected behavior
Loading PayPal default button

Screenshots
p24-error

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chrome
  • React Version: 16.9.0

Description option don't work

I want to show description in payment completed email.

return actions.order.create({
              purchase_units: [{
                description: "some description about payment",
                amount: {
                  currency_code: "USD",
                  value: `${rate}`
                }
              }]
            });

So I have set description for purchase_units, but it doesn't show in email content.

Screen Shot 2019-07-15 at 10 20 21 PM

purchase_units description option don't work

I want to show description in payment completed email.

return actions.order.create({
              purchase_units: [{
                description: "some description about payment",
                amount: {
                  currency_code: "USD",
                  value: `${rate}`
                }
              }]
            });

So I have set description for purchase_units, but it doesn't show in email content.
Screen Shot 2019-07-15 at 10 20 21 PM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.