At your page head, add a script tag and add the following line inside:
Stripe.setPublishableKey('Your_Publishable_Key');
For sure, you will replace 'Your_Publishable_Key' with your publishable key either in Test of Live mode. The above line identifies your account in stripe. You have to add reference for jquery if it is not added yet in the view or the containing layout.
The scenario now is to send a request to stripe server using stripe js with credit card info and receives a token that will be used in server side API invokes. To send the request we need to handle form submission event to send the request before posting back.
Add the following lines to your script tag to handle form submission:
$(document).ready(function () {
$("#payment-form").submit(function (event) {
// disable the submit button to prevent repeated clicks
$('.submit-button').attr("disabled", "disabled");
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('#CardNumber').val(),
cvc: $('#CVC').val(),
exp_month: $('#ExpirationMonth').val(),
exp_year: $('#ExpirationYear').val()
}, stripeResponseHandler);
return false; // submit from callback
});
});
The above code block handles the submission behavior of "payment-form" form. Remeber that, you just need to set the id of your form to "payment-form". This can be done by overriding the Html.BeginForm() method in the view to be:
@using (Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object> { { "id", "payment-form" }, { "enctype", "multipart/form-data" } }))
Stripe.CreateToken() method sends a request to stripe using the publishable key which is set before. As you can see we disabled the submit button first to prevent multiple requests. Note: the jquery selector finds the submit button using a css class "submit-button", you can either add this css class to your submit button or change the selector to find other attribute value.
By looking to CreateToken() method parameters, you can notice that the first parameter is a JSON object that contains credit card information. The second parameter is stripeResponseHandler, this handler - which will be created soon- is responsible for handling the response returned from the sent Stripe request.
Let's now write the definition of the stripeResponseHandler. In the script tag, write the following script block:
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit-button').removeAttr("disabled");
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' id='stripeToken' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
As you see above, we checked first for errors, and if exist we display error message in a div has a css class "payment-errors". So, you need to add this div to your view which may look like this:
<span class="payment-errors"></span>
In case of no errors we catch the response id into a variable called token. Make a hidden field "stripeToken" to carry the token value. Now we have the token saved in the form, this means we can post this token to the server in the next postbacks. So, we are ready for submitting the form.
Stripe.Net API
It is the time now to write our server side code which makes the real payment operations. Stripe.Net needs from you to identify your account in stripe by setting your secret key. You secret key is to be set into the application's web config in appSettings section, which will look like that:
<appSettings>
<add key="StripeApiKey" value="Your_Secret_Key" />
</appSettings>
We have to write the post action which handles the form postback. Open PaymentController and add a new action and name it "Buy" with [httpPost] attribute. Below is the full definition of the Buy() action:
[HttpPost]
public ActionResult Buy(FormCollection form)
{
var customerToken = form["stripeToken"];
var buyerModel = new BuyerViewModel();
UpdateModel(buyerModel, form.ToValueProvider());
// create customer
var customerOptions = new StripeCustomerCreateOptions
{
Email = buyerModel.Email,
Description = buyerModel.FullName,
TokenId = customerToken
};
var service = new StripeCustomerService();
var customer = service.Create(customerOptions);
// create a charge for the added customer
var myCharge = new StripeChargeCreateOptions
{
AmountInCents = 1000,
Currency = "usd",
CustomerId = customer.Id
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return RedirectToAction("PaymentComplete", "Payment", new RouteValueDictionary { { "chargeId", stripeCharge.Id } });
}
As you can see, We get the stripeToken hidden field value to be used in our request. After getting the token, we may need to take the inputs value into an empty BuyerViewModel model.
UpdateModel(buyerModel, form.ToValueProvider());
Note: Make sure that you are using namespace "Stripe"
using Stripe;
Now, it is the time to create the customer. To do that we can make an object of StripeCustomerCreateOptions and set Email, Description and Token of customer's credit card info. Note: The StripeCustomerCreateOptions has different initializers (e.g set credit card info instead of token, look at https://github.com/jaymedavis/stripe.net Create customer section).
Note: I preferred to set description as customer full name, but you may have other representation of customer description.
As you can see, customer creation is completed by:
var customer = service.Create(customerOptions);
At this moment, you can see the customer in your customers page in stripe management web site.
We can now use customer.id to make an actual payment. All we need is to determine the amount to be charged in cents and pass the added customer id to the StripeChargeCreateOptions initialiazer. Then complete the creation by:
var stripeCharge = chargeService.Create(myCharge);
At this moment, you can see the payment that has been done. You can see it in either your payments page or in the added customer page; at payments section.
In our example, we redirects the buyer to another page that inform him that the payment has been done successfully if it really does :). So, we created a new action for PaymentComplete to redirect the buyer to it after completing payment and inform him with the charge id. You may choose any other behavior after buyer completes his/her payment. PaymentComplete() action presented by a view that contains just a successful message and charge id.
Now we have made a completed payment operation - as you can see - in an easy way and with a little number of lines.
What else you can do?
You can do some other stripe operations like: Refunding, Editing customers, Editing plans, Editing subscriptions, Editing coupons and Retrieving token details.
You can find very useful examples here: