Monday, December 25, 2017

Easy Stripe Checkout using AngularJS

Here's a simple way to use angularJS to integrate Stripe Checkout into your web page.

First, in your HTML add the Stripe script reference inside the head tag:

<head>
[angularJS includes here]
<script type="text/javascript" src="https://checkout.stripe.com/checkout.js"></script>
</head>

Next, in the body declare a link or button with an ng-click handler to invoke a method in your controller:

<a href="" ng-click="onStripe('<%= StripeConstants.PUBLIC_API_KEY %>', '<%= request.getAttribute("email") %>')">Stripe Checkout via angularjs</a>

*Note: My page is a JSP and since my user is already signed in I know the email so I push it in to the request object and pull it into my JSP page. Likewise, I load my Stripe public key (encrypted) from a properties file located on my server. Again, I pull that into my JSP and then pass both the user's email and the Stripe public key in to the click handler in my controller.

That's it for the HTML page. Now on to the controller.

I'll need two functions - the click handler to invoke Stripe Checkout and a function to handle the Stripe callback with the token representing the payment details.

// stripe will call this once it has successfully created a token for the payment details
        $scope.onToken = function(token) {
            console.log(token);
            // now call a service to push the necessary token info to the server to complete the checkout processing
        };

        $scope.onStripe = function(apiKey, userEmail) {
            var handler = StripeCheckout.configure({
                key: apiKey,
                image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
                locale: 'auto',
                token: $scope.onToken
            });

            handler.open({
                panelLabel : 'Subscribe',
                amount : 4995,
                name : 'My Product Name here',
                description : '$49.95 Monthly Subscription',
                email : userEmail,
                zipCode : true,
                allowRememberMe : false
            });
        };


That's it!

Here's what the Stripe Checkout form looks like with the above configurations: