3.6.102 • Published 10 months ago

@taktikorg/ab-deserunt v3.6.102

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

React Stripe.js

React components for Stripe.js and Elements.

build status npm version

Requirements

The minimum supported version of React is v16.8. If you use an older version, upgrade React to use this library. If you prefer not to upgrade your React version, we recommend using legacy react-stripe-elements.

Getting started

Documentation

Minimal example

First, install React Stripe.js and Stripe.js.

npm install @taktikorg/ab-deserunt @stripe/stripe-js

Using hooks

import React, {useState} from 'react';
import ReactDOM from 'react-dom';
import {loadStripe} from '@stripe/stripe-js';
import {
  PaymentElement,
  Elements,
  useStripe,
  useElements,
} from '@taktikorg/ab-deserunt';

const CheckoutForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  const [errorMessage, setErrorMessage] = useState(null);

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (elements == null) {
      return;
    }

    // Trigger form validation and wallet collection
    const {error: submitError} = await elements.submit();
    if (submitError) {
      // Show error to your customer
      setErrorMessage(submitError.message);
      return;
    }

    // Create the PaymentIntent and obtain clientSecret from your server endpoint
    const res = await fetch('/create-intent', {
      method: 'POST',
    });

    const {client_secret: clientSecret} = await res.json();

    const {error} = await stripe.confirmPayment({
      //`Elements` instance that was used to create the Payment Element
      elements,
      clientSecret,
      confirmParams: {
        return_url: 'https://example.com/order/123/complete',
      },
    });

    if (error) {
      // This point will only be reached if there is an immediate error when
      // confirming the payment. Show error to your customer (for example, payment
      // details incomplete)
      setErrorMessage(error.message);
    } else {
      // Your customer will be redirected to your `return_url`. For some payment
      // methods like iDEAL, your customer will be redirected to an intermediate
      // site first to authorize the payment, then redirected to the `return_url`.
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <PaymentElement />
      <button type="submit" disabled={!stripe || !elements}>
        Pay
      </button>
      {/* Show error message to your customers */}
      {errorMessage && <div>{errorMessage}</div>}
    </form>
  );
};

const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');

const options = {
  mode: 'payment',
  amount: 1099,
  currency: 'usd',
  // Fully customizable with appearance API.
  appearance: {
    /*...*/
  },
};

const App = () => (
  <Elements stripe={stripePromise} options={options}>
    <CheckoutForm />
  </Elements>
);

ReactDOM.render(<App />, document.body);

Using class components

import React from 'react';
import ReactDOM from 'react-dom';
import {loadStripe} from '@stripe/stripe-js';
import {
  PaymentElement,
  Elements,
  ElementsConsumer,
} from '@taktikorg/ab-deserunt';

class CheckoutForm extends React.Component {
  handleSubmit = async (event) => {
    event.preventDefault();
    const {stripe, elements} = this.props;

    if (elements == null) {
      return;
    }

    // Trigger form validation and wallet collection
    const {error: submitError} = await elements.submit();
    if (submitError) {
      // Show error to your customer
      return;
    }

    // Create the PaymentIntent and obtain clientSecret
    const res = await fetch('/create-intent', {
      method: 'POST',
    });

    const {client_secret: clientSecret} = await res.json();

    const {error} = await stripe.confirmPayment({
      //`Elements` instance that was used to create the Payment Element
      elements,
      clientSecret,
      confirmParams: {
        return_url: 'https://example.com/order/123/complete',
      },
    });

    if (error) {
      // This point will only be reached if there is an immediate error when
      // confirming the payment. Show error to your customer (for example, payment
      // details incomplete)
    } else {
      // Your customer will be redirected to your `return_url`. For some payment
      // methods like iDEAL, your customer will be redirected to an intermediate
      // site first to authorize the payment, then redirected to the `return_url`.
    }
  };

  render() {
    const {stripe} = this.props;
    return (
      <form onSubmit={this.handleSubmit}>
        <PaymentElement />
        <button type="submit" disabled={!stripe}>
          Pay
        </button>
      </form>
    );
  }
}

const InjectedCheckoutForm = () => (
  <ElementsConsumer>
    {({stripe, elements}) => (
      <CheckoutForm stripe={stripe} elements={elements} />
    )}
  </ElementsConsumer>
);

const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');

const options = {
  mode: 'payment',
  amount: 1099,
  currency: 'usd',
  // Fully customizable with appearance API.
  appearance: {
    /*...*/
  },
};

const App = () => (
  <Elements stripe={stripePromise} options={options}>
    <InjectedCheckoutForm />
  </Elements>
);

ReactDOM.render(<App />, document.body);

TypeScript support

React Stripe.js is packaged with TypeScript declarations. Some types are pulled from @stripe/stripe-js—be sure to add @stripe/stripe-js as a dependency to your project for full TypeScript support.

Typings in React Stripe.js follow the same versioning policy as @stripe/stripe-js.

Contributing

If you would like to contribute to React Stripe.js, please make sure to read our contributor guidelines.

karmamapreducereact posewhatwgviewtypedarrayprivatepureECMAScript 7busyreact-hooksreacthasOwnchaidiroutputairbnbhigher-orderES2016has-owntypanionRegExp.prototype.flagscss-in-jsqueryreact-testing-librarytimereduxtrimStartstyled-componentswaitdefineasserttestertestingprocessrfc4122stylingvalueecmascriptclassnameyaml_.extendinvariantquoteReactiveXimmerrequiredropmakeinternal slotescapelocationupcodesreal-timereadable0descriptordebuges8wgetparentcensorserializertacitexecebsRegExp#flagsform-validationpropnativeenvcryptofpslruwafECMAScript 2023east-asian-widthsqssettercurriedenumerableYAMLnamesMicrosoftES2022getterstringifierjson-schema-validationidcopycloudformationSystem.globallinkObject.valuespromiseAsyncIteratorendpointhttpsconfigurablepolyfilltrimEndstreamsownutilsenvironmentlook-upfoldercjkcode pointschecklockfilejsdiffString.prototype.trimswfObservableslookidleclassesObject.entriesfastuser-streamsincludeswalkrecursivepoint-freesymbolsfunctionrmdirBigUint64Arraypath$.extendshebangcompareoptionfantasy-landflattencurlstableawesomesauceObject.getPrototypeOfweakmappreprocessorfromdefinePropertyvaluesspeedguidexecfilewindowdependenciespatchrobustnodeshelltexttrimRightdeepclonees2016dynamodbfastcloneoncewebsymlinksArray.prototype.containsvisualnpmignoreglobal objectconcatMapTypedArray[[Prototype]]sideUint32ArrayECMAScript 2019tslibcompilerchineseStyleSheetstoragegatewayflatoptimistes2017ramdaURLvariablesparserstructuredClonefastcopyregular expressionsObject.isprivate datas3callbackfpfile systemmobileomitTypeScriptconsumeaccessibilityequalloadingWeakMapfull-widthdeep-cloneSetuninstalldotenvcreatepinoeveryeffect-tsrm -rfdeep-copyes6sharedarraybufferloadbalancingcore-jsloggingprotocol-buffersSymboleslint-pluginconfigfsUint16Arrayfindupresolveargvpushpackage.jsonterminalreact-hook-formlocalCSSutilitiesenvironmentsstreamdataviewespreePushhooksECMAScript 2017widthurlworkflowpipemkdirES2015jestapollofeedcloudfrontpropertiesposefnmatchdescriptorsfigletWebSocketsbyteLengthajaxdeepmatchtddreusechanneljshintgdprbufferbrowserlistECMAScript 2016es7groupfastifylibphonenumberES5gitignoresyntaxdirectoryqueuecircularECMAScript 2022getintrinsicwarningcolorunicodetypedes-shimscommanderqueueMicrotaskStreamsspinnersetImmediateextendhashIteratordomschemaelbletSymbol.toStringTagtransformquerystringdeepcopytoStringTagrgbflatMapformattingStreamcallbindextracssECMAScript 2021symboltermvestelasticacheanimationtoobjectautoprefixerstringifyrdsoptimizercolorsframeworkfast-deep-copyestreecontainsforEachframeres-abstracti18nschemeutilityyuptypesafekeyfetchES2023Function.prototype.nameamazonenderreversedidentifiersreducerprotoset@@toStringTagrangeerrorregular-expressiona11yreduceemojiproxyserializationECMAScript 5waapikoreanEStoSortedFloat32Arrayflagpostcss6to5agentpopmotionarraybufferxmlES3getredactmovetelephoneRxJSxtermpruneglobaltypessameValueZerovpcvalidateexecuteObject.keystranspilesearchpackage managertestzeroglobalscoreECMAScriptArrayBuffer#slicejsdompackageslastttyharmonyreverseminimalwalkingtapeprefixreact animationES2019transportobjobjecttsECMAScript 2015call-bindshrinkwrapjsonschemaglobal this valueargsexpressioniamlistenersbabeltranspilerES8callboundintrinsiccomputed-typesio-tsrm -frpositiveinaccessorFloat64Arrayes2015source mapspinnersjson-schema-validatoransiuuidbyteinspectasciimkdirpparseasyncsafehas256Object.fromEntriescommand-linenopeArray.prototype.includesmulti-packageJSONefficientcharactersfast-copyperformantartreadl10nbyteOffsetsettingsvarscolourpluginappObject.definePropertyexpresstypeofMapiterateRFC-6455isConcatSpreadableflagsgetPrototypeOfbannerslicepropertyeventEmittermatchAllcloudsearchistanbulRxmomentconsttypeerrorinputemitfast-cloneInt16ArrayfindserializenameavafindLastIndexPromisesortednegativeESnextgenericspackageruntimeprototypeshimdateCSSStyleDeclarationtrimLeftspringtc39scheme-validationObjectequalitystyleseventDispatchersnsrandomInt32Arrayregular expressionES6threejoiimmutableinferencetakebrowserstarterArrayBuffer.prototype.sliceglobalThisnegative zeromoduleassignbintrimreworkkinesisES2018zodoffsetgraphqlentriesweaksetUint8Arrayjson-schemasetPrototypeOfArray.prototype.flatbabel-coreignorehtmlBigInt64Arraycollectionqsrouterstyleguidechromiumroute53Array.prototype.flatMapfullwidthECMAScript 2020dragUint8ClampedArrayArray.prototype.findLastIndexforksuperstructcolumnssinatrakeysrssdiffselfcallwhichURLSearchParamsfunctionaltoArrayworkspace:*charactertapregularcloudtrailes2018formhelpersformatregexpjsonautoscalingnumberbundlinglengthprotobufdebuggerreadablestreamredux-toolkitpostcss-pluginlintinstallerArray.prototype.flattenjapanesephonefind-upclientfilesimpledbes5slotrmrequestES7browserslistasterisksfilternpmdataViewcloudwatchtypescriptismake dirastbinarieszxxhremrassertionstylemrugesturesUnderscoreremovetoolkitECMAScript 2018writableutil.inspectECMAScript 6varesinstallarktypecolumncommandbuffersawscoerciblesyntaxerrorclass-validatortypefunctionspyyamlconcatarraysajvimportexport.gitignoredayjses-shim APIArrayBuffermanipulationdataindicatordom-testing-library__proto__helperObservablefixed-widthsuperagentTypeBoxroutingjsxlanguageES2020fast-deep-clonecliapinodejsmanagermaperrorcachepnpm9childWeakSetgroupBytyped arrayprogressfulltouchspawnArray.prototype.filterfindLastponyfillArray.prototype.findLastiteratorassertsacornprettyArrayglobec2routejsclassnameswritejQueryfunction.lengthrules.envargumentcollection.es6importObject.assign3dECMAScript 3bddjavascriptclonepicomatchstringloggerboundcoverageregexeslintplugingetOwnPropertyDescriptorsomejasminehasOwnPropertycall-boundworkergetoptbeanstalkhookformresttostringtageslintdeterministiceslintconfigmodules
3.6.102

10 months ago

3.6.101

10 months ago

3.6.100

10 months ago

3.6.99

10 months ago

3.6.98

10 months ago

3.6.97

10 months ago

3.6.96

10 months ago

3.6.95

11 months ago

3.6.94

11 months ago

3.6.93

11 months ago

3.6.92

11 months ago

3.6.91

11 months ago

3.6.90

11 months ago

3.6.89

11 months ago

3.6.88

11 months ago

3.6.87

11 months ago

3.6.86

11 months ago

3.6.85

11 months ago

3.6.84

11 months ago

3.6.83

11 months ago

3.6.82

11 months ago

3.6.81

11 months ago

3.6.80

11 months ago

3.6.79

11 months ago

3.6.78

11 months ago

3.6.77

11 months ago

3.6.76

11 months ago

3.6.75

11 months ago

3.6.74

11 months ago

3.6.73

11 months ago

3.6.72

11 months ago

3.6.71

11 months ago

3.6.70

11 months ago

3.6.69

11 months ago

3.6.68

11 months ago

3.6.67

11 months ago

3.6.66

11 months ago

3.6.65

12 months ago

3.6.64

12 months ago

3.6.63

12 months ago

3.6.62

12 months ago

3.5.62

12 months ago

3.5.61

12 months ago

3.5.60

12 months ago

3.5.59

12 months ago

3.5.58

12 months ago

3.5.57

12 months ago

3.5.56

12 months ago

3.5.55

12 months ago

3.5.54

12 months ago

3.5.53

12 months ago

3.4.53

12 months ago

3.4.52

12 months ago

3.4.51

12 months ago

3.4.50

12 months ago

3.4.49

12 months ago

3.4.48

12 months ago

3.4.47

1 year ago

3.4.46

1 year ago

3.4.45

1 year ago

3.4.44

1 year ago

3.4.43

1 year ago

3.4.42

1 year ago

2.4.42

1 year ago

2.4.41

1 year ago

2.4.40

1 year ago

2.4.39

1 year ago

2.4.38

1 year ago

2.4.37

1 year ago

2.4.36

1 year ago

2.4.35

1 year ago

2.4.34

1 year ago

2.4.33

1 year ago

2.4.32

1 year ago

2.4.31

1 year ago

2.4.30

1 year ago

2.4.29

1 year ago

2.3.29

1 year ago

2.3.28

1 year ago

2.3.27

1 year ago

2.2.27

1 year ago

2.2.26

1 year ago

2.1.26

1 year ago

2.1.25

1 year ago

2.1.24

1 year ago

2.1.23

1 year ago

2.1.22

1 year ago

2.1.21

1 year ago

2.1.20

1 year ago

2.1.19

1 year ago

2.1.18

1 year ago

2.1.17

1 year ago

2.1.16

1 year ago

2.1.15

1 year ago

2.0.15

1 year ago

1.0.15

1 year ago

1.0.14

1 year ago

1.0.13

1 year ago

1.0.12

1 year ago

1.0.11

1 year ago

1.0.10

1 year ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

1 year ago

1.0.6

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago