Giter Site home page Giter Site logo

react-coinbase-commerce's Introduction

CircleCI npm version

Coinbase Commerce React Button

Note: This repository is not actively maintained.

A button to embed a Coinbase Commerce checkout or charge directly into your React application.

npm i -S react-coinbase-commerce 

Features

  • Connect your Coinbase Commerce account to easily accept cryptocurrencies from within your application.
  • Support for embedding individual charges or entire checkouts
  • Callback APIs for successful and failed payments.
  • No API key required

Table of Contents

Usage

import CoinbaseCommerceButton from 'react-coinbase-commerce';
import 'react-coinbase-commerce/dist/coinbase-commerce-button.css';

const App = () => {
  return (
    <CoinbaseCommerceButton checkoutId={'My checkout ID'}/>
  )
};

Getting Started

  1. To start accepting digital currency payments, first register for a Coinbase Commerce account here.
  2. Whitelist your domain in Settings.
  3. Follow the API Documentation here to create a charge or checkout.
    • Alternatively, create a checkout from the merchant dashboard and copy the ID found in the checkout's details.
  4. Pass the ID of the charge or checkout you create to the CoinbaseCommerceButton component
  5. That's it! You're ready to start accepting digital currency payments with Coinbase Commerce

Docs

Props

In addition to the regular button props, this component accepts some custom props:

Prop Name default required type
styled false no boolean
checkoutId nil If no chargeId, yes string
chargeId nil If no checkoutId, yes string
onLoad nil no ()=>void
onChargeSuccess nil no (MessageData)=>void
onChargeFailure nil no (MessageData)=>void
onPaymentDetected nil no (MessageData)=>void
onModalClosed nil no ()=>void
disableCaching false no boolean
customMetadata nil no string

Warning: If disableCaching is set to true, users that accidentally close their payment windows will be unable to see their transaction's status upon reopening.

Data Types

type MessageData = {
  event: 'charge_confirmed' | 'charge_failed' 'payment_detected',
  code: <CHARGE_CODE>
}

react-coinbase-commerce's People

Contributors

aarti avatar abohannon avatar allenan avatar dependabot[bot] avatar georgii-nansen avatar guacamoli avatar jakeleboeuf avatar jguyton avatar jorgenvatle avatar krobertson avatar ksmithbaylor avatar morleytatro avatar oa-coinbase avatar sahil-cb avatar samiragadri-34 avatar sds avatar tbtstl 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

Watchers

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

react-coinbase-commerce's Issues

iframe uncentered

A few days ago we started noticing the coinbase iframe is no longer centered. I'm not sure if this is intended behavior or not, but it looks a bit strange. Here is a sample:

Screen Shot 2021-10-20 at 7 14 12 PM

Make Button component overridable with a component from a prop

Introduce a "Button" prop on the CoinbaseCommerceButton which will allow us to replace the <button> which is rendered with our own. I use ChakraUI and EmotionCSS, and I just want to render my button easily instead of the current one. I can add it as a child and with some css override it will work, but I will have nested button tags then.

onChargeSuccess and onPaymentDetected not being called

I've created this React component with a customized button:

const CryptoButton: React.FC = () => {
  const { setRootLoading, setErrors, paymentClientData } = useContext(OrderContext);

  useEffect(() => {
    const button = document.querySelector(
      "button.coinbase-commerce-button"
    ) as HTMLElement;

    if (button) {
      button.classList.add("ui", "black", "button", "big");
      button.innerHTML = `<i class="bitcoin icon"></i> Pay With Cryptocurrency`;
      button.style.display = "inherit";
    }
  }, []);

  useEffect(() => {
    setRootLoading(!paymentClientData?.code);
  }, [paymentClientData]);

  const onLoad = async () => {
    setRootLoading(true);
  };

  const onChargeSuccess = async (data: any) => {
    console.log("onChargeSuccess");
  };

  const onChargeFailure = () => {
    console.log("onChargeFailure");
    setErrors(["An error has occurred."]);
  };

  const onModalClosed = () => {
    console.log("onModalClosed");
    setRootLoading(false);
  };

  const onPaymentDetected = async (data: any) => {
    console.log("onPaymentDetected", data);
  };

  return (
    <>
      <style jsx global>{`
        button.coinbase-commerce-button {
          display: none;
        }

        div.commerce-loading-spinner {
          position: absolute;
          top: 50%;
          left: 50%;
          margin-top: -20px;
          margin-left: -20px;
          width: 40px;
          height: 40px;
          border: 3px solid rgba(6, 103, 208, 0.05);
          border-radius: 100%;
          border-top-color: white;
          animation: spin 1s infinite linear;
        }

        @keyframes spin {
          33% {
            transform: rotate(90deg);
          }
          66% {
            transform: rotate(270deg);
          }
          100% {
            transform: rotate(360deg);
          }
        }

        div.coinbase-commerce-iframe-container {
          left: 0;
          right: 0;
          top: 0;
          bottom: 0;
          width: 100%;
          height: 100%;
          position: fixed;
          z-index: 99998;

          background-color: rgba(0, 0, 0, 0.5);
        }

        iframe.coinbase-commerce-iframe {
          position: fixed;
          left: 0;
          right: 0;
          top: 0;
          bottom: 0;
          z-index: 99999;
          height: 100%;
          width: 100%;
          border: none;
        }
      `}</style>
      <CoinbaseCommerceButton
        styled
        chargeId={paymentClientData?.code}
        onLoad={onLoad}
        onChargeSuccess={onChargeSuccess}
        onChargeFailure={onChargeFailure}
        onModalClosed={onModalClosed}
        onPaymentDetected={onPaymentDetected}
      />
    </>
  );
};

The props don't seem to work at first. The callbacks are being called but only when I close the modal and reopen it again.

`onModalClosed` doesn't work

Hello.

When the <CoinbaseCommerceButton> component is instantiated (and the modal opens up), the component fails to render if the onModalClosed property is set.

According to the documentation here, onModalClosed is a valid property, however, the component doesn't look like it has the code in place to recognize it.

Here's what my code looks like:

      <CoinbaseCommerceButton
        className={styles.coinbaseBuyNow}
        onPaymentDetected={processCoinbaseEvent}
        onChargeFailure={processCoinbaseEvent}
        onChargeSuccess={processCoinbaseEvent}
        onModalClose={processModalClose} // this fails
        chargeId={coinbaseChargeId}>
        Buy Now
      </CoinbaseCommerceButton>

I tried both onModalClosed and onModalClose and I got the same error:

Screen Shot 2021-09-09 at 11 22 00 AM

"Element type is invalid" error when rendering button

Somewhere in the upgrade from version 1.4.4 to version 1.5.0, an error got introduced that causes the button to throw an error when rendering.

The error is: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object..

Very simple CodeSandbox. If you switch the react-coinbase-commerce version to 1.4.4 in the package.json file, you'll see the button start to work again.

My project uses latest version of react.

My project uses latest version of react. However; when installing the plugin it wants a lower version. Why is it not compatible with latest version of react ?

Found: [email protected]
#9 38.15 npm ERR! node_modules/react
#9 38.15 npm ERR! react@"^17.0.1" from the root project
#9 38.15 npm ERR!
#9 38.15 npm ERR! Could not resolve dependency:
#9 38.15 npm ERR! peer react@"^15.6.0 || ^16.0.0" from [email protected]
#9 38.15 npm ERR! node_modules/react-coinbase-commerce
#9 38.15 npm ERR! react-coinbase-commerce@"^1.6.0" from the root project
#9 38.15 npm ERR!
#9 38.15 npm ERR! Fix the upstream dependency conflict, or retry
#9 38.15 npm ERR! this command with --force, or --legacy-peer-deps
#9 38.15 npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

New payment cannot be made until last payment is successful

Problem:
I'm not able to make a new payment until the current payment being processed is successful.

Situation:
I'm building a web app where users will click the React-Coinbase-Commerce button and pay. After the payment has been received the modal will be closed and they'll be able to continue on shopping. If the user finds another item they'd like to buy they can click the React-Coinbase-Commerce button again and a new charge should be created so they can buy this item as well. Instead when they click the button again the second time it just shows the payment verification process.

Steps to Recreate

  1. Setup coinbase-commerce button
  2. Send an arbitrary payment to a checkout
  3. close the modal when the payment is detected
  4. try to re-open to modal by clicking the coinbase-commerce button again
  5. instead of being shown a new charge, you'll be shown the verification process (or completion page) of the old transaction

Coinbase login doesn't work in Safari or on iOS

Logging in via Coinbase doesn't seem to work in Safari on OSX nor Chrome or Safari on iOS. Choosing Coinbase as the payment method opens the Login popup, but even after logging in and authorizing Coinbase Commerce, the modal never picks up the authorization event and remains stuck on the "Just a moment, redirecting you to Coinbase..." screen.

Tested and the flow is working on Chrome on OSX and Android.

(53s) loom video of issue

Sorting by market cap does not work - CTC below SUN

Location: https://www.coinbase.com/price?page=7
Time: 17 April 2021, 3.14pm UTC+01:00

Scenario: Sort by market cap.

Expected: all results should be descending

Actual: results are descending only till SUN (SUN), then Creditcoin (CTC) has higher market cap but is below SUN in the sorted list. Sorting is wrong.
image

Disclaimer: not sure if this is the right repo for this issue, but it is an issue.

Changelog?

Hey, dependabot filed a PR to bump the version of react-coinbase-commerce to 1.5.1 however both the releases page and the Changelog point to 1.4.x. Was the package bump update not pushed?

Screen Shot 2021-02-17 at 2 39 44 PM

Support for SSR

Hello Coinbase team! First of all, we at nobscrypto.com are loving Coinbase Commerce!

Background

We use GatsbyJS (a static site generator built on React) which of course uses SSR to generate the static html.

Issue

This project depends on window being defined. Of course, window only exists in the browser, so while building our production deployment using SSR, we are getting window not defined from this library.

Solution

I believe the solution would be something as simple as a Polyfill. In fact, this issue went undetected for us because we were using a separate third-party library that brought in this type of polyfill already. It wasn't until we removed the other library that we ran into the issue with this library. You can see the polyfill used by this other library here:

https://github.com/aws-amplify/amplify-js/blob/66fa18db5e2d9450d467f3ed3d27994ed8aa0149/packages/core/src/Polyfills/Polyfills.ts

Not actively maintained?

According to the README this repo is not actively maintained. Does this mean the component should no longer be used in production? This component is referenced by live production CoinBase Commerce documentation. That should be updated if we're not supposed to be using this.

`onChargeSuccess` not firing callback

After a crypto payment is successful and the Continue button is pressed, the callback function is not firing. We just started noticing this issue a few days ago.

                <CoinbaseCommerceButton
                  chargeId={coinbaseChargeId}
                  styled={true}
                  onChargeSuccess={onChargeSuccess}
                  onChargeFailure={onChargeFailure}
                />
  const onChargeSuccess = () => {
    // not firing
    console.log('on success')
    history.push(`/wallet?deposit_success=true`)
  }

No payment method available for recurring transactions

Hi, Team.
please relocate the issue if wrongly placed

Unfortunately when I try to create a recurring transaction on the web interface .
Message is displayed: "link and verify a payment method"even thou I have already 3 payment methods defined and verified.

can this be fixed ?

Unknown DOM property allowtransparency

When I click the CoinbaseCommerceButton for the first time, console prints the following warning.
image

Click for the second time, there is no warning.

Could you take a look at it?

not working with React v15.6?

vendor.bundle.js:20637 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `t`.

Clicking the "Close" button in the Coinbase Commerce modal navigates the page back

I'd expect the Close button to behave like clicking the "X" in the top-right corner and just close the modal and call my onModalClosed callback, but instead it logs an error and navigates the whole page back.

The error logged is "no product state to return to", which appears in the Coinbase Commerce checkout js loaded by the modal, and which is followed by a call to goBack(). Go to https://commerce.coinbase.com/static/js/checkout.04d9aced.js and search for "no product state to return to".

I'd hazard a guess that this is actually an issue with the non-public Commerce Checkout code instead of this repo, but since I don't have access to that repo, I'm posting the issue here!

Screen Shot 2021-02-09 at 4 25 09 PM

Add support for React ^17.x

In dependencies list there are ^15.x and ^16.x of React are mentioned but as React 17 has no breaking changes from 16, I believe it should be added into the list of allowed deps as well.

Custom metadata not working for Payment Button

Hey everyone!
Let me start saying that I know this issue does not belong to react-coinbase-commerce integration, but I couldn't find any other place to ask my questions or contact support, so I was hoping if you guys can somehow answer my question or at least point me in the right direction.

Thank you!

The issue

We are adding a Payment Commerce Button in our website following this guide: https://docs.cloud.coinbase.com/commerce/docs/add-payment-button
We embedded the html <a> and <script> and everything works just fine.

The issue comes when we want to send some custom metadata (a user id) so when get a callback call in our backend, we can identify what user was doing the transaction.

According to the guide, we can add a data-custom attribute to the <a>, but when we get our backend call, metadata is always empty.

We tried 2 approaches, sending data-custom as an attribute (the site is build in Angular) and also I saw in this repo that react sends the metadata as a queryParam, so we also did that, but no luck

<a class="donate-with-crypto btn btn-sm btn-primary" [attr.data-custom]="customUserId"
    href="https://commerce.coinbase.com/checkout/XXXXXXXXXXX?custom={{customUserId}}"
    target="_blank">
      <span>Add funds with Coinbase</span>
    </a>
    
    <script src="https://commerce.coinbase.com/v1/checkout.js?version=201807"></script>

Again, I would love to post this question in the right repo, but I couldn't find it, so any help would be much appreciated

Popup does not appear

A few days ago I cannot seem to open checkout popup when click on its commerce button anymore.

Chrome console shows this error:
Could not load content for https://commerce.coinbase.com/static/js/checkout.014c3ed1.js.map: HTTP error: status code 503, net::ERR_HTTP_RESPONSE_CODE_FAILURE

When I click on the link inside it says "Service Unavailable".

Is this problem from coinbase's end?

Curious

When does the onChargeSuccess method get called? Should it be simultaneous with when Coinbase sends out the success email?

I've got this as my prop, but it's not getting invoked for some reason.

onChargeSuccess={res => {
                          console.log(res);
                          axios
                            .post("/chargesuccess", res)
                            .then(console.log("success"))
                            .catch(err => console.error(err));
                        }}

Implementation confusions

when using the onChargeSuccess prop on the CoinbaseCommerceButton component I'm becoming confused.

when using the props onPaymentDetected I'm wanting to send myself the data so that I can check if the payment has been receieved and the close the modal so that the user can move on. After this, I'd also like to make to that a new charge is generated when the user clicks the Pay Button again so that they can create a new charge (as I'm selling many items on my site that could be potentially bought in rapid succession)

 onPaymentDetected={msgdata => {
                          console.log(msgdata);
                          document
                            .querySelector(
                              ".coinbase-commerce-iframe-container"
                            )
                            .remove();

Also, onChargeSuccess I'm looking to manipulate my DOM, as well as void the charge so that the next time a user clicks the pay with crypto button a new charge is generated. However, currently whenever a payment is completed, the next time I click on the Pay Button it just shows the "Your payment has been completed!" and doesn't generate a new charge.

Any help would be appreciated!

React -Element type is invalid on production

I'm using react latest version and "react-coinbase-commerce": "^1.6.0"

imported the react component as the documentation said import CoinbaseCommerceButton from 'react-coinbase-commerce';

now I got this error in my production: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
I think it has something to do with the component export.

As said in this #55 issue, it should be fixed by version 1.5.1.

New React (16.5.2) breaks react-coinbase-commerce library

Just a heads up, if you install the new version of Create-React-App and try and use this library it will break it. I have found the fix though.

In this portion of the code:
.amd?define("react-coinbase-commerce",["React"],t)

delete ["React"] and it will work.

onPaymentDetected error

Whenever a payment is detected, I get a TypeError:

checkout.b56640fe.js:1 TypeError: Cannot read property 'payment_detected' of undefined

My component looks like so:

 <CoinbaseCommerceButton
                        checkoutId="12a69b79-11bc-420b-****-06a13edddf6f"
                        styled={true}
                        onModalClosed={() => this.props.modalBody("")}
                        onPaymentDetected={res => {
                          console.log(res);
                        }} 
/>

Even with out console logging the res I'm hitting that same error. Can you show me how to handle responses with onPaymentDetected so that I can use that data to manipulate the DOM please?

looking to do something like this:
onPaymentDetected={res => {if(res.data === "success"} {close modal, make it so next time the Pay Now button is clicked a new charge is created so the user can make many purchases in relatively rapid succession}}

onChargeSuccess prop is not working

<CoinbaseCommerceButton
                      checkoutId="12a69b79-11bc-420b-a22c-06a17fdd72qf"
                      styled={true}
                      onLoad={() => this.props.modalBody("modalBody")}
                      disableCaching={true}
                      onChargeSuccess={res => {
                        console.log(res);
                        axios
                          .post("/chargesuccess", res)
                          .then(console.log("success"))
                          .catch(err => console.error(err));
                      }}
                      onModalClosed={() => this.props.modalBody("")}
                      customMetadata={`${this.state.email};${
                        this.props.parcelId
                      }`}
                      onPaymentDetected={res => {
                        console.log(res);
                        document
                          .querySelector(".coinbase-commerce-iframe-container")
                          .remove();
                        this.props.modalBody("");
                        this.setState({
                          paymentDetected:
                            "A Payment Has Been Detected. We will email you when the payment has been completed."
                        });
                        axios
                          .post("/chargedetected", res)
                          .then(console.log("success"))
                          .catch(err => console.error(err));
                      }}
                    >

Here is my component.

Expected behavior:

I expect to get data posted to my endpoint when the charge successfully goes through

Actual behavior:

I get a data posted to my endpoint upon detection of the payment, but I don't receieve any response whenever the payment has successfully gone through.

NPM package has 36 vulnerabilities

Just installd the react-coinbase-commerce npm package and it has 36 vulnerabilities.

added 1 package from 1 contributor and audited 42885 packages in 18.993s
found 36 vulnerabilities (6 low, 22 moderate, 8 high)

When I ran npm audit fix afterward all 36 of them required manual review.

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.