Calling a JS method from .NET

Viewed 49

I need help with calling a Javascript method from .NET c# backend.

From what I understand, I need to take paymentIntent from my backend and post it to client side, and call stripe.confirmCardPayment

This is how Javascript looks like:

    // Pass the failed PaymentIntent to your client from your server
stripe.confirmCardPayment(intent.client_secret, {
  payment_method: intent.last_payment_error.payment_method.id
}).then(function(result) {
  if (result.error) {
    // Show error to your customer
    console.log(result.error.message);
  } else {
    if (result.paymentIntent.status === 'succeeded') {
      // The payment is complete!
    }
  }
});

This is how my .NET c# code looks like:

try
{
  var service = new PaymentIntentService();
  var options = new PaymentIntentCreateOptions
  {
    Amount = 1099,
    Currency = "usd",
    Customer = "{{CUSTOMER_ID}}",
    PaymentMethod = "{{PAYMENT_METHOD_ID}}",
    Confirm = true,
    OffSession = true,
  };
  service.Create(options);
}
catch (StripeException e)
{
  switch (e.StripeError.ErrorType)
  {
    case "card_error":
      // Error code will be authentication_required if authentication is needed
      Console.WriteLine("Error code: " + e.StripeError.Code);
      var paymentIntentId = e.StripeError.PaymentIntent.Id;
      var service = new PaymentIntentService();
      var paymentIntent = service.Get(paymentIntentId);

      Console.WriteLine(paymentIntent.Id);
      break;
    default:
      break;
  }
}
1 Answers

This flow is covered in this guide to accepting a payment. On each of the server-side code examples you can select the ".NET" tab to see the code for your preferred server language.

You haven't shown how you're initially collecting payment details, so I assume you're using a payment method already attached to a known customer. YOu've also not shown how you're sending the payment data back to the client, but in your javascript snippets it looks like you have the entire intent object. I wouldn't recommend that, and suggest instead sending only what you need. Here, say, just a client_secret and payment_method_id to use in confirmCardPayment.

Related