Giter Club home page Giter Club logo

react-stripe-js's Introduction

Go Stripe

Go Reference Build Status Coverage Status

The official Stripe Go client library.

Requirements

  • Go 1.15 or later

Installation

Make sure your project is using Go Modules (it will have a go.mod file in its root if it already is):

go mod init

Then, reference stripe-go in a Go program with import:

import (
	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/customer"
)

Run any of the normal go commands (build/install/test). The Go toolchain will resolve and fetch the stripe-go module automatically.

Alternatively, you can also explicitly go get the package into a project:

go get -u github.com/stripe/stripe-go/v79

Documentation

For a comprehensive list of examples, check out the API documentation.

See video demonstrations covering how to use the library.

For details on all the functionality in this library, see the Go documentation.

Below are a few simple examples:

Customers

params := &stripe.CustomerParams{
	Description:      stripe.String("Stripe Developer"),
	Email:            stripe.String("[email protected]"),
	PreferredLocales: stripe.StringSlice([]string{"en", "es"}),
}

c, err := customer.New(params)

PaymentIntents

params := &stripe.PaymentIntentListParams{
	Customer: stripe.String(customer.ID),
}

i := paymentintent.List(params)
for i.Next() {
	pi := i.PaymentIntent()
}

if err := i.Err(); err != nil {
	// handle
}

Events

i := event.List(nil)
for i.Next() {
	e := i.Event()

	// access event data via e.GetObjectValue("resource_name_based_on_type", "resource_property_name")
	// alternatively you can access values via e.Data.Object["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]

	// access previous attributes via e.GetPreviousValue("resource_name_based_on_type", "resource_property_name")
	// alternatively you can access values via e.Data.PrevPreviousAttributes["resource_name_based_on_type"].(map[string]interface{})["resource_property_name"]
}

Alternatively, you can use the event.Data.Raw property to unmarshal to the appropriate struct.

Authentication with Connect

There are two ways of authenticating requests when performing actions on behalf of a connected account, one that uses the Stripe-Account header containing an account's ID, and one that uses the account's keys. Usually the former is the recommended approach. See the documentation for more information.

To use the Stripe-Account approach, use SetStripeAccount() on a ListParams or Params class. For example:

// For a list request
listParams := &stripe.CustomerListParams{}
listParams.SetStripeAccount("acct_123")
// For any other kind of request
params := &stripe.CustomerParams{}
params.SetStripeAccount("acct_123")

To use a key, pass it to API's Init function:

import (
	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/client"
)

stripe := &client.API{}
stripe.Init("access_token", nil)

Google AppEngine

If you're running the client in a Google AppEngine environment, you'll need to create a per-request Stripe client since the http.DefaultClient is not available. Here's a sample handler:

import (
	"fmt"
	"net/http"

	"google.golang.org/appengine"
	"google.golang.org/appengine/urlfetch"

	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/client"
)

func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	httpClient := urlfetch.Client(c)

	sc := client.New("sk_test_123", stripe.NewBackends(httpClient))

	params := &stripe.CustomerParams{
		Description: stripe.String("Stripe Developer"),
		Email:       stripe.String("[email protected]"),
	}
	customer, err := sc.Customers.New(params)
	if err != nil {
		fmt.Fprintf(w, "Could not create customer: %v", err)
	}
	fmt.Fprintf(w, "Customer created: %v", customer.ID)
}

Usage

While some resources may contain more/less APIs, the following pattern is applied throughout the library for a given $resource$:

Without a Client

If you're only dealing with a single key, you can simply import the packages required for the resources you're interacting with without the need to create a client.

import (
	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/$resource$"
)

// Setup
stripe.Key = "sk_key"

// Set backend (optional, useful for mocking)
// stripe.SetBackend("api", backend)

// Create
resource, err := $resource$.New(&stripe.$Resource$Params{})

// Get
resource, err = $resource$.Get(id, &stripe.$Resource$Params{})

// Update
resource, err = $resource$.Update(id, &stripe.$Resource$Params{})

// Delete
resourceDeleted, err := $resource$.Del(id, &stripe.$Resource$Params{})

// List
i := $resource$.List(&stripe.$Resource$ListParams{})
for i.Next() {
	resource := i.$Resource$()
}

if err := i.Err(); err != nil {
	// handle
}

With a Client

If you're dealing with multiple keys, it is recommended you use client.API. This allows you to create as many clients as needed, each with their own individual key.

import (
	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/client"
)

// Setup
sc := &client.API{}
sc.Init("sk_key", nil) // the second parameter overrides the backends used if needed for mocking

// Create
$resource$, err := sc.$Resource$s.New(&stripe.$Resource$Params{})

// Get
$resource$, err = sc.$Resource$s.Get(id, &stripe.$Resource$Params{})

// Update
$resource$, err = sc.$Resource$s.Update(id, &stripe.$Resource$Params{})

// Delete
$resource$Deleted, err := sc.$Resource$s.Del(id, &stripe.$Resource$Params{})

// List
i := sc.$Resource$s.List(&stripe.$Resource$ListParams{})
for i.Next() {
	$resource$ := i.$Resource$()
}

if err := i.Err(); err != nil {
	// handle
}

Accessing the Last Response

Use LastResponse on any APIResource to look at the API response that generated the current object:

c, err := coupon.New(...)
requestID := coupon.LastResponse.RequestID

Similarly, for List operations, the last response is available on the list object attached to the iterator:

it := coupon.List(...)
for it.Next() {
    // Last response *NOT* on the individual iterator object
    // it.Coupon().LastResponse // wrong

    // But rather on the list object, also accessible through the iterator
    requestID := it.CouponList().LastResponse.RequestID
}

See the definition of APIResponse for available fields.

Note that where API resources are nested in other API resources, only LastResponse on the top-level resource is set.

Automatic Retries

The library automatically retries requests on intermittent failures like on a connection error, timeout, or on certain API responses like a status 409 Conflict. Idempotency keys are always added to requests to make any such subsequent retries safe.

By default, it will perform up to two retries. That number can be configured with MaxNetworkRetries:

import (
	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/client"
)

config := &stripe.BackendConfig{
    MaxNetworkRetries: stripe.Int64(0), // Zero retries
}

sc := &client.API{}
sc.Init("sk_key", &stripe.Backends{
    API:     stripe.GetBackendWithConfig(stripe.APIBackend, config),
    Uploads: stripe.GetBackendWithConfig(stripe.UploadsBackend, config),
})

coupon, err := sc.Coupons.New(...)

Configuring Logging

By default, the library logs error messages only (which are sent to stderr). Configure default logging using the global DefaultLeveledLogger variable:

stripe.DefaultLeveledLogger = &stripe.LeveledLogger{
    Level: stripe.LevelInfo,
}

Or on a per-backend basis:

config := &stripe.BackendConfig{
    LeveledLogger: &stripe.LeveledLogger{
        Level: stripe.LevelInfo,
    },
}

It's possible to use non-Stripe leveled loggers as well. Stripe expects loggers to comply to the following interface:

type LeveledLoggerInterface interface {
	Debugf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Warnf(format string, v ...interface{})
}

Some loggers like Logrus and Zap's SugaredLogger support this interface out-of-the-box so it's possible to set DefaultLeveledLogger to a *logrus.Logger or *zap.SugaredLogger directly. For others it may be necessary to write a thin shim layer to support them.

Expanding Objects

All expandable objects in stripe-go take the form of a full resource struct, but unless expansion is requested, only the ID field of that struct is populated. Expansion is requested by calling AddExpand on parameter structs. For example:

//
// *Without* expansion
//
c, _ := charge.Get("ch_123", nil)

c.Customer.ID    // Only ID is populated
c.Customer.Name  // All other fields are always empty

//
// With expansion
//
p := &stripe.ChargeParams{}
p.AddExpand("customer")
c, _ = charge.Get("ch_123", p)

c.Customer.ID    // ID is still available
c.Customer.Name  // Name is now also available (if it had a value)

How to use undocumented parameters and properties

stripe-go is a typed library and it supports all public properties or parameters.

Stripe sometimes launches private beta features which introduce new properties or parameters that are not immediately public. These will not have typed accessors in the stripe-go library but can still be used.

Parameters

To pass undocumented parameters to Stripe using stripe-go you need to use the AddExtra() method, as shown below:

	params := &stripe.CustomerParams{
		Email: stripe.String("[email protected]")
	}

	params.AddExtra("secret_feature_enabled", "true")
	params.AddExtra("secret_parameter[primary]","primary value")
	params.AddExtra("secret_parameter[secondary]","secondary value")

	customer, err := customer.Create(params)

Properties

You can access undocumented properties returned by Stripe by querying the raw response JSON object. An example of this is shown below:

customer, _ = customer.Get("cus_1234", nil);

var rawData map[string]interface{}
_ = json.Unmarshal(customer.LastResponse.RawJSON, &rawData)

secret_feature_enabled, _ := string(rawData["secret_feature_enabled"].(bool))

secret_parameter, ok := rawData["secret_parameter"].(map[string]interface{})
if ok {
	primary := secret_parameter["primary"].(string)
	secondary := secret_parameter["secondary"].(string)
} 

Webhook signing

Stripe can optionally sign the webhook events it sends to your endpoint, allowing you to validate that they were not sent by a third-party. You can read more about it here.

Testing Webhook signing

You can use stripe.webhook.GenerateTestSignedPayload to mock webhook events that come from Stripe:

payload := map[string]interface{}{
	"id":          "evt_test_webhook",
	"object":      "event",
	"api_version": stripe.APIVersion,
}
testSecret := "whsec_test_secret"

payloadBytes, err := json.Marshal(payload)

signedPayload := webhook.GenerateTestSignedPayload(&webhook.UnsignedPayload{Payload: payloadBytes, Secret: testSecret})
event, err := webhook.ConstructEvent(signedPayload.Payload, signedPayload.Header, signedPayload.Secret)

if event.ID == payload["id"] {
	// Do something with the mocked signed event
} else {
	// Handle invalid event payload
}

Writing a Plugin

If you're writing a plugin that uses the library, we'd appreciate it if you identified using stripe.SetAppInfo:

stripe.SetAppInfo(&stripe.AppInfo{
	Name:    "MyAwesomePlugin",
	URL:     "https://myawesomeplugin.info",
	Version: "1.2.34",
})

This information is passed along when the library makes calls to the Stripe API. Note that while Name is always required, URL and Version are optional.

Telemetry

By default, the library sends telemetry to Stripe regarding request latency and feature usage. These numbers help Stripe improve the overall latency of its API for all users, and improve popular features.

You can disable this behavior if you prefer:

config := &stripe.BackendConfig{
	EnableTelemetry: stripe.Bool(false),
}

Mocking clients for unit tests

To mock a Stripe client for a unit tests using GoMock:

  1. Generate a Backend type mock.
mockgen -destination=mocks/backend.go -package=mocks github.com/stripe/stripe-go/v79 Backend
  1. Use the Backend mock to initialize and call methods on the client.
import (
	"example/hello/mocks"
	"testing"

	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
	"github.com/stripe/stripe-go/v79"
	"github.com/stripe/stripe-go/v79/account"
)

func UseMockedStripeClient(t *testing.T) {
	// Create a mock controller
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	// Create a mock stripe backend
	mockBackend := mocks.NewMockBackend(mockCtrl)
	client := account.Client{B: mockBackend, Key: "key_123"}

	// Set up a mock call
	mockBackend.EXPECT().Call("GET", "/v1/accounts/acc_123", gomock.Any(), gomock.Any(), gomock.Any()).
		// Return nil error
		Return(nil).
		Do(func(method string, path string, key string, params stripe.ParamsContainer, v *stripe.Account) {
			// Set the return value for the method
			*v = stripe.Account{
				ID: "acc_123",
			}
		}).Times(1)

	// Call the client method
	acc, _ := client.GetByID("acc_123", nil)

	// Asset the result
	assert.Equal(t, acc.ID, "acc_123")
}

Beta SDKs

Stripe has features in the beta phase that can be accessed via the beta version of this package. We would love for you to try these and share feedback with us before these features reach the stable phase. To install a beta version of stripe-go use the commit notation of the go get command to point to a beta tag:

go get -u github.com/stripe/stripe-go/[email protected]

Note There can be breaking changes between beta versions.

We highly recommend keeping an eye on when the beta feature you are interested in goes from beta to stable so that you can move from using a beta version of the SDK to the stable version.

If your beta feature requires a Stripe-Version header to be sent, set the stripe.APIVersion field using the stripe.AddBetaVersion function to set it:

Note The APIVersion can only be set in beta versions of the library.

stripe.AddBetaVersion("feature_beta", "v3")

Support

New features and bug fixes are released on the latest major version of the Stripe Go client library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.

Development

Pull requests from the community are welcome. If you submit one, please keep the following guidelines in mind:

  1. Code must be go fmt compliant.
  2. All types, structs and funcs should be documented.
  3. Ensure that make test succeeds.

Test

The test suite needs testify's require package to run:

github.com/stretchr/testify/require

Before running the tests, make sure to grab all of the package's dependencies:

go get -t -v

It also depends on stripe-mock, so make sure to fetch and run it from a background terminal (stripe-mock's README also contains instructions for installing via Homebrew and other methods):

go get -u github.com/stripe/stripe-mock
stripe-mock

Run all tests:

make test

Run tests for one package:

go test ./invoice

Run a single test:

go test ./invoice -run TestInvoiceGet

For any requests, bug or comments, please open an issue or submit a pull request.

react-stripe-js's People

Contributors

alic-stripe avatar andywang-stripe avatar awalker-stripe avatar bmathews-stripe avatar bsharon-stripe avatar cbala-stripe avatar christopher-stripe avatar cweiss-stripe avatar cyuen-stripe avatar dependabot[bot] avatar dweedon-stripe avatar elorakelkel-stripe avatar fruchtose-stripe avatar graceg-stripe avatar hofman-stripe avatar jackieosborn-stripe avatar jima-stripe avatar krissalvador-stripe avatar madhav-stripe avatar martinalong-stripe avatar maxwelly-stripe avatar mkcy3 avatar pololi-stripe avatar rado-stripe avatar rahul-kulkarni105 avatar thetrevdev avatar traitano avatar tuurekaunisto avatar tylersmith-stripe avatar wesbos 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  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

react-stripe-js's Issues

TypeError: cyclic object value

const cardElement = elements.getElement(cardNumberElement); // split form
const payload = await stripe.confirmCardPayment(secret, {card: cardElement});

this results in the cyclic object value error message in the title.

const payload = await stripe.confirmCardPayment(secret, {});

does the expected thing: payload.error has a bunch of stuff

card undefined when trying to get a token

Summary

when trying to create a token the responses token.card is undefined

const ibanElement = elements?.getElement(
  IbanElement
) as StripeIbanElement;
const { token } = (await stripe?.createToken(ibanElement, {
  currency: "eur",
  // eslint-disable-next-line @typescript-eslint/camelcase
  account_holder_name: name,
  // eslint-disable-next-line @typescript-eslint/camelcase
  account_holder_type: "individual",
})) as {
  token?: Token;
  error?: StripeError;
};

if (token) {
  const { card, id } = token; <-- card is undefined here
}

Other information

the http response:

Request URL: https://api.stripe.com/v1/tokens

response

{
  "id": "btok_1GIIRXGlONu5YADJCiOQJkss",
  "object": "token",
  "bank_account": {
    "id": "ba_1GIIRXGlONu5YADJJg8aFYLd",
    "object": "bank_account",
    "account_holder_name": "Jip Sterk",
    "account_holder_type": "individual",
    "bank_name": "STRIPE TEST BANK",
    "country": "NL",
    "currency": "eur",
    "last4": "5264",
    "name": "Jip Sterk",
    "routing_number": "110000000",
    "status": "new"
  },
  "client_ip": "xx.xxx.x.xxx",
  "created": 1583171559,
  "livemode": false,
  "type": "bank_account",
  "used": false
}

"Add Payment" with PaymentRequestButton

From what I can see from current implementation, you can have the PaymentRequestButton's canMakePayment method return non-null if you're on a supported browser with a payment method already loaded. Is it possible to support adding a payment method if you're on a supported browser but don't have one integrated yet? On our site, it feels like we're missing a subset of people who would happily do a faster checkout with GooglePay but we don't even have a button to display to them if they haven't loaded a card before. I know there are ways to do this when inegrateing with GooglePay and ApplePay directly, is this something Stripe's wrapper can also support?

Rollup inlining prop-types into ESM build

In trying to import the ES6 module and prop-types don't appear to be properly imported. The rollup build should import rather than inline proptypes.

Happy to look at fixing the build myself if needed, but wanted to notify you of the issue here.

Payment with saved cards?

Hello, I am having trouble coming up with a way to enable users to pay with their saved cards under their Stripe customer profile. Could I get some help in implementing such a solution?

Multiple Stripe Keys

I have an interesting issue in on site I'm working on for a client.

They want to swap stripe PKs (and the backend will swap SKs based on the same logic) based on a number of conditions in the checkout form.

We're using @stripe/react-stripe-js at the moment (having upgraded from the old react-stripe-elements package) and I've noticed that it does not like me switching PKs on the fly. Ignoring the warning and continuing anyway, obviously, causes the wrong key to be used.

Summary

The current flow is as follows:

  • The user fills out the form (swapping PK on the client side based on their inputs) & fills out their card details
  • They hit "pay"
  • We generate a payment intent on the backend using the correct key for their inputs
  • We try to capture it on the frontend, supposedly, using the correct key

The problem seems to be that <Elements> doesn't accept changes in the stripe prop at any point and always sticks to the first set key.

Other information

I did some digging and found that setContext only ever gets set when final is not true. https://github.com/stripe/react-stripe-js/blob/master/src/components/Elements.tsx#L135-L148

Is there a technical reason for this? Should I be switching to Stripe Checkout?

Thanks to @w1zeman1p on IRC for the initial help.

Please add a usage example for Connect

Summary

I'd like to put Connect on a react app but there's no example. The only example is for a swift app

Would it please be possible to add a usage example of react-stripe-js to make a stripe connect app?

Then it would be much easier to develop web platform marketplace type things...

Feature request: Render elements while stripe.js is loading, gives a way to handle loading and error states

Summary

A brief of the new API, including a code sample. Consider where this feature
would fit into our documentation, and what the updated documentation would
look like.

import React from "react";
import { Elements } from "@stripe/react-stripe-js";
import CardForm from "./../demos/CardForm";

const wait = n => new Promise(resolve => setTimeout(resolve, n));

const loadStripeAsync = () =>
  wait(3000).then(() =>
    import("@stripe/stripe-js")
      .then(module => module.loadStripe)
      .then(loadStripe => loadStripe("pk_test_6pRNASCoBOKtIshFeQd4XMUh"))
  );

const AsyncCardForm = () => (
//               I know that it may not be the best name for such behaviour
//                                              |
//                                              |
//                                              |
  <Elements stripe={loadStripeAsync()} aggresiveRendering>
    <CardForm />
  </Elements>
);

export default AsyncCardForm;

It'd be better for the user from the ux perspective to show stripe elements (CardElement etc) in a loading, disabled, skeleton state when stripe.js is loading.
It opens opportunity to load stripe.js on demand (150kb, 40kb[gzip] less for the whole website or app).

At the moment, stripe elements are not rendered until stripe.js is loaded.

Demo: https://codesandbox.io/s/react-stripe-js-cmm5m

Motivation

Describe the problem you are trying to solve with this API change. What does
this API enable that was previously not possible?

Better UX and showing user as quickly as possible the "most final" state of the UI.

Similar APIs

Is this new API similar to an existing Stripe API? Are there similar APIs or
prior art in other popular projects?

At the moment stripe elements are not rendered until stripe.js is fully loaded.
Developer may use simple conditions like stripe ? <Loaded /> : <Loading /> to render some kind of loaders, spinners or even fake inputs or forms. The problem is that it's quite annoying to duplicate the exact look of stripe elements.

Alternatives

How else could we implement this feature? Are there any existing workarounds
that would offer the same functionality? Why should we chose this
implementation over another?

Creating fake stripe elements by developers.

Scope

Which interfaces will this apply to? For example, is this specific to one
component, or does it affect all Element components? Does this set a precedent
for future interfaces we'll add?

It will apply to all Element components.

Developer could choose the way how stripe elements should be rendered:
a) the current behaviour which means - render stripe elements when stripe is loaded
b) new behaviour which means - render stripe elements in disabled/skeleton state and when stripe.js is loaded, stripe elements are unblocked and ready to use by the user

This would also require a way to handle errors of loading stripe.js.

Risks

Are there any security implications (for example, XSS)? What are some ways
users might get confused or misuse this feature?

The most serious risk is what should happen if stripe.js fails to load, what if it's loading for a long time (10s, 15s etc).

Cannot read property 'getElement' of null

Summary

We recently have migrated from react-stripe-elements to react-stripe-js. After following the migration steps, we are receiving the the following error when attempting to load our app: Cannot read property 'getElement' of null

Versions:
@stripe/react-stripe-js: ^1.1.2
@stripe/stripe-js: ^1.4.0

Our form with a CardElement is broken into 3 files:

index.js

// ...imports

// Confirmed correct API key
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_API_KEY)

const VenueCreate = () => (
  <Elements stripe={stripePromise}>
    <VenueForm />
  </Elements>
)

VenueForm.js

// ...imports

const VenueForm = () => {
  const stripe = useStripe()
  const elements = useElements()
  const cardElement = elements.getElement(CardElement) // Cannot read property 'getElement' of null

  const onSubmit = async () => {
    const { token, error } = await stripe.createToken(cardElement, options)
  }

  return // form containing <VenueFields />
}

VenueFields.js

// ...imports

const VenueFields =() => (
  <CardElement
    id="cardDetails"
    options={options}
    onBlur={handleBlur}
    onReady={handleReady}
    onChange={handleChange}
  />
)

I can't seem to troubleshoot what the issue is. Any assistance is appreciated. Thank you.

Other information

Error occurs in latest versions of Chrome, Firefox, and Safari.

loadStripe is not working with latest version

I'm following pretty closely to the documentation, and am receiving the following error:

Error: Invalid prop stripe supplied to Elements. We recommend using the loadStripe utility from @stripe/stripe-js.

"@stripe/react-stripe-js": "^1.0.3",
"@stripe/stripe-js": "^1.0.2",

import {Elements} from '@stripe/react-stripe-js';
import {loadStripe} from '@stripe/stripe-js';

const stripePromise = loadStripe("pk_test_key");

<Elements stripe={stripePromise}>
     <PaymentForm/>
</Elements> 

Please add classes + stateless functional components examples to readme.

Hi,

I understand hooks are fashionable in React at the moment, but people have been writing software using classes and stateless functional components for many years now. It makes more sense to optimize the documentation to be helpful to as many people as possible. Meet people where they are; not where you want them to be.

Specific proposal:

  • Example using local state with classes
  • Example using Stateless functional components and redux.
  • Optional Hooks example.

Custom display component

Summary

I would love the ability to add custom (react) components to the stripe iframes!

Motivation

The motivation comes from projects like react-credit-cards which adds a beautiful UI to visualize credit cards. This just makes the user experience so much better!

Alternatives

Add the option to add react-credit-cards to elements

Scope

This would probably impact all element components.

Risks

I don't know much about the risks involved with this, but they shouldn't be to crazy, if the communication to the outside gets denied!

How about Typescript support?

Hi. I'm currently working on a React app that's going to handle payments through Stripe. I'm using Typescript and make heavy use of the React Hooks API. I know that https://github.com/stripe/react-stripe-elements is still technically the way to go when it comes to handling Stripe in React but I really like what you did with this library and after reading through the Beta docs, I'd love to be able to just use this library and be done with it.

I know you're using Flow for typing but it would be great if you could consider also exporting Typescript type definitions. Any chance you will be doing this any time soon?

Would you even recommend trying to use this library over the legacy one at this moment in time? On one hand, I don't want to overcomplicate things by introducing a possibly flawed new library, but on the other, I would really just love to throw a useStripe and useElements into my component and be done with it.

Getting access to stripe_token to pass to handleSubmit

Hi,

I have a form with several fields, and a CardElement at the end.

I need a stripe_token field for a card source, to submitted with my form data for my server-side processing.

Is it possible to access a card token from the CardElement field?

Thanks, any help or pointers would be appreciated.

Type mismatch on ElementShape

type ElementsShape = { create: (type: string, options: MixedObject) => ElementShape; getElement: (type: string) => null | ElementShape; };

In your type declaration getElement receives a string, but in all examples and practice it appears to be getting an Element.

<IbanElement> default value

Summary

Hi,

When our clients already have registered an IBAN, we would like to autofill the input with it.
Unfortunately there is no "value" option for <IbanElement>

Is there any way I can achieve this ?

Thanks

loadStripe promise is not working correctly

I spend 1 day on trying to use loadStripe function but it always through promise error by using
const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
Error:
Uncaught Error: Invalid prop stripe supplied to Elements. Please pass a valid Stripe object or null. You can obtain a Stripe object by calling window.Stripe(...) with your publishable key.

but when I use window.Stripe("api_key") it works perfectly.
So, there are just 2 possibilities, loadStripe not work correctly or I'm using it wrongly.
Guys please have a look if anyone have solution of it

add example how to collect card country for postal code collection

Summary

I'm following the example here -- it collects postal code without element assuming the card is US.

A while back react elements dropped support for the postal element

Now that Postal support is dropped... How can I know if the card is US or CA so I can mask or validate the postal input properly?

Other information

stripe.createToken returns undefined token

while using the following snippet the method doesn't return a token.
however it does make a valid http call with 200 response.

import { IbanElement, useElements, useStripe } from "@stripe/react-stripe-js";
import { StripeError, StripeIbanElement, Token } from "@stripe/stripe-js";
import { Form, Formik } from "formik";
import React, { FC } from "react";

const Billing: FC = () => {
  const stripe = useStripe();
  const elements = useElements();
  return <form onSubmit={async () => {
    const ibanElement = elements?.getElement(
       IbanElement
     ) as StripeIbanElement;
    const { token } = stripe?.createToken(ibanElement, {
       currency: "eur",
       account_holder_name: name,
       account_holder_type: "individual",
     }) as {
      token?: Token;
      error?: StripeError;
     };
     console.log(token); // <-- undefined
  }}
  >
  <IbanElement options={{ supportedCountries: ["SEPA"] }} />
     <button type="submit" disabled={!stripe}>
       Pay
     </button>
  <form>
  );
}

Fix useLayoutEffect issue with nextjs SSR

hey @dweedon-stripe , great work on the new hook version of stripe-js, just played around with it a bit and found a minor issue with server-side rendering using nextjs, here's a modified example that worked perfectly, just FYI.

import React, { useState, useEffect, useRef } from 'react'
import Layout from '../components/layout'
import Head from 'next/head'
import { login, invokeAndRedirect, invoke } from '../utils/api'

import {
 CardElement,
 Elements,
 useStripe,
 useElements,
} from '@stripe/react-stripe-js'

const MyCheckoutForm = () => {
 const stripe = useStripe()
 const elements = useElements()

 const handleSubmit = async event => {
  const { error, paymentMethod } = await stripe.createPaymentMethod({
   type: 'card',
   card: elements.getElement(CardElement),
  })

  console.log( '[result] ', error, paymentMethod )
 }

 // early bailout when on server πŸ‘ˆ
 if(typeof window === 'undefined') return ''

 return (
  <div >
   <CardElement />
   <button onClick={handleSubmit}>Pay</button>
  </div>
 )
}

export default () => {
 const [stripe, setStripe] = useState(null)

 useEffect(() => {
  console.log('[set stripe] ', window.Stripe)
  setStripe(window.Stripe('pk_test_XXXX'))
 }, [])

 return (
  <React.Fragment>
   <Head>
    <script src="https://js.stripe.com/v3/"></script>
   </Head>
   <Layout>
    <Elements stripe={stripe}>
     <MyCheckoutForm />
    </Elements>
   </Layout>
  </React.Fragment>
 )
}

elements.getElement(CardElement) returning null

I'm using the minimalist example from the README.

elements.getElement(CardElement) is returning null for me:
Unhandled Rejection (IntegrationError): Invalid value for createPaymentMethod: card should be object or element. You specified: null.

Did I miss a step for registering the actual element?

Here's a simplified version of my actual code:

const PaymentForm = (props) => {

  const stripe = useStripe();
  const elements = useElements();

  const update = async () => {
    console.log(elements);
    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: elements.getElement(CardElement),
    });
    console.log(error)
    console.log(paymentMethod)
  }

  return (
    <div>
      <Form>
        <FormGroup>
          <Label>Payment Card</Label>
          <Elements stripe={stripe}>
            <CardElement />
          </Elements>
        </FormGroup>
        <Button type="button" onClick={update} color="primary">Update Billing Info</Button>
      </Form>
    </div>
  );
}

const Wrapper = (props) => {

  const config = useSelector(state => state.config.info);
  const stripe = window.Stripe(config.stripe);

  return (
    <Elements stripe={stripe}>
      <PaymentForm />
    </Elements>
  );
}

export default Wrapper;

Working Example of PaymentRequestButtonElement with hooks?

I've been working on trying to implement your library, and have run into an issue with the PaymentRequestButton. Working off of your examples directory and trimming away some of the extras, I've added the element itself along with the required useState and useEffect hooks (typeScript incoming):

const [
    paymentRequest,
    setPaymentRequest,
  ] = useState<stripe.paymentRequest.StripePaymentRequest | null>(null);

  useEffect(() => {
    const pr = stripe.paymentRequest({
      country: "US",
      currency: "usd",
      total: {
        label: "Demo total",
        amount: 100,
      },
    });
    pr.on("paymentmethod", async e => {
      e.complete("success");
    });

    pr.canMakePayment().then(result => {
      if (result) {
        setPaymentRequest(pr);
      } else {
        setError("something went wrong");
      }
    });
  }, [stripe]);

...
return (
  <div>
        {paymentRequest && <PaymentRequestButtonElement options={{paymentRequest}} />}
  </div>
)

From what I can see, this should be enough to get the button to render at the least, but the canMakePayment process is resolving with null every time without any additional information. I doubt it's an issue with the TS typing I've added or with how I've implemented the useStripe and useElement hooks, as I've got a fully functioning CardElement on the same page. Since this is a beta library, I can't actually find a fully functioning version of this PaymentRequestButtonElement anywhere else to reverse engineer. If the team has any insights or a working demo, I'd love to see them.

In case there's any chance it's relevant, I've attached my thin index.d.ts which is extending @types/stripe-v3.

I've been testing on Chrome with a loaded payment method. The Button does render and "work" on this stripe page with my testing browser, so that shouldn't be the issue either.

Redirection of payment gateway

const result = await stripe.confirmIdealPayment(iDEALPayment.clientSecret, {
            payment_method: {
              ideal: elements.getElement(IdealBankElement),
              // billing_details: {
              //   name: 'Jenny Rosen',
              // },
            },
            return_url: window.location.href,
          });

i'm using this method for completing the payment. now what it really does, is it simply redirects us to the strip's payment page for completing the payment on the same page. i wanted to have more control over this default redirection.
e.g => how can we redirect the user into new tab or in the same tab but in a modal. like it does in this exapmle while using card payment.
https://stripe.com/docs/payments/accept-a-payment

Module parse failed

Summary

I was using React 16.4 and upgraded to 16.8 to use the new version of react-stripe. I notice that as I import something from @stripe/stripe-js, I get this error:

[1] ./node_modules/@stripe/react-stripe-js/dist/react-stripe.umd.js
[1] Module parse failed: Unexpected token (1555:32)
[1] You may need an appropriate loader to handle this file type.
[1] |           return {};
[1] |       }
[1] |       const { paymentRequest: _, ...rest } = options;
[1] |       return rest;
[1] |   };

Other information

Here's my webpack info if that helps:

import webpack from 'webpack';
import path from 'path';

export default {
  debug: true,
  devtool: 'inline-source-map',
  noInfo: false,
  entry: [
    'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
    path.resolve(__dirname, 'src/index')
  ],
  target: 'web',
  output: {
    path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'src')
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
      {test: /(\.css)$/, loaders: ['style', 'css']},
      {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
      {test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
      {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
      {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
    ]
  }
};

Thanks in advance!

Should "Elements" go at the top level of my app?

Summary

Not a bug, just a question. In the examples, Elements goes at the very top level, similar to StripeProvider. Should this be the case for non-trivial applications too? Or should it go only where it is needed?

Focus/Keyboard Navigation broken in Safari + VoiceOver

Both the Stripe <CardElement> and the individual card elements (<CardNumberElement>, <CardExpiryElement> and <CardCvcElement>) exhibit unpredictable and broken behavior in Safari while using VoiceOver. This does not happen in Chrome with VoiceOver---Chrome+VoiceOver works as expected.

I was not sure whether to submit this here or https://github.com/stripe/stripe-js as I believe these issues are not unique to react-stripe-js.

Note that I am seeing this behavior using macOS 10.15.4 and Safari 13.1.

There are multiple problems with keyboard focus/navigation. It's rather hard to describe exactly what is going on in text so I've included these videos. Unfortunately QuickTime does not include system sound when doing screen recordings, but I've included the VoiceOver window so hopefully it will be somewhat clear what is happening. It's not hard to recreate these to see (and hear!) for yourself in Safari/VO.

All of these happen on the page https://stripe.dev/elements-examples/ but I've also recreated them in my own code.

Video 1:

video1
https://gfycat.com/rapidfearlessduck

I start with focus in the Card Number field (within the <CardElement>, I press tab, focus moves to the Card Expiration field, I press tab again, focus moves to the CVC field. So far everything is working as expected. Note that all field labels have been correctly read out by the screen reader.

Here's where things start going wrong:

I press tab again. I expect focus to move from the CVC field to the Pay $25 button. Instead, focus quickly cycles from Card Number to Card Expiration to CVC.

I press tab. Once again, I expect focus to move from the CVC field to the Pay $25 button. Instead, this time, focus moves to the Address field in the second form.

I've tested this with my own code and it seems that when focus leaves the CardElement it skips over the next tabbable element.

Video 2:

video2
https://gfycat.com/neighboringorganicbetafish

I start with focus in the Card Number field in the second form. I press tab. Focus moves to the Card Expiration field (as expected). However, Instead of reading the aria-label for the field aria-label="Credit or debit card expiration date" VoiceOver simply reads out "New Line" (you can see the newline character displayed on the VoiceOver window).

I press tab again. Focus moves to the CVCfield. Again, instead of reading the aria-label, VoiceOver reads out "New Line".

I press tab again. Instead of focus moving to the Pay $25 button, it skips over into the Name field in the third form.

Video 3:

video3

https://gfycat.com/warlikerewardingbighornedsheep

I'm using the following code with react-stripe-js:

const StripeExample = () => {
  const stripePromise = loadStripe('test');
  return (
    <div>
      <h1>Stripe Test</h1>
      <Elements stripe={stripePromise}>
        <CardNumberElement/>
        <CardExpiryElement/>
        <CardCvcElement/>
        <button>Checkout</button>
      </Elements>
    </div>
  );
};

I start with focus in the <CardNumberElement>. I press tab and nothing happens. Focus does not advance.

I press tab again. This time focus skips over the <CardExpiryElement> and moves to the <CardCvcElement>.

Video 4:

video4
https://gfycat.com/enchantingpinkbuck

Using the same code as Video 3. Here I start with focus on the Checkout button and press shift-tab to attempt to traverse backwards through the fields. I'm honestly not sure how many times I pressed shift-tab but from the video I think it's clear that focus jumps all over the place. You can not get from the Checkout button to the <CardNumberElement> with 3 presses of shift-tab as would be expected.

Video 5:

(This one's too long to embed.)
https://gfycat.com/bruisedzanyakitainu

Here I show VoiceOver with Chrome. Note that labels are read correctly when tabbing through fields, no fields/buttons are skipped, and shift-tab works as expected.

Summary

I've identified the following issues in Safari/VoiceOver:

  1. When inside the <CardElement> and the CVC field is focused. pressing tab loops focus through all the elements in the <CardElement> before refocusing the CVC field. The second time tab is pressed, focus skips over the next tabbable element.
  2. When tabbing through individual card fields, instead of reading out the labels, VoiceOver simply reads "New Line".
  3. Using the react-stripe-js elements, focus skips over the next tabbable element (e.g. focus skips from <CardNumberElement> over <CardExpiryElement> and into <CardCvcElement>)
  4. shift-tab behavior is broken

I hope this was clear. I'd be happy to elaborate on anything!

AuBankAccountElement bsbNumber and accountNumber missing

When I log the onChange event, the bsbNumber and accountNumber are not part of the event object. The bankName and branchName however, appear as expected.

Is this the expected behaviour?

This is how I am logging the event:

<AuBankAccountElement onChange={(e) => {
console.log(e)
}} />

Safari: CardExpiry focus state does not focus input initially

Summary

When I place CardNumber, CardExpiry, CardCvc individually on the page and try to tab through them, I can see the class .StripeElement--focus on the container element showing up, but the actual input for CardExpiry does not focus i.e. there is no caret nor can I input any text.

Weirdly if I tab backwards (shift+tab) from CardCvc, and go over the entire CardExpiry (it seems to stop 2-3 times internally) then arrive back at it, it does focus.

Other information

  • @stripe/[email protected]
  • Safari Version 13.0.5 (14608.5.12)
  • It does work on the latest Microsoft Edge (Webkit version)

Tell me why `.js` file works like` .tsx` file.

Thank you for a great project.

I have a question. I cloned and tried this project.
Tell me why .js file works like .tsx file.

I'm not developing well in my development environment.😭

γ‚Ήγ‚―γƒͺγƒΌγƒ³γ‚·γƒ§γƒƒγƒˆ 2019-12-05 18 07 15

Typescript error on getElement

Feature request or idea? Consider opening an
API review!

Summary

I receive a Typescript error when I attempt to use getElement by passing in a CardElement

Here's a code snippet:

const stripe = useStripe()
const elements = useElements()
const { error, token } = await stripe.createToken(
  elements.getElement(CardElement),
  {/* various data */ }
)

And this is the error I receive from Typescript:

No overload matches this call.
  The last overload gave the following error.
    Argument of type 'StripeCardElement' is not assignable to parameter of type 'StripeIbanElement'.
      Type 'StripeCardElement' is not assignable to type '{ on(eventType: "change", handler: (event: StripeIbanElementChangeEvent) => any): StripeIbanElement; on(eventType: "ready", handler: () => any): StripeIbanElement; on(eventType: "focus", handler: () => any): StripeIbanElement; on(eventType: "blur", handler: () => any): StripeIbanElement; update(options: Partial<...>...'.
        Types of property 'on' are incompatible.
          Type '{ (eventType: "change", handler: (event: StripeCardElementChangeEvent) => any): StripeCardElement; (eventType: "ready", handler: () => any): StripeCardElement; (eventType: "focus", handler: () => any): StripeCardElement; (eventType: "blur", handler: () => any): StripeCardElement; }' is not assignable to type '{ (eventType: "change", handler: (event: StripeIbanElementChangeEvent) => any): StripeIbanElement; (eventType: "ready", handler: () => any): StripeIbanElement; (eventType: "focus", handler: () => any): StripeIbanElement; (eventType: "blur", handler: () => any): StripeIbanElement; }'.
            Types of parameters 'handler' and 'handler' are incompatible.
              Types of parameters 'event' and 'event' are incompatible.
                Type 'StripeCardElementChangeEvent' is missing the following properties from type 'StripeIbanElementChangeEvent': country, bankNamets(2769)
index.d.ts(269, 5): The last overload is declared here.

The usage of the API seems to work, and from what I can tell of the type definitions the implementation shouldn't yield any errors.

I'm very much a Typescript novice, so my apologies if I've missed something obvious!

Other information

Here are some of my package versions:

    "@stripe/react-stripe-js": "^1.0.0-beta.7",
    "typescript": "^3.7.5"

And the contents of my tsconfig.json, in case that helps

{
  "compilerOptions": {
    // because we're compiling with Babel instead of TypeScript
    // and we're only using TypeScript for type checking, we'll set "noEmit"
    // to true so running type checking doesn't generate any files.
    "noEmit": true,
    "baseUrl": ".",
    "jsx": "react",
    "allowJs": true,
    "esModuleInterop": true
  },
  "exclude": ["node_modules", "**/*.spec.ts"]
}

Value prop doesn't change placeholder

I want to change the placeholder "Card number" to another language but with no success. Am I using the wrong prop or are you not able to change the placeholder?

const CARD_ELEMENT_OPTIONS = { value: 'test', style: { ... } }

Compatibility with react-redux

I am in the process of migrating from the older react-stripe-elements library, using the migration guide.

In the migration guide, it is mentioned that we need to replace injectStripe(). However, it is not clear to me whether this is safe to do when the component is connected to Redux using connect() from react-redux.

The old react-stripe-elements library had a whole Troubleshooting section in the docs talking about how injectStripe() should be used on the outside of connect(), as it would otherwise be unable to detect the context updates and so the component would fail to re-render.

As far as I understand, that issue from the Troubleshooting docs still applies to @stripe/stripe-js, as it also relies on context. Is that correct? Or do the hooks somehow solve it? Could you provide an example for using this library with react-redux?

Previously, I had code like this:

const CheckoutForm = (props) => {
    const {stripe, elements} = props;
    // ...
};
const CheckoutWithStripe = injectStripe(
    connect(null, {
        // ...
    })(
        reduxForm({
            // ...
        })(CheckoutForm)
    )
);
<StripeProvider apiKey="pk_test_1234">
    <Elements>
        <CheckoutWithStripe />
    </Elements>
</StripeProvider>

The migration guide inidcates that I should replace that as follows:

const CheckoutForm = (props) => {
    const stripe = useStripe();
    const elements = useElements();
    // ...
};
const CheckoutWithStripe = connect(null, {
    // ...
})(
    reduxForm({
        // ...
    })(CheckoutForm)
);
<Elements stripe={loadStripe('pk_test_1234')}>
    <CheckoutWithStripe />
</Elements>

Exposing mockStripe and mockElements for testing purposes

Would it be possible to expose your testing mocks as part of your library? It would make it a lot easier to write jest tests for components that implement the useStripe and useElements hooks, since they need to be wrapped in "valid" Elements components.

Clear CardComponent

Feature request or idea? Consider opening an
API review!

Summary

I would like to be able to clear the CardElement after submitting data however, it doesn't appear to be a way to get a ref. I am not seeing a way to get access to elementRef (previously: stripe-archive/react-stripe-elements#26) and it doesn't look like createElementComponent forwards Ref. Am I missing something?

The only method I have found to work is to change the key on the CardElement component. While this works, it seems like accessing the intended properties to reset is a better solution.

Other information

ElementsConsumer.propTypes - func undefined

Working with react-stripe-js and stripe-js betas, I'm getting the following error when trying to load up my webapp that uses stripe:

Uncaught TypeError: Cannot read property 'isRequired' of undefined

The offending line appears to be:

/**
 * @docs https://stripe.com/docs/stripe-js/react#elements-consumer
 */
const ElementsConsumer = ({ children, }) => {
    const ctx = useElementsContextWithUseCase('mounts <ElementsConsumer>');
    // Assert to satsify the busted React.FC return type (it should be ReactNode)
    return children(ctx);
};
ElementsConsumer.propTypes = {
    children: __exports.func.isRequired,  <-- ERROR FROM HERE
};

Based on what @christopher-stripe linked in the TypeScript issue, maybe this comes from that commonjs namedExports? Let me know if anything pops out to you guys.

What's the point of CardExpiryElement and CardCvcElement

The examples highlight two main ways to integrate React Stripe with Stripe.js. The most common is to use the CardElement component, which allows the user to enter the card number, expiry, and cvc all in one component. The second method is to pass the CardNumberComponent instead, which lets you move the expiry and cvc input into separate inputs for UI designs that desire that.

An example of that approach is here: https://github.com/stripe/react-stripe-js/blob/master/examples/hooks/2-Split-Card.js

But in every example where that happens, including the one above, CardExpiryElement and CardCvcElement are unused. The inputs are placed on screen and they have stubbed event handlers showing that something could be happening there, but nothing is. Their values aren't sent to stripe at all, so maybe it's on the developer to provide client side validation? Are they just included for show?

Support -webkit-text-security: disc; in CardCvcElement

I'm looking for a solution to help me set the CVC content displayed as dots.
ζˆͺεœ– 2020-04-14 δΈ‹εˆ12 06 31
ζˆͺεœ– 2020-04-14 δΈ‹εˆ12 06 19

At the begin, I found that -webkit-text-security CSS property is not supported in style option. So I was wondering to create my own CVC input component then set the CVC value when submit to create a stripe token.

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Input } from 'components/Form';
import i18n from 'utils/i18n';

const CVCInput = styled(Input)`
    -webkit-text-security: disc;
`;

const CVC = ({
    onBlur,
    onChange,
    ...props
}) => {
    const [cvc, setCVC] = useState('');

    const validateCVC = () => {
        return {
            complete: !(cvc.length < 3),
            empty: cvc === '',
            error: !(/(^[0-9]{3}$)|(^[0-9]{4}$)/.test(cvc))
        };
    };

    const handleChangeCVC = (e) => {
        const target = e.target || e;
        const value = target.value.replace(/\D/g, '');
        const error = validateCVC();
        onChange(error, value);
        setCVC(value);
    };

    const handleBlurCVC = () => {
        const error = validateCVC();
        onBlur(error);
    };

    return (
        <CVCInput
            placeholder={i18n.t('payment:payment.form.cvc')}
            value={cvc}
            maxLength={4}
            onChange={handleChangeCVC}
            onBlur={handleBlurCVC}
            {...props}
        />
    );
};

CVC.propTypes = {
    onBlur: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired
};

export default CVC;

Then I realize that the CVC value is not able to be set by myself due to its sensitivity. I can only use the stripe element for it. In the process I'm no doubt to touch the value inside. So the approach is failed.

I've read the similar issue in react-stripe-elements before and understood the response you gave.

However sometimes this request and the designs came from the whole team not only ourself. So I really need this.

I believe the simplest way to achieve it is extend the flexibility of input CSS property. Supporting -webkit-text-security: disc; is a quick and helpful way.

Is distributing as ES6 intentional

Hi!

This library is currently distributed as ES6 which is a bit troublesome as we need to support IE11 and would like to avoid transpiling node_modules if possible. We did not experience this with react-stripe-elements, so this was an unexpected migration step.

Would you consider distributing the package as ES5 instead?

PS. Thank you for an excellent developer experience using Stripe.

Support for react native?

Hi there, Stripe is an amazing payment gateway. I would like to know if this library support react-native also? if not, are there any library that support react native at the moment.

Thank you.

Support Selective Use of Stripe

Summary

Will this project address the long-standing issue of not being able to truly selectively and dynamically use Stripe in React?

Heretofore, developers have been forced to live with persistent controller iframes and event listeners throughout their SPA unless they want to develop their own custom hacks to delete upon component dismount.

It would be great if this library somehow included the logic to remove all elements, dependencies, etc., from the DOM, etc.

I am intrigued by this project, but I don't see the point, if it doesn't address what is arguably developers' top bugaboo. I don't understand why this has been ignored for so long.

Other information

Refer to stripe-archive/react-stripe-elements#99 for additional context.

Developers have shared countless JavaScript hacks to "clean up" after stripe. In the end, developers are trying to remove these iframes (and related event listeners):

stripe-controller-inspector

I am submitting this issue at the request of stripe engineers on freenode. I would definitely tag this as a question.

Uncaught ReferenceError: regeneratorRuntime is not defined

When running the example hooks/2-split card with react 16.12, built with parceljs
I get this error:
Uncaught ReferenceError: regeneratorRuntime is not defined
This is in the handleSubmit method of CheckoutForm.
It can be fixed by removing "async" on the declaration for handleSubmit() and then
having stripe.createPayment({blah}).then(payload => { etc})

Tried this on both Chromium and Firefox

No support for on[KeyboardEvent] prevents use of escape key to close modals

Note: I'm currently using react-stripe-elements, but since it appears current development is happening here and issue is in both places, this is where I'm filing - if I should move it please let me know!

Summary

I'm working on a site where payment options, and therefore the Stripe Elements, are often rendered in a modal. In order to be compliant with current accessibility recommendations regarding modals, the escape key must close modals. However, when focus is in one of the Stripe elements, there is no way to detect the escape key press. It would be nice to have a prop option similar to that for onChange, onFocus, etc, that could be used to listen to keyboard events to assist in meeting accessibility guidelines.

Although I don't need it in this particular case, this could also potentially assist when developers need to do custom management of tab and shift+tab in modals in order to prevent keyboard focus from moving to the document underneath the modal.

Confirm Card Payment with Idempotent key

Looks like I am unable to confirm the card payment using confirmCardPayment method from useStripe by passing in an options object with idempotency_key.

const stripe = useStripe();
stripe.confirmCardPayment(
        intentSecret,
        {
          payment_method: {
            card: elements.getElement(CardElement),
          },
        },
        {
          idempotency_key: orderId, // not getting used
        }
      );

Is this an expected behavior?

Post Mortem on NPM Issue?

Hello Stripe team,

Can we please have a post mortem on what exactly happened with @stripe/react-stripe?

Yesterday I merged a massive pull request only to find out today that it was never auto deployed. The reason why the deploy never happened was because yarn got a 404 response on this package:

error An unexpected error occurred: "https://registry.yarnpkg.com/@stripe/react-stripe-js/-/react-stripe-js-7.0.0-beta.1.tgz: Request failed "404 Not Found"".

I've done 75 deploys previously using this Stripe package and my yarn/package manifest never changed so I assumed this was a npm/yarn CDN hosting issue. Upon visiting the package page on NPM, I learn that this actually been deprecated

Screen Shot 2020-03-04 at 2 42 10 PM

Moving a NPM package that relates to accepting credit cards with such brazen carelessness is extremely troubling. How am I supposed to know if Stripe's NPM account was hacked and this new NPM location is actually a compromised piece of software? This is exactly how it would happen if Stripe's account is hacked.

This sudden deprecation/rename was handled very poorly. As of right now, I still don't actually know if @stripe/react-stripe-js is compromised or not. Please remember: this is not just another React Component on Github/NPM. This one is responsible for dealing with payments. When you suddenly change the name of an NPM package it will creates A LOT of consternation for security-minded people.

Can someone official from Stripe please confirm this new package you're forwarding to is actually genuine and not compromised?

Thank you,

Michael

update "amount" for <PaymentRequestButtonElement />

I'm trying to make the "amount" update based on state change.

However, despite the state's value changing correctly, the Payment Request's "amount" remains at the initial value.

Please check out this codesandbox for a reproduction / code. It is a forked version of the offical example, with a simple button that updates the react state called "amount".

To see what I mean on the frontend, you can check: https://oushf.csb.app/payment-request-button-element

Any ideas how to make this work? There are no docs about this on stripe.com and I think this is an extremely common use case..

Thanks!

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.