Skip to content

Commit

Permalink
1.0.1 Add descriptions of methods
Browse files Browse the repository at this point in the history
  • Loading branch information
yawaflua committed Mar 10, 2024
1 parent 9258cb8 commit a2b4865
Show file tree
Hide file tree
Showing 8 changed files with 398 additions and 25 deletions.
16 changes: 15 additions & 1 deletion Lava.NET.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,26 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.0</Version>
<Version>1.0.1</Version>
<GenerateDocumentationFile>False</GenerateDocumentationFile>
<Authors>yawaflua</Authors>
<Company>yawaflua</Company>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/yawaflua/Lava.NET</RepositoryUrl>
<NeutralLanguage>ru</NeutralLanguage>
</PropertyGroup>


<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>


<ItemGroup>
<None Update="README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>

</Project>
92 changes: 83 additions & 9 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,54 +13,123 @@ namespace Lava.NET
/// </summary>
/// <param name="token">Токен от Lava.ru</param>
/// <param name="type">Тип вашего аккаунта</param>
public class ILavaAPI(string token, LavaType type)
public class LavaAPI(string token, LavaType type)
{
internal readonly HttpClient _httpClient = new HttpClient()
{
BaseAddress = new("https://api.lava.ru/")
};
internal async Task<string> SendRequest(string path, LavaType? neededType, HttpMethod method, string? body = null)
/// <summary>
/// Отправка запроса на сервер
/// </summary>
/// <param name="path">path метода</param>
/// <param name="neededType">требуемый тип аккаунта</param>
/// <param name="method">Метод для отправки запроса</param>
/// <param name="body">string body</param>
/// <returns>string от сервера</returns>
/// <exception cref="Exceptions.TypeException">Несоответсвие типа аккаунта и требуемого типа</exception>
internal virtual async Task<string> SendRequest(string path, LavaType? neededType, HttpMethod method, string? body = null)
{
if (neededType != LavaType.any && neededType != type) throw new Exceptions.TypeException("Your Lava.ru account type is not equals needed type");
_httpClient.DefaultRequestHeaders.Authorization = new("", token);
using (var message = new HttpRequestMessage(method, path))
using (var message = new HttpRequestMessage(method, _httpClient.BaseAddress + path))
{

message.Content = body == null ? new StringContent(body.ToString()) : null;
var req = await _httpClient.SendAsync(message);
return await req.Content.ReadAsStringAsync();
}
}

public async Task<PaymentResponse?> CreatePaymentAsync(PaymentRequest data)
/// <summary>
/// Создание ссылки на оплату (Выставление счета)
/// </summary>
/// <param name="data"> Данные, передаваемые в запрос. Смотреть АПИ</param>
/// <returns>Ответ от сервера или null</returns>
public virtual async Task<PaymentResponse?> CreatePaymentAsync(PaymentRequest data)
=> JsonConvert.DeserializeObject<PaymentResponse>(await SendRequest("invoice/create", LavaType.any, HttpMethod.Post, data.ToString()));
public async Task<PaymentInfo?> GetPaymentInfoAsync(string id)
/// <summary>
/// Получение информации о выставленном счете, в т.ч. о том, оплачен ли счет
/// </summary>
/// <param name="id">айди выставленного счета</param>
/// <returns>Ответ от сервера или null</returns>
public virtual async Task<PaymentInfo?> GetPaymentInfoAsync(string id)
=> JsonConvert.DeserializeObject<PaymentInfo>(await SendRequest("invoice/info", LavaType.any, HttpMethod.Post, id));
/// <summary>
/// Установка webhook для получения информации о пополнениях, оплате выставленных счетов и т.д.
/// </summary>
/// <param name="url">HTTPS url до вашего бекенда, куда должен приходить вебхук</param>
/// <returns></returns>
public async Task SetWebhookUrl(string url)
=> await SendRequest("invoice/set-webhook", LavaType.any, HttpMethod.Post, url);
/// <summary>
/// Проверка токена
/// </summary>
/// <returns></returns>
public async Task<bool> pingAsync()
=> JsonNode.Parse(await SendRequest("test/ping", LavaType.any, HttpMethod.Get))?["status"]?.ToString().Equals(true) ?? false;
}
public class PublicLavaAPI : ILavaAPI
public sealed class PublicLavaAPI : LavaAPI
{
// Для обычных юзеров + общедоступное
/// <summary>
/// Для обычных юзеров, т.е. вкладка Кошелек
/// </summary>
/// <param name="token">токен от вашего аккаунта</param>
public PublicLavaAPI(string token) : base(token, LavaType.wallet) { }

/// <summary>
/// Получение кошельков на вашем аккаунте
/// </summary>
/// <returns>Список из кошельков или null</returns>
public async Task<Wallet[]?> getWallets()
=> JsonConvert.DeserializeObject<Wallet[]>(await SendRequest("wallet/list", LavaType.wallet, HttpMethod.Get));
/// <summary>
/// Cоздние заявки на вывод
/// </summary>
/// <param name="withdraw">данные, передаваемые в запрос</param>
/// <returns>Стандартный ответ от сервера или null</returns>
public async Task<DefaultResponse?> MakeWithdraw(Withdraw withdraw)
=> JsonConvert.DeserializeObject<DefaultResponse>(await SendRequest("withdraw/create", LavaType.wallet, HttpMethod.Post, withdraw.ToString()));
/// <summary>
/// Информация о выводе
/// </summary>
/// <param name="id">Id заявки</param>
/// <returns>Информация о выводе</returns>
public async Task<WithdrawInfo?> InfoWithdrawAsync(string id)
=> JsonConvert.DeserializeObject<WithdrawInfo>(await SendRequest("withdraw/info", LavaType.wallet, HttpMethod.Post, id));
/// <summary>
/// Создание перевода
/// </summary>
/// <param name="data">Данные, передаваемые в запрос</param>
/// <returns>Стандартный ответ от сервера или null</returns>
public async Task<DefaultResponse?> MakeTransfer(Transfer data)
=> JsonConvert.DeserializeObject<DefaultResponse>(await SendRequest("transfer/create", LavaType.wallet, HttpMethod.Post, data.ToString()));
/// <summary>
/// Получение информации о переводе
/// </summary>
/// <param name="id">Id перевода</param>
/// <returns>Данные о переводе</returns>
public async Task<TransferData?> GetTransferDataAsync(string id)
=> JsonConvert.DeserializeObject<TransferData>(await SendRequest("transfer/info", LavaType.wallet, HttpMethod.Post, id));
/// <summary>
/// Получение всех транзакций
/// </summary>
/// <param name="transaction">Необ. данные для настройки вывода</param>
/// <returns>Все транзакции</returns>
public async Task<Transaction[]?> GetTransactionsAsync(TransactionParam? transaction = null)
=> JsonConvert.DeserializeObject<Transaction[]>(await SendRequest("transactions/list", LavaType.wallet, HttpMethod.Post, transaction?.ToString()));
/// <summary>
/// Получение банков, подключенных к СБП
/// </summary>
/// <returns>Список банков</returns>
public async Task<SBPBanks?> GetSBPBanksAsync()
=> JsonConvert.DeserializeObject<SBPBanks>(await SendRequest("withdraw/get-sbp-bank-list", LavaType.wallet, HttpMethod.Post));
}
public class BusinessLavaAPI(string token) : ILavaAPI(token, LavaType.business)
/// <summary>
/// В РАЗРАБОТКЕ
/// Часть lava.ru API, которая работает с бизнесом. Вкладка "Бизнес" dev.lava.ru
/// </summary>
/// <param name="token">Токен вашего аккаунта</param>
public sealed class BusinessLavaAPI(string token) : LavaAPI(token, LavaType.business)
{
internal async Task<string> SendRequest(string path, LavaType? neededType = LavaType.business, HttpMethod? method = null, string? body = null, bool isSpecial = true)
{
Expand All @@ -79,6 +148,11 @@ internal async Task<string> SendRequest(string path, LavaType? neededType = Lava
return await req.Content.ReadAsStringAsync();
}
}
/// <summary>
/// Создание вывода
/// </summary>
/// <param name="request">Данные, передаваемые в запрос</param>
/// <returns></returns>
public async Task<PayoffResponse?> CreatePayoffAsync(PayoffRequest request)
=> JsonConvert.DeserializeObject<PayoffResponse>(await SendRequest("business/payoff/create", body: request.ToString()));
public async Task<PayoffDataResponse?> GetPayoffDataAsync(PayoffDataRequest request)
Expand Down
80 changes: 79 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,79 @@
# Lava.NET
# Lava.NET
Áèáëèîòåêà äëÿ ðàáîòû ñ API ñàéòà lava.ru.
Ïîêà ÷òî âåäåòñÿ ðàáîòà íàä áèçíåñ-÷àñòüþ API

Ñîâåòóåòñÿ ïåðåä èñïîëüçîâàíèåì ïðî÷èòàòü [API ñàéòà lava.ru](https://dev.lava.ru/)
# Ïðèìåðû
## Óñòàíîâêà áèáèëîòåêè
```bash
dotnet add package Lava.NET
```
### È èñïîëüçëîâàíèå â ïðîåêòå
```cs
using Lava.NET;
public class Program
{
public static async Task Main(string[] args)
{
var publicLavaApi = new PublicLavaAPI("[ Âàø òîêåí ]");
// ... Âàøà ëîãèêà
}
}
```
## Ïðèìåð èñïîëüçîâàíèÿ ñ ASP.NET ïðèëîæåíèåì:
```cs
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
var publicLavaApi = new PublicLavaAPI("[ Âàø òîêåí ]");
services.AddControllers();
services

.AddSwaggerGen();

services
// ...Íàñòðîéêà ïðèëîæåíèÿ
.AddSingleton(publicLavaAPI);
}
```

## Ïðèìåð ðàáîòû ñ âåáõóêîì(.NET 8):
```cs
// PaymentController.cs
[ApiController]
[Route("/payment/")]
public class PaymentController(PublicLavaAPI lavaAPI) : ControllerBase
{


[HttpPost("lava")]
public async Task<IActionResult> ValidatePaymentLava([FromBody] WebhookResponse webhookResponse)
{
// Âàøà ëîãèêà
return Ok(); // Îáÿçàòåëüíî îòâå÷àòü 200, èíà÷å âåáõóêè áóäóò ïðèõîäèòü ñíîâà è ñíîâà, äî 15 ðàç.
}
}
```

## Ñîçäàíèå ññûëêè íà îïëàòó:
```cs
var publicLavaApi = new PublicLavaAPI("[Âàø òîêåí]");
var createdPayment = await publicLavaApi.CreatePaymentAsync(
new (){
comment = "Îïëàòà ïîêóïêè â Telegram áîòå", // Íåîá.
hook_url = $"https://example.com/api/payment/lava", // Íåîá.
merchant_id = "AskMeAboutBOT", // Íåîá.
merchant_name = "AskMeAboutBOT", // Íåîá.
custom_fields = $"Ëþáûå êàñòîìíûå äàííûå, ïåðåäàâàåìûå â webhook", // Íåîá.
success_url = $"https://example.com/", // Íåîá.
sum = 39.00f,
wallet_to = "R123123123"
}
);
Console.Out.WriteLine(createdPayment.url);

// >>> 'https://p2p.lava.ru/form?id=1ee31634-e3e0-34ce-1423-b5b4cb524c6a'
```
80 changes: 77 additions & 3 deletions Types/LavaAPI/Payment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,105 @@ namespace Lava.NET.Types.LavaAPI
{
public class PaymentRequest : IBase

Check warning on line 9 in Types/LavaAPI/Payment.cs

View workflow job for this annotation

GitHub Actions / build

Nullability of reference types in return type of 'string? object.ToString()' doesn't match implicitly implemented member 'string IBase.ToString()' (possibly because of nullability attributes).
{
public string wallet_to { get; set; }
public float sum { get; set; }
/// <summary>
/// Ваш номер счета
/// </summary>
public string wallet_to { get; set; }
/// <summary>
/// Сумма с копейками и f на конце
/// Пример: 1.00f
/// </summary>
public float sum { get; set; } = 1.00f;
/// <summary>
/// Уникальный номер счета в вашей системе
/// </summary>
public string? order_id { get; set; }
/// <summary>
/// Url для отправки webhook
/// </summary>
public string? hook_url { get; set; }
public string? success_url { get; set; }
/// <summary>
/// Url для переадресации в случае успешной оплаты
/// </summary>
public string? success_url { get; set; }
/// <summary>
/// Url для переадресации в случае неуспешной оплаты
/// </summary>
public string? fail_url { get; set; }
/// <summary>
/// Время жизни счета в минутах
/// Мин: 1 ; Макс: 43200
/// </summary>
public int? expire { get; set; } = 43200;
/// <summary>
/// С кого списывать комиссию:
/// 1 - с клиента
/// 0 - с магазина
/// </summary>
public string? subtract { get; set; }
/// <summary>
/// Дополнительные данные предаваемые в вебхуке
/// </summary>
public string? custom_fields { get; set; }
/// <summary>
/// Комментарий
/// </summary>
public string? comment { get; set; }
/// <summary>
/// ID марчанта(только в вебхуке)
/// </summary>
public string? merchant_id { get; set; }
/// <summary>
/// Название мерчанта (отображается в форме перевода)
/// </summary>
public string? merchant_name { get; set; }
}
public class PaymentResponse : IBase

Check warning on line 64 in Types/LavaAPI/Payment.cs

View workflow job for this annotation

GitHub Actions / build

Nullability of reference types in return type of 'string? object.ToString()' doesn't match implicitly implemented member 'string IBase.ToString()' (possibly because of nullability attributes).
{
/// <summary>
/// Статус запроса
/// </summary>
public string status { get; set; }
/// <summary>
/// Номер счета на оплату
/// </summary>
public string id { get; set; }
/// <summary>
/// Ссылка на оплату
/// </summary>
public string url { get; set; }
/// <summary>
/// Время истечения счета
/// </summary>
public int expire { get; set; }
/// <summary>
/// Сумма счета
/// </summary>
public string sum { get; set; }
/// <summary>
/// // URL для переадресации после успешной оплаты
/// </summary>
public string success_url { get; set; }
/// <summary>
/// URL для переадресации после неудачной оплаты
/// </summary>
public string fail_url { get; set; }
/// <summary>
/// адрес для вебхука
/// </summary>
public string hook_url { get; set; }
/// <summary>
/// Дополнительное поле
/// </summary>
public string custom_fields { get; set; }
/// <summary>
/// ID и наименование мерчанта
/// </summary>
public string merchant_name { get; set; }
/// <summary>
/// ID и наименование мерчанта
/// </summary>

public string merchant_id { get; set; }
}
public class Invoice : IBase
Expand Down
6 changes: 6 additions & 0 deletions Types/LavaAPI/SBPBanks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ namespace Lava.NET.Types.LavaAPI
{
public class Datum : IBase

Check warning on line 9 in Types/LavaAPI/SBPBanks.cs

View workflow job for this annotation

GitHub Actions / build

Nullability of reference types in return type of 'string? object.ToString()' doesn't match implicitly implemented member 'string IBase.ToString()' (possibly because of nullability attributes).
{
/// <summary>
/// ID банка
/// </summary>
public object id { get; set; }
/// <summary>
/// Название
/// </summary>
public string name { get; set; }
}

Expand Down
Loading

0 comments on commit a2b4865

Please sign in to comment.