在Expo React-Native应用程序中确认条纹付款意向

时间:2020-10-07 23:56:14

标签: react-native stripe-payments

我正在服务器上创建Stripe PaymentIntent,并将其客户端机密检索到Expo React-Native应用程序。在迁移到PaymentIntents之前,我使用了expo-payments-stripe及其PaymentStripe对象来执行paymentRequestWithCardFormAsync并获得令牌,这有助于我在没有PaymentIntent的情况下向客户的卡收费。

现在有了PaymentIntent,情况就不同了。我不再需要令牌,但是我需要PaymentMethodId来确认意图(如果我想在服务器上这样做)。当客户是新手时,我没有他的PaymentMethod,为了接收它,应该在客户端确认第一个PaymentIntent。在使用Web客户端的另一种情况下,我设法获得了Stripe Elements,并通过它可以确认PaymentIntent客户端。我没有为Expo React-Native应用程序找到任何类似的库来确认付款意向。

有人知道我该怎么做到吗?预先感谢。

1 个答案:

答案 0 :(得分:2)

我在EXPO中使用条纹。没有用于博览会的图书馆。我要做的是创建一个Webview以使用Stripe的Web软件包。这是一个例子:

这是Web视图,我在使用Stripe的位置渲染HTML,并调用“ window.ReactNativeWebView.postMessage”与应用程序进行Web视图通信。

 <WebView
        originWhitelist={["*"]}
        source={{ html: renderHtml(user,token) }}
        ref={webviewRef}
        onError={(syntheticEvent) => {
          const { nativeEvent } = syntheticEvent;
          console.warn('WebView error: ', nativeEvent);
        }}
        injectedJavaScript={javascriptAfterLoad()}
        onLoad={() => onLoadWebView()}
        onMessage={(event) => {
          let data = JSON.parse(event.nativeEvent.data);
          console.log("Esta es la data");
          console.log(data);
          switch (data.action) {
            case "subscribe":
         
              subscribe(data.data);

              break;

              case "retry":
            

                retryInvoiceWithNewPaymentMethod(data.data)
                

              break;

            default:
              console.log("ninguna accion");
              break;
          }

        }}
        style={{ marginTop: 20 }}
      />

这是HTML:

const renderHtml = (user,userToken) => {

  return /*html*/ `
    <html>

    <head>
        <title>Checkout</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    
        <link rel="stylesheet" href="./assets/normalize.css" />

        <script src="https://js.stripe.com/v3/"></script>
        <link rel="stylesheet" href="StripeElements.css">

        <style>
          ${globalCss()}
        </style>
    </head>
    
    <body style="width:100%;height:100%;">
    <div style="padding:0px 20px;">
    <h2 style="font-size:16px;margin-bottom:20px;">Empieza la membresía ahora y forma parte de nuestra comunidad de profesionales</h2>
    <h4>Beneficios:</h4>
    <ul>
    <li>Ten a tu disposición nuestra base de datos de profesionales de todas las áreas. </li>
    <li style="margin-top:10px;">Ofrece tus servicios y empieza a aumentar tus ingresos exponencialmente. </li>
    </ul>

    <h1 style="font-size:20px;">Ingresa tu número de tarjeta:</h1>
    <form id="subscription-form">
    <div id="card-element" class="MyCardElement">
        <!-- Elements will create input elements here -->
    </div>

    <!-- We'll put the error messages in this element -->
    <div id="card-errors" role="alert"></div>
    <button id="submit-premium" type="submit" style="margin-top:20px;"


    >
    
  
    <div class="">
    <div id="loading" class="hidden">Subscribing...</div>
    <span id="button-text" class="">  Empezar Membresía - US$14/año</span>
  </div>
    </button>
</form>
    
    </div>
    
    
       
        <script defer>

          try{
            var customerId = '${user.customerId}'
            

          }catch(err){
            alert(err)
          }
        
        ${globalJS(userToken)}
    
    
            var stripe = Stripe('STRIPE_API');
            var elements = stripe.elements();
    
          
            var style = {
                base: {
                    color: "#32325d",
                    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                    fontSmoothing: "antialiased",
                    fontSize: "16px",
                    "::placeholder": {
                        color: "#aab7c4"
                    }
                },
                invalid: {
                    color: "#fa755a",
                    iconColor: "#fa755a"
                }
            };
    
            var card = elements.create("card", { style: style });
            card.mount("#card-element");
            card.on('change', showCardError);
    
            function showCardError(event) {
                let displayError = document.getElementById('card-errors');
                if (event.error) {
                    displayError.textContent = event.error.message;
                } else {
                    displayError.textContent = '';
                }
            }
    
    
            var form = document.getElementById('subscription-form');
    
    
            form.addEventListener('submit', function (ev) {
                ev.preventDefault();
          
              
             
                // If a previous payment was attempted, get the latest invoice
                const latestInvoicePaymentIntentStatusKey = null; //get paymentintent from localstorage

             

            
                if (latestInvoicePaymentIntentStatus === 'requires_payment_method'  ) {
                    const isPaymentRetry = true;
                    // create new payment method & retry payment on invoice with new payment method

                
                    
                 try{

                  createPaymentMethod({
                        card,
                        isPaymentRetry,
                        invoiceId:latestInvoiceId,
                    });
                 }catch(err){
                   alert(err.message)
                 }
                 finally{
                      
                    }
                   
                } else {
                    // create new payment method & create subscription
                    try{
                      createPaymentMethod({ card,customerId });

                    }catch(err){
                      alert(err.message)
                    }
                    finally{
                      
                    }
                    
                }
            });
    
    
         
    
        </script>
    </body>
    
    
    </html>
    `;