ASP.Net Core parse Stripe Webhook JSON Response - c#

I am working with Stripe/Stripe.net Webhooks in my ASP.Net Core app. I am trying to map an object where I can use the properties returned from the Webhook JSON response and save various properties into my database. Using Postman, I am able to receive the sample JSON that I got from Stripe test webhooks in my Controller method and parse the JSON using
var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
Event stripeEvent = EventUtility.ParseEvent(json);
which returns:
stripeEvent = {<Stripe.Event#2269235 id=evt_00000000000000> JSON: {"id": "evt_00000000000000", "object": "event", "account": null, "api_version": "2020-03-02", "created": 1326853478, "data": { "object": { "id": "ch_00000000000000", "...
I am needing to map the JSON from the RawObject ChildrenTokens into a model but I'm not able to access the ChildrenTokens through C#. Is there any way to be able to map these properties?

The trick here is to cast the stripeEvent.Data.Object as the specific class that the underlying event data should represent. Typically, you'll have a switch or if statement checking the stripeEvent.Type.
For instance, if the type of the event is payment_intent.succeeded, then the underlying data would be a PaymentIntent and you might have the following code to check the type, then cast to that type.
if (stripeEvent.Type == Events.PaymentIntentSucceeded)
{
var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
}
From there, you can interact with the paymentIntent and it's related properties.

Related

Dynamics CRM C# Plugin - First time with API

While I've been developing in Dynamics for awhile, I have never had to do an external call to an API before.
I'm not sure where to start. Any help in pointing me in the right direction would be very helpful.
The Api in question is located here:
http://apidocs.assess.com/
There are examples within there that show what needs to get passed to the url (https://app.fasttestweb.com/FastTest/api/swagger.json)
But in all honesty, this is my first attempt at this and I'm overwhelmed with the information I've been finding, and having trouble parsing through what needs to be done for this.
Step 1, of course is to generate an auth token from the site.
This needs to be passed in this formation (I assume that is JSON).
But I'm having trouble figuring out how to even do that part, or what the code should even look like. If anyone has an example of something they've done, or can point me to a link/video that walks through this, that would be awesome.
Note, I do have Newtonsoft.Json installed in Visual Studio, but I'm having trouble finding good examples on how to actually pass the information back and forth.
Thank you in advance.
How to call an API in rest is a really common practice as a developer since this is common practice to expose data, i highly recommend that you read up on the subject, there are alot of good resources out there, this site is one and youtube is another, did a quick search and found alot about it: https://www.youtube.com/results?search_query=intro+to+rest+c%23
To the problem at hand:
The swagger documentation tells you all you need to know to call the service your after,
Take the auth service for example, first of we need to know which method the service uses, in this case it is post.
Now we need to know which address we can call the service. Specified in the docs as: https://app.fasttestweb.com/FastTest/api/auth/simple
What are we sending:
{
"username": "string",
"pwd": "string",
"apiKey": "string",
"timeSent": 0,
"tokenTTL": 0
}
if you switch to model you can see the description of the parameters. You can even test this out directly in the page by editing the editable box with the values you were given and pressing "try it out!" in the bottom of the endpoint specification.
What response are we getting:
{
"apiToken": "string",
"timeGenerated": 0,
"ttl": 0
}
To call it, there are many ways to do this, i like to make separate objects/dto's of what im sending and recieving and then serialize/deserialize them from and to that object. Since you already have json.net here is how you do serialize.
You can specify the specific json names so it matches with the schema with an attribute
or define a strategy.
When you get the json back from the service you will have to deserialize it.
So your body obj would look like this for example
public class AuthBody
{
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("pwd")]
public string Password { get; set; }
[JsonProperty("apiKey")]
public string ApiKey { get; set; }
[JsonProperty("timeSent")]
public int TimeSent { get; set; }
[JsonProperty("tokenTTL")]
public int TokenTimeToLive { get; set; }
}
Just setup the response in similar fashion.
I like to use a lib called RestSharp to call rest services, its available on nuget.
Here is a very basic code example (not tested):
var body = new AuthBody()
{
UserName = "value",
Password = "value",
ApiKey = "value",
TimeSent = 123,
TokenTimeToLive = 10000
};
var json = JsonConvert.SerializeObject(body);
var client = new RestClient("https://app.fasttestweb.com/FastTest/api");
var request = new RestRequest("auth/simple", Method.POST, DataFormat.Json);
request.AddParameter("application/json", json, ParameterType.RequestBody);
var jsonResponse = client.Execute(request);
AuthResponse authResponse = JsonConvert.DeserializeObject<AuthResponse>(jsonResponse.Content);
You can also set the default serializer of restsharp to json.net if you want, then you can set the body with addJsonBody instead of the parameter and you dont have to serialize your object yourself, more info is available on RestSharp.
if you dont want to use RestSharp, the normal client is called HttpClient instead of RestClient, if you want to google it.
Hope it helps.

How to properly send JSON metadata value to Woocommerce API

My c# application creates products using the Woocommerce.NET NuGet package.
I'm sending metadata with the key: woodmart_variation_gallery_data and value: {"5543":"5519"}
But the plugin that uses this metadata can't use the value, however, when checking the metadata in the database, it's exactly the same as I sent it.
But WordPress should serialize it unless I'm sending the JSON the wrong way.
For example, I need to send this JSON to Woocommerce:
{"5543":"5519"}
Here's how I would to this using code:
Product product = new Product();
//add some stuff like price
product.meta_data = new List<ProductMeta>()
{
new ProductMeta()
{
key = "woodmart_variation_gallery_data",
value = "{\"5543\":\"5519\"}"
}
}
await wcObject.Products.Add(product);
When this run, what I'm expecting to see in the database postmeta is serialized code:
a:1:{i:5543;s:4:"5519";}
But what I see is {"5543":"5519"} It's supposed to be serialized by wordpress/woocommerce, but it's not?
You can use Sharp Serialization Library

Microsoft Graph API doesn't return the properties I need

Trying to do a simple query using ms graph API to get the user's aboutMe property:
string filter = #"
startswith(displayName,'Bassie')
";
var users = await graphClient.Users
.Request()
.Filter(filter)
.Select("aboutMe")
.GetAsync();
But I just keep getting
{Code: NotImplementedMessage: This operation target is not yet supported. Inner error}
Where the InnerError doesn't contain any useful information.
It works fine when I do the same with mail.
Why is this? I'm fairly sure I have retrieved aboutMe section using graph API before, but I don't remember exaclty how...
When trying it with Graph Explorer
https://graph.microsoft.com/v1.0/users?$select('AboutMe')
It returns objects like this
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",
"#odata.nextLink": "https://graph.microsoft.com/v1.0/users?=%24select(%27AboutMe%27)&$skiptoken=X%2744537074020001000000273A24504A424632302D344D474E324C34484551384E40776F726C6579706172736F6E732E636F6D29557365725F62363964646464302D353865332D343537332D386639332D363033333731386231336237B900000000000000000000%27",
"value": [
{
"id": "d6a2b540-bd56-420f-bb46-bb46d6a2b540",
"businessPhones": [],
"displayName": "54-3-24",
"givenName": "user",
"jobTitle": null,
"mail": "user#domain.com",
"mobilePhone": null,
"officeLocation": null,
"preferredLanguage": null,
"surname": "surname",
"userPrincipalName": "username#domain.com"
}
What does this mean? How am I supposed to retrieve the properties that I need? And if only some are available, is there a reference for this? I don't want to have to test out every single property before I know which are available..
Unfortunately aboutMe property of user entity could not be retrieved for a collection of users, only for a single user (entity) it is supported to retrieve this property like this:
/beta/users/me?$select=aboutMe
Refer this thread that lists all the properties that could not be
retrieved per user collection.
The query:
https://graph.microsoft.com/v1.0/users?$select('AboutMe')
is invalid and in your case select query option expression is simply ignored since it is provided incorrectly, here is the example how to specify select query option (follow this article for a more details):
/beta/users?$select=email,displayName
/v1.0/users?$filter=startswith(displayName,'Bassie')&$select('AboutMe')
will execute properly but, the c# sdk will resolve your Queries to the following format
/v1.0/users?$filter=startswith(displayName,'Bassie')&$select=AboutMe
"BaseRequest.cs, ~line 310"
However select
/v1.0/users?$select=AboutMe
seems to throw the NotImplementedException.
Not sure if this is a bug, but i would recommend you to submit a bug report

What is the easiest way to convert JSON into BSON in .net world

I just started working on MongoDB. From my JavaScript client I am sending a JSON string to ASP.NET WEB API project. Is it possible to use this JSON string directly and save it into MongoDB? I also want to know whether this approach make sense ?
I am thinking of passing the JSON from client and on the server side read the string as
[System.Web.Mvc.HttpPost]
public dynamic SaveData([FromBody] string data)
{
System.Web.HttpContext.Current.Request.Form[0]
return null;
}
Try this:
string json = "...";
BsonDocument.Parse(json);
Try this!
string json = "{ 'foo' : 'bar' }";
MongoDB.Bson.BsonDocument document
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
Yes you can.
but keep in mind that sending client side data without check the user data can lead to security issues (Never Trust The User's Input)
You can do this by using the insert Collection Methods.
keep in mind that if you will not have _id in your json Mongodb will produced it for you.
for example i will create a document in the "test" Collection like that
db.test.insert(
{
"foo":"bar"
}
);
and the result can be something like that
{
"_id" : ObjectId("546c9be08e66b0571a5e3965"),
"foo" : "bar"
}

asp.net call url to get information

I'm trying to implement a domain search in our website, but I have no clue how... the WHOIS service I registered by, gave me an API key to use... When I use the following address in my browser's url,
http://api.robowhois.com/v1/availability/example.com
a login box appears, asking me for my username and password, when I type in my username and password which is the key they gave me, a page appears with the following
{
"response": {
"available": false
}
}
I'm sorry to say, but I've been searching for weeks on how to solve this but at the end my last resort was to turn to stack overflow... can someone please help, is there a way on how to use and call the url and use the info?
You already got the information you need. It responds with a JSON object saying it's not available.
To retrieve the information as you wish, you can use Jquery, just put your URL in a function as in the examples and get data.response.available value and assign it to your textbox etc. For more information how to make JSON calls and parse them, check out this documentation in Jquery website.
RoboWhois is a web service that provides an API suite to access WHOIS
records and domain related information with a unified, consistent
interface. Using RoboWhois API you can retrieve WHOIS details parsed
as convenient JSON structure.
In order to check the availability of a given domain you have to send a http get request to the robowhois api http://api.robowhois.com/v1/availability/example.com
The server does answer the request by sending http response containing json which looks like this:
{
"response": {
"available": false
}
}
which means the domain is no longer available.
In order to use the information contained in the json response you should deserialize the json object to a c# object. You can do this for example with the json.net library.
Here is a small example from the documentation on how to use json.net to deserialize a json:
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

Categories

Resources