简体   繁体   中英

Implementing Stripe on Web: Uncaught ReferenceError: StripeCheckout is not defined

I am trying to implement Stripe payments in my web app. However, when using the sample code I am getting the following javascript error:

Uncaught ReferenceError: StripeCheckout is not defined

The code is like so:

    <script type="text/javascript" src="https://js.stripe.com/v2/"></script>

    <script>
      Stripe.setPublishableKey('pk_test_HnjFihOWwYTWnnsTLnZTmbgv');

      var handler = StripeCheckout.configure({
        key: 'pk_test_HnjFihOWwYTWnnsTLnZTmbgv',
        image: '/img/documentation/checkout/marketplace.png',
        token: function(token) {
          // Use the token to create the charge with a server-side script.
          // You can access the token ID with `token.id`
        }
      });

      $('#customButton').on('click', function(e) {
        // Open Checkout with further options
        handler.open({
          name: 'Demo Site',
          description: '2 widgets',
          amount: 2000
        });
        e.preventDefault();
      });

      // Close Checkout on page navigation
      $(window).on('popstate', function() {
        handler.close();
      });
    </script>

Any idea why I'm getting the error? Thank you.

StripeCheckout is built on top of Stripe. You need to include the js file that defines StripeCheckout.

<script src="https://checkout.stripe.com/checkout.js"></script>

See the documentation here: https://stripe.com/docs/checkout#integration-custom

The publishable key line should only be executed once the checkout.js file has been downloaded and your javascript file is compiled, for my project this works

<script type="text/javascript" src="https://js.stripe.com/v2/">

$(function(){

  Stripe.setPublishableKey('<%= Rails.configuration.stripe[:PUBLISHABLE_KEY] %>');

});

</script>

To test this open a console using developer tools in your browser and after the page has loaded, paste $('#payment-form') if the console returns a reference to the form in your page then its working.

I have put this in the form page in my app and it solved this error, when it was included in my javascript file even wrapped in the on ready event it caused the same error as you experienced

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM