Портирование Xero API Google Apps Код скрипта в C# не работаетC#

Место общения программистов C#
Ответить
Anonymous
 Портирование Xero API Google Apps Код скрипта в C# не работает

Сообщение Anonymous »

Я новичок в этом. Я пытаюсь взаимодействовать с API -интерфейсом Xero (первоначально идентификация) в C# без использования SDK. Я сделал это успешно в скрипте приложений Google, используя urlfetchapp.fetch , но теперь вот мой код C# в настоящее время ...
private static async Task XeroConnect()
{
var valueBytes = Encoding.UTF8.GetBytes(xeroClientId + ":" + xeroSecretKey);

var connectParams = new {
method = "post",
headers = new {
Authorization = "Basic " + Convert.ToBase64String(valueBytes)
},
payload = new {
grant_type = "client_credentials",
scope = "accounting.transactions accounting.contacts"
}
};

using (var client = new HttpClient())
{
using (var content = new StringContent(JsonConvert.SerializeObject(connectParams), Encoding.UTF8, "application/json"))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

HttpResponseMessage response = await client.PostAsync(xeroConnectAPI, content);
response.EnsureSuccessStatusCode();
dynamic responseValues = JsonConvert.DeserializeObject(response.Content.ToString());

if (responseValues.HasErrors || responseValues.HasValidationErrors)
{
throw new Exception(response.Content.ToString());
}

return responseValues.access_token;
}
}
}
< /code>
Просто получите ошибку 400 без дополнительной информации. Я пробовал много разных способов, используя PostAsjsonAsync и т. Д., Но каждый раз один ответ каждый раз.
function xeroConnect() {
let step = 0;
try
{
const constants = globalConstants();
step = 10;
const params = {
method: "post",
headers: {Authorization: "Basic " + Utilities.base64Encode(constants.xeroClientId + ":" + constants.xeroSecretKey)},
payload: {
"grant_type": "client_credentials",
"scope": "accounting.transactions accounting.contacts",
}
};
step = 20;
let response = UrlFetchApp.fetch(constants.xeroConnectAPI, params);
step = 25;
if (!response) { throw "No response"; }
step = 30;
let responseValues = JSON.parse(response.getContentText());
step = 40;
if (responseValues.HasErrors || responseValues.HasValidationErrors)
{
throw(response.getContentText());
}
step = 50;
return responseValues.access_token;
}
catch (error)
{
let errorString = "ERROR: xeroConnect; error=" + JSON.stringify(error) + ";step=" + step;
Logger.log(errorString);
return errorString;
}
}
< /code>
Вот мой пересмотренный код ... < /p>
private static async Task XeroConnect()
{
var valueBytes = Encoding.UTF8.GetBytes(xeroClientId + ":" + xeroSecretKey);
var payload = new
{
grant_type = "client_credentials",
scope = "accounting.transactions accounting.contacts"
};

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(valueBytes));
HttpResponseMessage response = await client.PostAsJsonAsync(xeroConnectAPI, payload);
//response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
dynamic responseValues = JsonConvert.DeserializeObject(response.Content.ToString());

if (responseValues.HasErrors || responseValues.HasValidationErrors)
{
throw new Exception(response.Content.ToString());
}

return responseValues.access_token;
}
}
< /code>
Вот рабочий код ... < /p>
private static async Task XeroConnect()
{
var valueBytes = Encoding.UTF8.GetBytes(xeroClientId + ":" + xeroSecretKey);

using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(300);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(valueBytes));

var content = new MultipartFormDataContent();
content.Add(new StringContent("client_credentials"), "grant_type");
content.Add(new StringContent("accounting.transactions accounting.contacts"), "scope");

var header = new ContentDispositionHeaderValue("form-data");
content.Headers.ContentDisposition = header;

var response = await client.PostAsync(xeroConnectAPI, content);

response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
dynamic responseValues = JsonConvert.DeserializeObject(responseContent);
return responseValues.access_token;
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... ot-working
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»