Add project files.

This commit is contained in:
yawaflua
2024-03-07 18:11:59 +03:00
parent aee40c9686
commit 9f29952f71
19 changed files with 736 additions and 0 deletions

28
.github/workflows/dotnet.yml vendored Normal file
View File

@@ -0,0 +1,28 @@
# This workflow will build a .NET project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net
name: .NET
on:
push:
branches: [ "*" ]
pull_request:
branches: [ "*" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal

28
.github/workflows/nuget.yml vendored Normal file
View File

@@ -0,0 +1,28 @@
name: NuGet - Release
on:
release:
types: [published]
jobs:
publish-nuget:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: '7.x.x'
- name: Set output
id: vars
run: echo "tag=${GITHUB_REF#refs/*/}" >> $GITHUB_OUTPUT
- name: Publish to NuGet
uses: kelson-dev/publish-nuget-fixed@2.5.6
with:
PROJECT_FILE_PATH: Lava.NET.csproj
VERSION_STATIC: ${{ steps.vars.outputs.tags }}
TAG_COMMIT: true
TAG_FORMAT: "*"
NUGET_KEY: ${{secrets.NUGET_API_KEY}}
NUGET_SOURCE: https://api.nuget.org
INCLUDE_SYMBOLS: false

17
Exceptions.cs Normal file
View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Exceptions
{
/// <summary>
/// Sending error when Lava.ru type is not equals your type
/// </summary>
public class TypeException : Exception {
public TypeException(string? message) : base(message) { }
public TypeException() : base() { }
public TypeException(string? message, Exception exception) : base(message, exception) { }
}
}

22
Lava.NET.csproj Normal file
View File

@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>v1.0.0</Version>
</PropertyGroup>
<ItemGroup>
<Compile Include=".github\workflows\dotnet.yml" />
</ItemGroup>
<ItemGroup>
<None Include=".github\workflows\nuget.yml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>

25
Lava.NET.sln Normal file
View File

@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34622.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lava.NET", "Lava.NET.csproj", "{D273E6E8-53EC-483F-985D-E71A6E0BA041}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D273E6E8-53EC-483F-985D-E71A6E0BA041}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D273E6E8-53EC-483F-985D-E71A6E0BA041}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D273E6E8-53EC-483F-985D-E71A6E0BA041}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D273E6E8-53EC-483F-985D-E71A6E0BA041}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {26DE234C-76FC-4D24-BF3C-9ECAD7823E1C}
EndGlobalSection
EndGlobal

92
Program.cs Normal file
View File

@@ -0,0 +1,92 @@
using Lava.NET.Types.Enums;
using Lava.NET.Types.LavaAPI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json.Nodes;
namespace Lava.NET
{
/// <summary>
/// Ограниченный класс, который используется как базовый для бизнес части и публичной части Lava API. Использование нежелательно!
/// </summary>
/// <param name="token">Токен от Lava.ru</param>
/// <param name="type">Тип вашего аккаунта</param>
public class ILavaAPI(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)
{
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))
{
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)
=> JsonConvert.DeserializeObject<PaymentResponse>(await SendRequest("invoice/create", LavaType.any, HttpMethod.Post, data.ToString()));
public async Task<PaymentInfo?> GetPaymentInfoAsync(string id)
=> JsonConvert.DeserializeObject<PaymentInfo>(await SendRequest("invoice/info", LavaType.any, HttpMethod.Post, id));
public async Task SetWebhookUrl(string url)
=> await SendRequest("invoice/set-webhook", LavaType.any, HttpMethod.Post, url);
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 PublicLavaAPI(string token) : base(token, LavaType.wallet) { }
public async Task<Wallet[]?> getWallets()
=> JsonConvert.DeserializeObject<Wallet[]>(await SendRequest("wallet/list", LavaType.wallet, HttpMethod.Get));
public async Task<DefaultResponse?> MakeWithdraw(Withdraw withdraw)
=> JsonConvert.DeserializeObject<DefaultResponse>(await SendRequest("withdraw/create", LavaType.wallet, HttpMethod.Post, withdraw.ToString()));
public async Task<WithdrawInfo?> InfoWithdrawAsync(string id)
=> JsonConvert.DeserializeObject<WithdrawInfo>(await SendRequest("withdraw/info", LavaType.wallet, HttpMethod.Post, id));
public async Task<DefaultResponse?> MakeTransfer(Transfer data)
=> JsonConvert.DeserializeObject<DefaultResponse>(await SendRequest("transfer/create", LavaType.wallet, HttpMethod.Post, data.ToString()));
public async Task<TransferData?> GetTransferDataAsync(string id)
=> JsonConvert.DeserializeObject<TransferData>(await SendRequest("transfer/info", LavaType.wallet, HttpMethod.Post, id));
public async Task<Transaction[]?> GetTransactionsAsync(TransactionParam? transaction = null)
=> JsonConvert.DeserializeObject<Transaction[]>(await SendRequest("transactions/list", LavaType.wallet, HttpMethod.Post, transaction?.ToString()));
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)
{
internal async Task<string> SendRequest(string path, LavaType? neededType = LavaType.business, HttpMethod? method = null, string? body = null, bool isSpecial = true)
{
method ??= HttpMethod.Post;
if (neededType != LavaType.any && neededType != LavaType.business) throw new Exceptions.TypeException("Your Lava.ru account type is not equals needed type");
_httpClient.DefaultRequestHeaders.Authorization = new("", token);
if (isSpecial)
{
_httpClient.DefaultRequestHeaders.Accept.Add(new("application/json"));
_httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
}
using (var message = new HttpRequestMessage(method, path))
{
message.Content = body == null ? new StringContent(body.ToString()) : null;
var req = await _httpClient.SendAsync(message);
return await req.Content.ReadAsStringAsync();
}
}
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)
=> JsonConvert.DeserializeObject<PayoffDataResponse>(await SendRequest("business/payoff/info", body: request.ToString()));
public async Task<PayoffTariffResponse?> GetPayoffTariffAsync(PayoffTariffRequest request)
=> JsonConvert.DeserializeObject<PayoffTariffResponse>(await SendRequest("business/payoff/get-tariffs", body: request.ToString()));
public async Task<PayoffCheckoutResponse?> CheckPayoffTariffAsync(PayoffCheckoutRequest request)
=> JsonConvert.DeserializeObject<PayoffCheckoutResponse>(await SendRequest("business/payoff/check-wallet", body: request.ToString()));
// В разработке...
}
}

23
Types/Base.cs Normal file
View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Lava.NET.Types
{
public interface IBase
{
public string ToString()
{
return JsonSerializer.Serialize(this);
}
}
public static class Statics
{
public static string ToString(this IBase @base)
=> JsonSerializer.Serialize(@base);
}
}

59
Types/Enums/ErrorCodes.cs Normal file
View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.Enums
{
public enum ErrorCode
{
/// <summary>Неизвестная ошибка</summary>
UnknownError = 0,
/// <summary>Объект не найден</summary>
ObjectNotFound = 1,
/// <summary>Неверное значение параметра</summary>
InvalidParameterValue = 2,
/// <summary>Неверный JWT-токен</summary>
InvalidJWTToken = 5,
/// <summary>Серверная ошибка</summary>
ServerError = 6,
/// <summary>Неверный тип запроса</summary>
InvalidRequestType = 7,
/// <summary>Переданы неверный параметры</summary>
InvalidParameters = 100,
/// <summary>Неверный номер счета</summary>
InvalidInvoiceNumber = 101,
/// <summary>Сумма меньше минимальной</summary>
AmountBelowMinimum = 102,
/// <summary>Сумма больше максимальной</summary>
AmountAboveMaximum = 103,
/// <summary>Недостаточно средств на балансе</summary>
InsufficientBalance = 104,
/// <summary>Транзакция не найдена</summary>
TransactionNotFound = 105,
/// <summary>Перевод недоступен</summary>
TransferUnavailable = 107,
/// <summary>Время жизни меньше минимальной</summary>
ExpireBelowMinimum = 202,
/// <summary>Время жизни больше максимальной</summary>
ExpireAboveMaximum = 203,
/// <summary>Номер больше 255 символов</summary>
OrderNumberTooLong = 204,
/// <summary>Такой номер заказа уже существует</summary>
OrderNumberAlreadyExists = 205,
/// <summary>Счет на оплату не найден</summary>
InvoiceNotFound = 206,
/// <summary>Срок жизни счета истек</summary>
InvoiceExpired = 207,
/// <summary>Счет уже оплачен</summary>
InvoiceAlreadyPaid = 208,
/// <summary>Не установлен секретный ключ</summary>
SecretKeyNotSet = 209,
/// <summary>Неверная сигнатура</summary>
InvalidSignature = 210,
/// <summary>Конвертация недоступна</summary>
ConversionUnavailable = 251
}
}

15
Types/Enums/LavaType.cs Normal file
View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.Enums
{
public enum LavaType
{
business,
wallet,
any
}
}

20
Types/Enums/Methods.cs Normal file
View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.Enums
{
public enum Methods
{
Qiwi = 10,
YooMoney = 10,
Card = 1000,
AdvCash = 50,
Payeer = 50,
Phone = 10,
PerfectMoney = 50,
SBP = 50
}
}

17
Types/LavaAPI/Default.cs Normal file
View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class DefaultResponse : IBase
{
public string id { get; set; }
public string status { get; set; }
public string amount { get; set; }
public int commission { get; set; }
}
}

57
Types/LavaAPI/Payment.cs Normal file
View File

@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class PaymentRequest : IBase
{
public string wallet_to { get; set; }
public float sum { get; set; }
public string? order_id { get; set; }
public string? hook_url { get; set; }
public string? success_url { get; set; }
public string? fail_url { get; set; }
public int? expire { get; set; } = 43200;
public string? subtract { get; set; }
public string? custom_fields { get; set; }
public string? comment { get; set; }
public string? merchant_id { get; set; }
public string? merchant_name { get; set; }
}
public class PaymentResponse : IBase
{
public string status { get; set; }
public string id { get; set; }
public string url { get; set; }
public int expire { get; set; }
public string sum { get; set; }
public string success_url { get; set; }
public string fail_url { get; set; }
public string hook_url { get; set; }
public string custom_fields { get; set; }
public string merchant_name { get; set; }
public string merchant_id { get; set; }
}
public class Invoice : IBase
{
public string id { get; set; }
public string order_id { get; set; }
public int expire { get; set; }
public string sum { get; set; }
public string comment { get; set; }
public string status { get; set; }
public string success_url { get; set; }
public string fail_url { get; set; }
public string hook_url { get; set; }
public string custom_fields { get; set; }
}
public class PaymentInfo : IBase
{
public string status { get; set; }
public Invoice invoice { get; set; }
}
}

178
Types/LavaAPI/Payoff.cs Normal file
View File

@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
/// <summary>
/// Параметры запроса на вывод средств.
/// </summary>
public class PayoffRequest : IBase
{
/// <summary>
/// Сумма вывода.
/// </summary>
public double amount { get; set; }
/// <summary>
/// Уникальный идентификатор платежа в системе мерчанта.
/// </summary>
public string orderId { get; set; }
/// <summary>
/// Подпись запроса.
/// </summary>
public string signature { get; set; }
/// <summary>
/// Идентификатор проекта.
/// </summary>
public Guid shopId { get; set; }
/// <summary>
/// Куда отправлять хук (Max: 500).
/// </summary>
public string hookUrl { get; set; }
/// <summary>
/// Сервис, на который производится вывод средств.
/// </summary>
public string service { get; set; }
/// <summary>
/// Номер кошелька, на который производится вывод средств.
/// При выводе на свой лава кошелёк параметр не указывается.
/// </summary>
public string walletTo { get; set; }
/// <summary>
/// С кого списывать коммиссию: с магазина или с суммы.
/// По умолчанию 0, 1 - с магазина, 0 - с суммы.
/// </summary>
public string subtract { get; set; }
}
public class Data : IBase
{
public string payoff_id { get; set; }
public string payoff_status { get; set; }
}
public class PayoffResponse : IBase
{
public Data data { get; set; }
public int status { get; set; }
public bool status_check { get; set; }
}
/// <summary>
/// Параметры запроса.
/// </summary>
public class PayoffDataRequest : IBase
{
/// <summary>
/// Подпись запроса.
/// </summary>
public string? signature { get; set; }
/// <summary>
/// Идентификатор проекта.
/// </summary>
public Guid shopId { get; set; }
/// <summary>
/// Уникальный идентификатор платежа в системе мерчанта.
/// </summary>
public Guid? orderId { get; set; }
/// <summary>
/// Номер вывода.
/// </summary>
public Guid? payoffId { get; set; }
}
public class ResponseData : IBase
{
public string id { get; set; }
public object orderId { get; set; }
public string status { get; set; }
public string wallet { get; set; }
public string service { get; set; }
public int amountPay { get; set; }
public double commission { get; set; }
public double amountReceive { get; set; }
public int tryCount { get; set; }
public object errorMessage { get; set; }
}
public class PayoffDataResponse : IBase
{
public ResponseData data { get; set; }
public int status { get; set; }
public bool status_check { get; set; }
}
public class PayoffTariffData : IBase
{
public List<Tariff> tariffs { get; set; }
}
public class PayoffTariffResponse : IBase
{
public PayoffTariffData data { get; set; }
public int status { get; set; }
public bool status_check { get; set; }
}
public class PayoffTariffRequest : IBase
{
/// <summary>
/// Подпись запроса.
/// </summary>
public string signature { get; set; }
/// <summary>
/// Идентификатор проекта.
/// </summary>
public Guid shopId { get; set; }
}
public class Tariff : IBase
{
public double percent { get; set; }
public int min_sum { get; set; }
public int max_sum { get; set; }
public string service { get; set; }
public int fix { get; set; }
public string title { get; set; }
public string currency { get; set; }
}
/// <summary>
/// Класс, представляющий параметры запроса.
/// </summary>
public class PayoffCheckoutRequest : IBase
{
/// <summary>
/// Кошелёк/аккаунт.
/// </summary>
public string walletTo { get; set; }
/// <summary>
/// Сервис для выплаты.
/// Тип: ['card_payoff', 'qiwi_payoff', 'lava_payoff', 'steam_payoff']
/// </summary>
public string service { get; set; }
/// <summary>
/// Подпись запроса
/// </summary>
public string? signature { get; set; }
/// <summary>
/// Идентификатор проекта
/// </summary>
public Guid shopId { get; set; }
}
public class PayoffData
{
public bool status { get; set; }
}
public class PayoffCheckoutResponse
{
public PayoffData data { get; set; }
public int status { get; set; }
public bool status_check { get; set; }
}
}

19
Types/LavaAPI/SBPBanks.cs Normal file
View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class Datum : IBase
{
public object id { get; set; }
public string name { get; set; }
}
public class SBPBanks : IBase
{
public List<Datum> data { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class TransactionParam : IBase
{
public string? transfer_type { get; set; }
public string? account { get; set; }
public string? period_start { get; set; }
public string? period_end { get; set; }
public int? offset { get; set; }
public int? limit { get; set; }
}
public class Transaction : IBase
{
public string id { get; set; }
public string created_at { get; set; }
public DateTime created_date { get; set; }
public string amount { get; set; }
public string status { get; set; }
public string transfer_type { get; set; }
public string comment { get; set; }
public string method { get; set; }
public string currency { get; set; }
public string account { get; set; }
public string commission { get; set; }
public string type { get; set; }
public string receiver { get; set; }
}
}

29
Types/LavaAPI/Transfer.cs Normal file
View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class Transfer : IBase
{
public string account_from { get; set; }
public string account_to { get; set;}
public int substract { get; set; } = 0;
public int amount { get; set; }
public string? comment { get; set; }
}
public class TransferData : IBase
{
public string id { get; set; }
public string created_at { get; set; }
public string amount { get; set; }
public string status { get; set; }
public object comment { get; set; }
public string currency { get; set; }
public string type { get; set; }
public string receiver { get; set; }
public string commission { get; set; }
}
}

15
Types/LavaAPI/Wallet.cs Normal file
View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class Wallet : IBase
{
public string account { get; set; }
public string currency { get; set; }
public string balance { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class WebhookResponse : IBase
{
public int type { get; set; }
public string invoice_id { get; set; }
public string order_id { get; set; }
public string status { get; set; }
public int pay_time { get; set; }
public string amount { get; set; }
public string custom_fields { get; set; }
public string credited { get; set; }
public string merchant_id { get; set; }
public string merchant_name { get; set; }
public string sign { get; set; }
}
}

33
Types/LavaAPI/Withdraw.cs Normal file
View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lava.NET.Types.LavaAPI
{
public class WithdrawInfo : IBase
{
public string id { get; set; }
public string created_at { get; set; }
public string amount { get; set; }
public string commission { get; set; }
public string status { get; set; }
public string service { get; set; }
public string comment { get; set; }
public string currency { get; set; }
}
public class Withdraw : IBase
{
public string account { get; set; }
public float amount { get; set; }
public string order_id { get; set; }
public string hook_url { get; set; }
public int subtract { get; set; } = 0;
public string service { get; set; } = "card";
public string wallet_to { get; set; }
public string comment { get; set; }
public string sbp_bank_id { get; set; }
}
}