Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get js POST in asp.net webform?

I know its a rudimentary questions, but I am out of practice on webforms. I am using Stripe.js for the first time, and want to use it in conjunction with stripe.net to process the client side. Here is the client code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="StripePage.aspx.cs" Inherits="StripePage.StripePage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
    // This identifies your website in the createToken call below
    // You need to put your real publish key here.
    Stripe.setPublishableKey('pk_test_1nDJ3hA1Mv2Sy9bUoYcBMXmm');
    // ...
    // I am using jquery to process the payment. It knows what form to 
    // process it on based on the name 'payment-form'
    jQuery(function ($) {
        //payment submission
        $('#payment-form').submit(function (event) {
            var $form = $(this);

            // Disable the submit button to prevent repeated clicks
            $form.find('button').prop('disabled', true);

            Stripe.createToken($form, stripeResponseHandler);

            // Prevent the form from submitting with the default action
            return false;
        });

        //if there is a error, it is displayed on the page if there was
        //no error this is where it gets sent to the server.
        var stripeResponseHandler = function (status, response) {
            var $form = $('#payment-form');

            if (response.error) {
                // Show the errors on the form
                $form.find('.payment-errors').text(response.error.message);
                $form.find('button').prop('disabled', false);
            } else {
                // 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" name="stripeToken" />').val(token));
                // and submit
                $form.get(0).submit();
            }
        };
    });
</script>

<form method="POST" id="paymentForm" runat="server">
    <span class="payment-errors" runat="server"></span>

    <div class="form-row">
        <label>
            <span>Card Number</span>
            <br />
            <input id="number" type="text" data-stripe="number" clientidmode="Static" />
            <input type="text" size="20" data-stripe="number" runat="server" />
        </label>
    </div>

    <div class="form-row">
        <label>
            <span>CVC</span>
            <br />
            <input type="text" size="4" data-stripe="cvc" runat="server" />
        </label>
    </div>

    <div class="form-row">
        <label>
            <span>Expiration (MM/YYYY)</span>
            <br />
            <input type="text" size="2" data-stripe="exp-month" runat="server" />
        </label>
        <br />
        <input type="text" size="4" data-stripe="exp-year" runat="server" />
    </div>
    <asp:Button ID="submit" ClientIDMode="Static" runat="server" Text="SubmitPayment" OnClick="submit_Click" />
</form>
</asp:Content>

The last call in JS creates a JSON object that I want to know how to get to on the C# page on the button click:

protected void submit_Click(object sender, EventArgs e)
{
....
}

I am wanting to do the javascript implementation to avoid having to do PCI compliance. Am I approaching this incorrectly? Should it be all Stripe.net to process everything, and skip the js entirely? Or if this is right, how can I get the form post data in the button click event?

like image 286
ledgeJumper Avatar asked Aug 04 '13 01:08

ledgeJumper


2 Answers

Thanks for the tips in the comments. After much perusal of the internet and hair pulling, I walked away for a bit and came back with this solution.

  1. Made the button just a standard html input (not the asp:Button)
  2. Got the posted back information that was being sent via the JavaScript in the Page_Load event like so

Code Behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        StripeConfiguration.SetApiKey("[API Secret Key");
        NameValueCollection nvc = Request.Form;
        string amount = nvc["amount"];
        var centsArray = amount.Split('.');
        int dollarsInCents = Convert.ToInt32(centsArray[0]) * 100;
        int remainingCents = Convert.ToInt32(centsArray[1]);
        string tokenId = nvc["stripeToken"];

        var tokenService = new StripeTokenService();
        StripeToken stripeToken = tokenService.Get(tokenId);


        var myCharge = new StripeChargeCreateOptions
        {
            TokenId = tokenId, 
            AmountInCents = dollarsInCents + remainingCents,
            Currency = "usd"
        };
        var chargeService = new StripeChargeService();
        StripeCharge stripeCharge = chargeService.Create(myCharge);
    }
}

Seems like using the NameValueCollection (which lives in System.Collections.Specialized namespace) gave me the ability to grab what I needed from the Request.Form by pulling it out via variable name. Since I new the variable names, it was simply a matter of grabbing them and then following the Stripe .NET library documentation to get the token and process the payment.

like image 77
ledgeJumper Avatar answered Oct 17 '22 06:10

ledgeJumper


I want to just post a comment to the answer, but I'm not allowed to yet. So, this isn't really an answer, more of a response to the OP's own findings.

I'm doing the exact same thing, using Stripe.js. I can simply grab stripeToken using Request.Form, and get all other non-c/c-related fields the usual way in the code-behind (e.g. int Total = PaymentTotal.Value;); but what I'm noting isn't so much about grabbing the data, it's that you have to handle it on Page_Load (or during some later point in the page life cycle), because the Submit button's onclick event is never actually fired, since the form is actually submitted using js and not the button.

So, being all literal and kinda answering the original question, you can't actually get the data in the button click event, w/o firing that event manually on postback (I'm surmising).

Hopefully save someone else some time figuring that out if they come here looking to make Stripe and .NET work together.

like image 39
GG2 Avatar answered Oct 17 '22 07:10

GG2