#pez-stripeapps-verification
1 messages ยท Page 1 of 1 (latest)
[HttpPost]
[Route("healthCheck")]
public async Task<IActionResult> HealthCheck([FromBody] JsonElement requestBody)
{
try
{
var sigHeader = Request.Headers["Stripe-Signature"];
var appSecret = _configuration["Stripe:AppKey"];Console.WriteLine($"Received Stripe-Signature: {sigHeader}"); var payload = new { user_id = requestBody.GetProperty("user_id").GetString(), account_id = requestBody.GetProperty("account_id").GetString() }; Console.WriteLine($"Received Payload: {payload}"); var eventJson = payload.ToString(); Console.WriteLine($"Constructed Event JSON: {eventJson}"); Event stripeEvent = EventUtility.ConstructEvent(eventJson, sigHeader, appSecret); // Perform health check with the Stripe API using var response = await _httpClient.GetAsync("https://api.stripe.com/healthcheck"); response.EnsureSuccessStatusCode(); var jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Stripe API Response: {jsonResponse}"); return Ok(jsonResponse); } catch (StripeException ex) { Console.Error.WriteLine($"StripeException: {ex}"); // Handle Stripe-specific exceptions return BadRequest($"Stripe Error: {ex.Message}"); } catch (Exception ex) { Console.Error.WriteLine($"Exception: {ex}"); // Handle other exceptions return StatusCode(500, $"Internal server error: {ex.Message}"); }}
Hi ๐
what do you mean by "my app is showing it's down"?
I am testing by app by doing a service check in the backend. If my app is running ok the backend can successfully excecute this check if not it will say stripe is down in my app dashboard
The code appears to be breaking here Event stripeEvent = EventUtility.ConstructEvent(eventJson, sigHeader, appSecret);
That line is likely throwing an error that will inform you what is going wrong. I would recommend adding a try...catch block there to log the error
I have tried it but it is not working
I see you have a large chunk of your server-side code wrapped in try..catch but I am saying you shoudl have just your
Event stripeEvent = EventUtility.ConstructEvent(eventJson, sigHeader, appSecret);
line in it's own
[HttpPost]
[Route("healthCheck")]
public async Task<IActionResult> HealthCheck([FromBody] JsonElement requestBody)
{
StripeConfiguration.ApiKey = _configuration["Stripe:PrivateKey"];
var sigHeader = Request.Headers["Stripe-Signature"];
var appSecret = _configuration["Stripe:AppKey"];
Event stripeEvent;
Console.WriteLine($"Received Stripe-Signature: {sigHeader}");
var payload = new
{
user_id =requestBody.GetProperty("user_id").GetString(),
account_id =requestBody.GetProperty("account_id").GetString()
};
Console.WriteLine($"Received Payload: {payload}");
// Verify the payload and signature with the app secret
////StripeConfiguration.ApiKey = _configuration["AppKey"];
var eventJson = payload.ToString();
//Console.WriteLine($"Constructed Event JSON: {eventJson}");
try
{
stripeEvent = EventUtility.ConstructEvent(eventJson, sigHeader, appSecret);
}
catch (StripeException ex)
{
Console.Error.WriteLine($"StripeException: {ex}");
// Handle Stripe-specific exceptions
return BadRequest($"Stripe Error: {ex.Message}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"Exception: {ex}");
// Handle other exceptions
return StatusCode(500, $"Internal server error: {ex.Message}");
}
// Perform health check with the Stripe API
using var response = await _httpClient.GetAsync("https://api.stripe.com/healthcheck");
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Stripe API Response: {jsonResponse}");
return Ok(jsonResponse);
}
/////////////////////////I have redone the controller and if i comment the try & catch for stripeEvent = EventUtility.ConstructEvent(eventJson, sigHeader, appSecret); it works. So i am not sure if there is something wrong with the event constructor
please help me using my code above
๐ snufkin had to head out so I'm hopping in to help - how are you testing this currently? Are you using the CLI to trigger events, or arey ou doing something else?
yes its cli. Its stripe apps. This is the video i am using. The only difference is my backend is .net. I could not see documentation for serverside logic using dotnet for Stripe Apps. https://www.youtube.com/watch?v=-TwxnEmKPqo&t=537s
In this episode, you'll learn how to build a backend to securely perform your Stripe Apps business logic by using signature verification.
Presenter
Paul Asjes - Developer Advocate at Stripe - https://twitter.com/paul_asjes
Table of contents
00:00 Introduction
00:38 Code walkthrough
02:00 Build out backend code
03:30 Build out frontend ...
and have you confirmed that the eventJson and appSecret are correct?
In node the verify the signature in the tutorial using "stripe.webhooks.signature.verifyheader"
yes they are
Can you share what the exact string looks like when you log eventJson?
pez-stripeapps-verification
{t=170266****,v1=08e26ae93a650bbea895cca9bd8cf24de7b0ff778c3a0ce1e9fd3947795*****} this is sigheader
"absec_DMehd2rsAQZNT099************" this is appSeccret
"{ user_id = usr_H2qaPy5u, account_id = acct_1GaqrF*** }" this is eventJson
conveted to string from payload
That's likely the issue - I believe the eventJson needs to look more like
"{ "user_id":"usr_H***2qaPy5u", "account_id":"acct_1GaqrF**" }"
Instead of using .ToString() try using JsonSerializer.Serialize (see https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to)
how would i write it to look like this?
It's all in the link I sent you on Json serialization
now it looks like this eventJson "{"user_id":"usr_H9993Xd*******","account_id":"acct_1GaqrFLudV*******"}"
๐ And do you still get the same errors when you hit constructEvent?
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Stripe.net
StackTrace:
at Stripe.Infrastructure.EventConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Stripe.Infrastructure.JsonUtils.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Stripe.Infrastructure.JsonUtils.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Stripe.EventUtility.ParseEvent(String json, Boolean throwOnApiVersionMismatch)
at Stripe.EventUtility.ConstructEvent(String json, String stripeSignatureHeader, String secret, Int64 tolerance, Int64 utcNow, Boolean throwOnApiVersionMismatch)
at Stripe.EventUtility.ConstructEvent(String json, String stripeSignatureHeader, String secret, Int64 tolerance, Boolean throwOnApiVersionMismatch)
at JwtAuthAspNetWepAPI.Controllers.StripeController.<HealthCheck>d__4.MoveNext() in C:\Users\peter\source\repos\JwtAuthAspNetWepAPI\JwtAuthAspNetWepAPI\Controllers\StripeController.cs:line 120
This exception was originally thrown at this call stack:
[External Code]
JwtAuthAspNetWepAPI.Controllers.StripeController.HealthCheck(System.Text.Json.JsonElement) in StripeController.cs
This is the exception i am getting
I think I know what this - I believe ConstructEvent is meant specifically for webhook events and not for verifying signatures with stripe apps. Let me find what the correct one should be
Thank you
Found it! You'll want to use ValidateSignature instead (see https://github.com/stripe/stripe-dotnet/blob/master/src/Stripe.net/Services/Events/EventUtility.cs#L131)