Stripe grails integration


In this tutorial, we will build a very simple 1 controller grails application that will process a fake credit card charge.

If you are new to Stripe, “Stripe is a developer-friendly way to accept payments online and in mobile apps.” http://stripe.com

Its important to note how Stripe processes credit card information. Stripe provides an Javascript API that will asynchronously retrieving a token representation of the credit card credentials. This prevents you from having to deal with credit card information server side. Here is an example on how you get the token.

Tutorial source code https://github.com/mcroteau/stripe-example

1. Create Application

grails create-app stripe-example

2. Add dependency

First step, add the stripe maven dependency in the dependencies section of the BuildConfig.groovy

runtime 'com.stripe:stripe-java:1.12.0'

3. CheckoutController

Now lets create a CheckoutController for payment process

grails create-controller Checkout

4. Create gsps

Grails will create the controller grails-app/controllers/CheckoutController.groovy and a grails-app/views/checkout directory. Lets go ahead and create a grails-app/views/checkout/index.gsp and a grails-app/views/checkout/checkout.gsp

5. grails-app/views/checkout/index.gsp

<!DOCTYPE html>
<html>
<head>
	<meta name="layout" content="main"/>
	<title>Stripe Checkout</title>
	
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	
	<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
	
	<style type="text/css">
		.container{
			padding:30px;
		}
		.form-group{
			margin:10px 0px;;
		}
		label{
			display:block;
			font-weight:bold;
		}
		label span{
			font-size:11px;
			font-weight:normal;
			display:block;
		}
	</style>
</head>
<body>

	<div class="container">
		<g:form action="checkout" method="post" id="checkout_form" name="checkout_form">
			
			<!-- * Important * you will need to set a hidden form input after retrieving the Stripe Token-->
			<input type="hidden" name="stripeToken" value="" id="stripeToken"/>
			
			<div class="form-group">
				<label>Amount</label>
				<input type="text" name="amount" value="" id="amount" size="7"/>
			</div>
			<div class="form-group">
				<label>Credit Cart # <span>(for testing purposes use 4242424242424242)</span></label>
				<input type="text" name="cc_number" value="4242424242424242" id="cc_number"/>
			</div>
			<div class="form-group">
				<label>CVC <span>(Any 3 numbers)</span></label>
				<input type="text" name="cvc" value="" id="cvc" size="3"/>
			</div>
			<div class="form-group">
				<label>Expiration <span>(MM/YYYY)</span></label>
				<input type="text" name="exp_month" value="" id="exp_month" size="2"/>
					 / 
				<input type="text" name="exp_year" value="" id="exp_year"/>
			</div>
		</g:form>

		<!-- Placing outside the form as we are going to manually submit the form after recieving the Stripe Token from Stripes web service -->
		<div class="form-group">
			<input type="submit" name="submit" size="4" id="submit" value="Stripe Checkout"/>
		</div>
		
	</div>
	

<script type="text/javascript">
			
$(document).ready(function(){

	var $tokenInput = $('#stripeToken'),
		$cardNumberInput = $('#cc_number'),
		$cardCvcInput = $('#cvc'),
		$cardExpMonth = $('#exp_month'),
		$cardExpYear = $('#exp_year'),
		$checkoutForm = $('#checkout_form');

	Stripe.setPublishableKey("YOUR STRIPE PUBLISHABLE KEY");

	$('#submit').click(checkCreditCardValues);
	
	function checkout(){
		console.info('submit form, process payment, create transaction', $checkoutForm);
		$checkoutForm.submit();
	}

	function setStripeTokenInput(code, token){
		console.info("retrieved token : ", token)
		//set hidden stripe token input
		$tokenInput.val(token.id)
		checkout();
	}

	 /**
	 	* IMPORTANT *
	    This is the somewhat tricky part, you will receive a token object in 
	    the callback function arguments.  You want to take this token and set
	    a hidden form input that later will get passed to the server side
	**/
	
	function getStripeToken(){
		console.info('get stripe token')
		Stripe.card.createToken({
		    number    : $cardNumberInput.val(),
		    cvc       : $cardCvcInput.val(),
		    exp_month : $cardExpMonth.val(),
		    exp_year  : $cardExpYear.val()
		}, setStripeTokenInput);
	}


	function checkCreditCardValues(){
		if($cardNumberInput.val() != "" &&
				$cardCvcInput.val() != "" &&
				$cardExpMonth.val() != "" &&
				$cardExpYear.val() != ""){
			getStripeToken();
		}else{
			alert('Please make sure all credit card information is provided')
		}
	}
	
})
</script>			
</body>
</html>

6. grails-app/views/checkout/checkout.gsp

<!DOCTYPE html>
<html>
<head>
	<meta name="layout" content="main"/>
	<title>Stripe Checkout</title>
</head>
<body>	
	<g:if test="${flash.message}">
		<h2 class="message" role="status">${flash.message}</h2>
	</g:if>
</body>
</html>	

7. CheckoutController.groovy

package stripe.example

import com.stripe.Stripe
import com.stripe.model.Charge

class CheckoutController {

    def index() { }
	
	def checkout() {
	
		try {
			//Set Stripe Secret/Api Key
			Stripe.apiKey = "YOUR STRIPE API KEY"
			  		
			def amount = Double.parseDouble(params.amount)
			def token = params.stripeToken
			
			if(amount && token){
				println "\n\nSTRIPE API KEY : ${Stripe.apiKey} -> TOKEN : ${token} -> AMOUNT : ${amount}\n\n"
				//convert amount into cents
    			def amountInCents = (amount * 100) as Integer
    			
				//create Stripe parameters object
    			def chargeParams = [
    			    'amount': amountInCents, 
    			    'currency': 'usd', 
    			    'card': token, 
    			    'description': "Order Placed ${amount}"
    			]
    			
    			Charge.create(chargeParams)
				flash.message = "Successfully charged Stripe"
			}

    	
		} catch (Exception e) {
			flash.message = "Something went wrong ..."
			println("Status is: " + e.printStackTrace());
		}	
	}
}

8. Run the app

Browse to http://localhost:8080/stripe-example/checkout

Here is a link to the complete tutorial source code https://github.com/mcroteau/stripe-example

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s