#guanwei22

1 messages · Page 1 of 1 (latest)

sacred flintBOT
arctic stone
#

Can you share the request ID (req_xxx) of the error? Here’s how you can find it: https://support.stripe.com/questions/finding-the-id-for-an-api-request or from the response of your request

heady yacht
#

it is a code problem on my side however, im unable to fix it. I do not have the request id as the post to stripe could not even work\

arctic stone
#

Can you share the code that you tried to make a request to Stripe?

heady yacht
#

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

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

<h1>Shopping Cart</h1>

<div class="clothe">
    <div class="clothe-name">Shirt 1</div>
    <div class="clothe-price">8</div>
    <div class="clothe-image">
        <asp:Image ID="imgProduct" runat="server" ImageUrl="~/Content/Images/shirt1.jpg" />
    </div>
</div>


<!-- Cart Total -->
<p>Total: $45</p>

<!-- Checkout Button -->
<!-- Checkout Button -->
<button id="checkoutAjaxButton" ServicePath="Default.aspx" onclick="checkoutWithAjax()">Check Out</button>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://js.stripe.com/v3/"></script>

<script>
    function checkoutWithAjax() {
        // Collect cart data from the HTML
        var cartData = [];
        $(".clothe").each(function () {
            var item = {
                name: $(this).find(".clothe-name").text(),
                price: parseFloat($(this).find(".clothe-price").text()),
                imageUrl: $(this).find(".clothe-image").attr("src"),
            };
            cartData.push(item);
        });
#

// Calculate the total price
var cartTotal = cartData.reduce(function (acc, item) {
return acc + item.price;
}, 0);

        // Send the data to the server asynchronously
        $.ajax({
            type: "POST",
            url: "Default.aspx/HandleCheckout", // This should match the method name in your code-behind
            data: JSON.stringify(cartData), // Convert your data to JSON
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                // Handle the response from the server, e.g., redirect to Stripe
                window.location.href = response;
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log("Error: " + errorThrown);
            }
        });
    }
</script>

</asp:Content>

#

this is my default.aspx folder

#

using System;
using System.IO; // For working with files
using System.Configuration; // For reading configuration from web.config
using Stripe;
using Stripe.Checkout;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Secret
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    }

    public class CartItem
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public string ImageUrl { get; set; }
    }

    [System.Web.Services.WebMethod]
    public static string HandleCheckout(List<CartItem> cartItems)
    {
        try
        {
            // Add the CORS headers to allow cross-origin requests
            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
#

// Initialize the Stripe API with your secret key
StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["StripeSecretKey"];

            // Create a Stripe Checkout session
            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List<string>
                {
                    "card",
                },
                Mode = "payment",
                LineItems = new List<SessionLineItemOptions>()
            };

            foreach (var item in cartItems)
            {
                options.LineItems.Add(new SessionLineItemOptions
                {
                    PriceData = new SessionLineItemPriceDataOptions
                    {
                        Currency = "sgd",
                        ProductData = new SessionLineItemPriceDataProductDataOptions
                        {
                            Name = item.Name,
                            Images = new List<string> { item.ImageUrl },
                        },
                        UnitAmount = (long)item.Price * 100, // Price in cents
                    },
                    Quantity = 1,
                });
            }

            options.SuccessUrl = "https://localhost:44379/Default";
            options.CancelUrl = "https://localhost:44379/Default";

            var service = new SessionService();
            var session = service.Create(options);

            return session.Url;
        }
        catch (Exception ex)
        {
            // Log the error using the LogError method
            LogError(ex);
            Console.WriteLine("Error occurred: " + ex.Message);

            // Return an error message or code that indicates a failure
            return "Error: An unexpected error occurred during checkout.";
        }
    }
#

// Function to log errors to a text file
private static void LogError(Exception ex)
{
string logFilePath = HttpContext.Current.Server.MapPath("~/App_Data/ErrorLog.txt");

        using (StreamWriter sw = System.IO.File.AppendText(logFilePath))
        {
            sw.WriteLine($"Error at {DateTime.Now}:");
            sw.WriteLine($"Message: {ex.Message}");
            sw.WriteLine($"Stack Trace: {ex.StackTrace}");
            sw.WriteLine(new string('-', 40));
        }
    }
}

}

#

this is my default.aspx.cs folder

#

im sorry if it is abit messy

#

if you need the whole sln folder i can send it to you

arctic stone
#

Which part of the code returned the error?

#

Is it from var session = service.Create(options);, or client side?

heady yacht
#

i think is the var session create, because this is what i see in my console

arctic stone
#

The error is thrown when your client attempts to make a request to your server. 401 error is thrown from your server, not Stripe. I'd recommend checking why your server threw such an error.

401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401. It's likely that your server doesn't authorise your own request from client.

heady yacht
#

i see thank you so much