Cloud Jasmin Common Use Cases
Common Use Cases
Common Use Cases
Back | List of Articles

How to create a sales order?

Last changed in 26/08/2022

An order represents a commitment by the customer to purchase a good or service. In this article, we show how to create an order using an API. The example presented was developed in C# for a console app.

Concepts

AccountKey and SubscriptionKey

First, you need to specify these two parameters, which are required by the Web API. In the following example, available in the Program.cs file, you are prompted to enter the:

// Get the account key
Console.Write("Insert Account Key: ");
string account = Console.ReadLine();

// Get the subscription key
Console.Write("Insert Subscription Key: ");
var subscription = Console.ReadLine();

OrdersController.AccountKey = account;
OrdersController.SubscriptionKey = subscription;

Access token

To access the Web API you also need the authentication token associated with the user and the Jasmin subscription. In the Program.cs file you can find an example of a request for obtaining the token, stored in the clientId and clientSecret constants, by calling the method GetAccessTokenAsync.

// Get the authorization access token
string accessToken = await GetAccessTokenAsync();
Console.WriteLine(accessToken != null ? "Authorization token found." : "Authorization token not found.");

HttpClient

To make calls to a REST Web API in C# you can use the following class: System.Net.Http.HttpClient
Such as in the example:

System.Net.Http.HttpClient

For example:

using (HttpClient client = new HttpClient())
{
    (…)
}

Configuration of the access token

Web API requests always require the previous access token. This must be included in the request headers.

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);

Building the order to be created

To create an order, there are 3 classes that represent Jasmin's WebAPI contracts:

  • Order
  • OrderLine
  • Price

Contracts can be found in the Jasmin or ROSE API's technical documentation, according to the product being integrated.

To invoke the method to create orders, we create the object that represents it:

public static async Task CreateOrderAsync()
{
    // Build the order that should be created
    Order order = new Order();
    try
    {
        order.Company = "Bocasuja";
        order.DocumentType = "ECL";
        order.DocumentDate = DateTime.UtcNow;
        order.CustomerId = "0002";
        order.Currency = "EUR";
        order.Lines = new List
            {
                new OrderLine
                {
                    ItemId = "0002",
                    Quantity = 1,
                    Type = 1,
                    Price = new Price()
                    {
                        Value = 50,
                        Currency = "€"
                    }
                    (...)
                }
              };
    }
}

Building and running the request

Now the Web API call can be run from an HTTP Client. Note that the verb used is POST and the response is returned in an IDisposable HttpResponseMessage type.

// Build the request

string request = "sales/orders";
string resourceLocation = string.Format("{0}/api/{1}/{2}/{3}/", Constants.baseAppUrl, AccountKey, SubscriptionKey, request);

client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);

HttpRequestMessage postOrderMessage = new HttpRequestMessage(HttpMethod.Post, resourceLocation);

string invoiceRequest = JsonConvert.SerializeObject(order);

postOrderMessage.Content = new StringContent(invoiceRequest, Encoding.UTF8, "application/json");

// Send

using (HttpResponseMessage responseContent = await client.SendAsync(postOrderMessage))
{
    (…)
}

Response handling

The endpoint can return two types of responses: success or error. In case of success, a success message and the information of the created order will be returned. In the event of an error, the response will include the respective error message.

// Build the request
// Get the response

if (responseContent.IsSuccessStatusCode)
{
    string result = await ((StreamContent)responseContent.Content).ReadAsStringAsync();
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine(string.Concat("Order created: ", result));
}
else
{
    Console.WriteLine(string.Concat("Failed. ", responseContent.ToString()));
    string result = await ((StreamContent)responseContent.Content).ReadAsStringAsync();
    Console.WriteLine(string.Concat("Content: ", result));

    throw new Exception("Unable to create the order.");

}

Creating a sales order is that simple.

Bookmark or share this article
Esta página foi útil?
Obrigado pelo seu voto.

login para deixar a sua opinião.

Obrigado pelo seu feedback. Iremos analisá-lo para continuarmos a melhorar!
Artigos Relacionados
Como obter uma lista de encomendas? Como criar uma encomenda de vendas? Como obter o pdf de um documento? Como obter uma lista de encomendas? Como criar uma encomenda de vendas?