#zee_code

1 messages ¡ Page 1 of 1 (latest)

misty vergeBOT
#

👋 Welcome to your new thread!

⏲️ We'll be here soon! Typically we respond in a few minutes, but sometimes we might take a bit longer if the server is busy or if you have a particularly tricky question.

⏱️ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can always start a new thread if you have another question.

🔗 This thread will always be available, even after it's closed. You can find it again using Discord's search, or you can save this link: https://discord.com/channels/841573134531821608/1303881890612121710

📝 Have more to share? Add more details, code, screenshots, videos, etc. below.

weary inlet
#
        private async void ProceedToPaymentButton_Click(object sender, RoutedEventArgs e)
        {
            // Replace with your API's base address and endpoint
            string apiUrl = "https://localhost:7186/api/payment/create-checkout-session";

            // Use HttpClient to call the API
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // Make a POST request to the API
                    HttpResponseMessage response = await client.PostAsync(apiUrl, null);

                    // Check if the response is successful
                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        var jsonResponse = JObject.Parse(responseContent);

                        // Extract the sessionId
                        string sessionId = jsonResponse["sessionId"].ToString();

                        // Redirect to Stripe Checkout
                        string checkoutUrl = $"https://checkout.stripe.com/pay/{sessionId}";
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = checkoutUrl,
                            UseShellExecute = true
                        });
                    }
                    else
                    {
                        MessageBox.Show("Failed to create a checkout session.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"An error occurred: {ex.Message}");
                }
            }
        }


#

    [Route("api/[controller]")]
    [ApiController]
    public class PaymentController : ControllerBase
    {
        private readonly PaymentService _paymentService;
        private readonly ApplicationDbContext _context;

        public PaymentController(PaymentService paymentService)
        {
            _paymentService = paymentService;
            
        }

        [HttpPost("create-checkout-session")]
        public ActionResult CreateCheckoutSession()
        {
            var session = _paymentService.CreateCheckoutSession(
               "https://localhost:7186/payment/success?sessionId={CHECKOUT_SESSION_ID}",
               "https://localhost:7186/payment/cancel?sessionId={CHECKOUT_SESSION_ID}", "20"

            );


            return Ok(new { sessionId = session.Id });
        }

        [HttpGet("success")]
        public async Task<IActionResult> Success(string sessionId)
        {
            /*
            var paymentRecord = await _context.PaymentRecords.FirstOrDefaultAsync(p => p.StripeSessionId == sessionId);
            if (paymentRecord != null)
            {
                paymentRecord.Status = "Success";
                await _context.SaveChangesAsync();
            }
            */

            // Redirect to a success page or return success response
            return Ok("Payment successful.");
        }

        [HttpGet("cancel")]
        public async Task<IActionResult> Cancel(string sessionId)
        {
            /*
            var paymentRecord = await _context.PaymentRecords.FirstOrDefaultAsync(p => p.StripeSessionId == sessionId);
            if (paymentRecord != null)
            {
                paymentRecord.Status = "Cancelled";
                await _context.SaveChangesAsync();
            }
            */

            // Redirect to a cancel page or return cancel response
            return Ok("Payment cancelled.");
        }
    }
dense root
#

Hey @weary inlet Can you share the exact error you are getting or what's not working exactly?

weary inlet
#

yep will do thx

#

so it takes me to the page but it says this

#

The page you were looking for could not be found. Please check the URL or contact the merchant.

#

anything else you would like to see?

dense root
#
                        string checkoutUrl = $"https://checkout.stripe.com/pay/{sessionId}";
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = checkoutUrl,
                            UseShellExecute = true
                        });```
#

why are you doing this? You seem to manually construct the URL which is forbidden

#

I don't understand how this even works locally but that is likely part of your problem

weary inlet
#

oh well I was having trouble doing it by myself so was looking for code online and I found this

dense root
#

When you create the Checkout Session server-side, don't return return Ok(new { sessionId = session.Id });
Instead return the real URL that would be in session.Url

weary inlet
dense root
#

yeah I mean a lot of the approach is incorrect and doesn't match what we recommend at all but I can't make you rewrite the entire thing

#

So return the URL to your client and then client-side redirect to that URL. Do not construct the URL yourself

weary inlet
dense root
#

What exactly did you change in your code both client-side and server-side?

weary inlet
dense root
#

Okay so that will never work!

#

Right now your code gets the Session id cs_test_123 and then client-side constructs a custom URL that is broken. You need to change that logic entirely

  1. Server-side, return the real URL we calculated already
  2. Client-side, get that URL from your response and redirect to that URL

This means changing both your server-side and client-side code.

#

(also no need to reply to every message, just type in the box, I'll see it)

weary inlet
#

alright I am looking at the documentation to get a better understanding and try again thx

dense root
#

it's really not in the documentation because what you are doing is not the common way

misty vergeBOT
dense root
#

But really the change should be straightforward. Return the URL from the server and client-side get that URL and redirect there instead of making your own URL