Remove ignored files

This commit is contained in:
Mih4n
2023-10-25 21:09:01 +03:00
parent 9aa976b234
commit 922a8934ae
23 changed files with 256 additions and 186 deletions

120
src/README.md Normal file
View File

@@ -0,0 +1,120 @@
# spworlds-sharp-library
данный пак предназначен для использования апи сайта spworlds. Однако к создателям спворлдс отношения не имеет
# CS Библиотека сайтов СП
Это библиотека для dotnet для упрощения API сайтов СП. Документация к API [тут](https://github.com/sp-worlds/api-docs).
## Установка
Вы можете установить эту библиотеку при помощи
`dotnet` или альтернативного пакетного менеджера.
```bash
dotnet add package spworlds
```
## Использование
```cs
...
// в теле создаете новый обект типа spworlds в
// констрактор вы ОБЯЗАННЫ передать передать параметры указанные ниже. Тип данных - стринг
// SPWorlds sp = new SPworlds("[ваш айди]", "[ваш токен]");
//так же я советую вам использовать dependancy injection и добавить в него данный обьект как сингл тон т.к он не
//требуется более чем в одном экземпляре и так-же вам не прийдется каждый раз прописывать строки указанные выше
//пример:
using spworlds;
SPWorlds sp = new SPworlds("[ваш айди]","[ваш токен]");
IServiceProvider = new IServiceColection()
.AddSomething() // какойто добавляемый микросервис может быть что угодно
.AddSingletone(sp)
.Build();
// получение микросервиса в другом классе
public class MyClass
{
private readonly sp;
public MyClass(SPWorlds spInCtor)
// заметьте, мы в конструкторе должы указать именно
//тип того синглтона который мы хотим получить, а название может быть любым
{
this.sp = sp; // мы передаем переменную другой т.к данная переменная доступна только в конструкторе
}
}
```
## Использование
### Инициализировать платежную форму
Если вы хотите принимать оплату в АРах на своем сайте, используйте этот метод.
Получение ссылки на страницу оплаты 16 АР, после успешной оплаты пользователь перейдет со страницы оплаты на `https://eximple.com/success`, а сайт СП отправит запрос на `https://api.example.com/webhook` с данными этого платежа, в том числе и `SomeString`. Последнее поле можно использовать, например, для ID заказа или чего-то подобного или вставить туда json а потом его десериализовать в объект после оплаты, так как он возвращается вместе с вебхуком об успешной оплате.
```cs
const url = await sp.InitPayment(
16,
"https://example.com/success",
"https://api.example.com/webhook",
"SomeString"
);
```
ИЛИ
```cs
public async Task<IActionResult> GetCreatePaymentFunction([FromBody] PaymentData paymentData)
{
const url = await sp.InitPayment(paymentData);
// Ваша логика
}
```
### Перевод АРов на другую карту
Перевод 16 АР на карту с номером 11111 и комментарием "С днем рождения!"
```cs
sp.CreateTransaction("11111", 16, "С днем рождения!");
```
### Получение баланса карты
```cs
int balance = await sp.GetCardBalance();
```
### Получение ника игрока
Метод принимает ID игрока в Discord и возвращает его ник, если у него есть вход на сервер.
```cs
User user = await sp.GetUser("111111111111111111");
if (user.Name == "Mih4n")
{
// ваша логика дааа
}
```
### Получение скина(части скина) игрока
Метод принимает один из элементов енам-класса SkinPart и разрешение скина(советуется использовать 64, 128 и т.д., но если вам требуется использовать специфичные значения, например на сайте, указывайте как хотите)
Метод является сабметодом класса User, так что выглядит это так:
```cs
User user = await sp.GetUser("111111111111111111");
const faceUrl = user.GetSkinPart(SkinPart.face, "64");
```
### Подтверждение вебхука
Метод рабочий, но то, что присылается от сайта вместе с вебхуком от оплаты невозможно дешифровать, все же, если очень надо, то вот:
```cs
bool IsWebHook = await sp.ValidateWebHook(WebHookText, X_Body_Hash);
```
## Contributing
Если вы хотите дополнить или улучшить библиотеку или документацию к ней, то сделайте pull запрос к этому репозиторию.

View File

@@ -1,9 +1,9 @@
namespace spworlds.Types;
public class PaymentData
{
public int Amount;
public string RedirectUrl;
public string WebHookUrl;
public string Data;
namespace spworlds.Types;
public class PaymentData
{
public int Amount;
public string RedirectUrl;
public string WebHookUrl;
public string Data;
}

View File

@@ -1,12 +1,12 @@
namespace spworlds.Types;
public enum SkinPart
{
face,
front,
front_full,
head,
bust,
full,
skin
}
namespace spworlds.Types;
public enum SkinPart
{
face,
front,
front_full,
head,
bust,
full,
skin
}

View File

@@ -1,37 +1,37 @@
using spworlds;
using System.Text.Json.Nodes;
namespace spworlds.Types;
public class User
{
public string Name { get; }
public string Uuid { get; }
public JsonNode profile { get; }
public bool IsPlayer() => Name != null ? true : false;
public User(string name, string uuid, JsonNode profile)
{
Name = name;
Uuid = uuid;
this.profile = profile;
}
public static async Task<User> CreateUser(string name)
{
string uuid;
JsonNode profile;
using(HttpClient client = new())
{
uuid = (string)JsonNode.Parse(await client.GetStringAsync($"https://api.mojang.com/users/profiles/minecraft/{name}"))["id"];
profile = JsonNode.Parse(await client.GetStringAsync($"https://sessionserver.mojang.com/session/minecraft/profile/{uuid}"));
}
User user = new(name, uuid, profile);
return user;
}
public string GetSkinPart(SkinPart skinPart, string size = "64")
{
return (string)$"https://visage.surgeplay.com/{skinPart}/{size}/{this.profile["profileId"]}";
}
}
using spworlds;
using System.Text.Json.Nodes;
namespace spworlds.Types;
public class User
{
public string Name { get; }
public string Uuid { get; }
public JsonNode profile { get; }
public bool IsPlayer() => Name != null ? true : false;
public User(string name, string uuid, JsonNode profile)
{
Name = name;
Uuid = uuid;
this.profile = profile;
}
public static async Task<User> CreateUser(string name)
{
string uuid;
JsonNode profile;
using(HttpClient client = new())
{
uuid = (string)JsonNode.Parse(await client.GetStringAsync($"https://api.mojang.com/users/profiles/minecraft/{name}"))["id"];
profile = JsonNode.Parse(await client.GetStringAsync($"https://sessionserver.mojang.com/session/minecraft/profile/{uuid}"));
}
User user = new(name, uuid, profile);
return user;
}
public string GetSkinPart(SkinPart skinPart, string size = "64")
{
return (string)$"https://visage.surgeplay.com/{skinPart}/{size}/{this.profile["profileId"]}";
}
}

View File

@@ -0,0 +1,23 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v6.0",
"signature": ""
},
"compilationOptions": {},
"targets": {
".NETCoreApp,Version=v6.0": {
"spworlds/1.0.4": {
"runtime": {
"spworlds.dll": {}
}
}
}
},
"libraries": {
"spworlds/1.0.4": {
"type": "project",
"serviceable": false,
"sha512": ""
}
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -14,12 +14,12 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("данная библиотека предназначена для работы с сайтом spworlds. Ознакомиться с доку" +
"ментацией можно в гитхабе проекта")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.1.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.1")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.4.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.4")]
[assembly: System.Reflection.AssemblyProductAttribute("spworlds")]
[assembly: System.Reflection.AssemblyTitleAttribute("spworlds")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.1.0")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.4.0")]
[assembly: System.Reflection.AssemblyMetadataAttribute("RepositoryUrl", "https://github.com/Mih4n/spworlds")]
// Создано классом WriteCodeFragment MSBuild.
// Generated by the MSBuild WriteCodeFragment class.

View File

@@ -1 +1 @@
3b79596e0f193799e87c2d642144700f8551bcf8
4fc85608e250b55334138dc0a2960a1ccc317f15

View File

@@ -2,3 +2,10 @@ C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\spworlds.AssemblyInfoInputs.cache
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\spworlds.AssemblyInfo.cs
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\spworlds.csproj.CoreCompileInputs.cache
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\bin\Debug\net6.0\spworlds.deps.json
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\bin\Debug\net6.0\spworlds.dll
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\bin\Debug\net6.0\spworlds.pdb
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\spworlds.dll
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\refint\spworlds.dll
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\spworlds.pdb
C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\obj\Debug\net6.0\ref\spworlds.dll

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>spworlds</id>
<version>1.0.1</version>
<authors>Mih4n</authors>
<license type="expression">MIT</license>
<licenseUrl>https://licenses.nuget.org/MIT</licenseUrl>
<readme>README.md</readme>
<description>данная библиотека предназначена для работы с сайтом spworlds. Ознакомиться с документацией можно в гитхабе проекта</description>
<repository url="https://github.com/Mih4n/spworlds" />
<dependencies>
<group targetFramework="net6.0" />
</dependencies>
</metadata>
<files>
<file src="C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\bin\Debug\net6.0\spworlds.dll" target="lib\net6.0\spworlds.dll" />
<file src="C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\README.md" target="\README.md" />
</files>
</package>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>spworlds</id>
<version>1.0.4</version>
<authors>Mih4n</authors>
<license type="expression">MIT</license>
<licenseUrl>https://licenses.nuget.org/MIT</licenseUrl>
<readme>README.md</readme>
<description>данная библиотека предназначена для работы с сайтом spworlds. Ознакомиться с документацией можно в гитхабе проекта</description>
<repository url="https://github.com/Mih4n/spworlds" />
<dependencies>
<group targetFramework="net6.0" />
</dependencies>
</metadata>
<files>
<file src="C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\bin\Debug\net6.0\spworlds.dll" target="lib\net6.0\spworlds.dll" />
<file src="C:\Users\losev\OneDrive\Рабочий стол\spworlds\spworlds-csharp-library\src\README.md" target="\README.md" />
</files>
</package>

View File

@@ -12,7 +12,7 @@
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages": {}
},
"project": {
"version": "1.0.1",
"version": "1.0.4",
"restore": {
"projectUniqueName": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\src\\spworlds.csproj",
"projectName": "spworlds",

View File

@@ -1,6 +1,6 @@
{
"version": 2,
"dgSpecHash": "BcScqcBajGeCpumrD0XHCVXubY8iGSvVtyfgtqEr1b+ZFER5tFI/jvxsd7fM+aNBX0ZgxKhrR3Trd/3mtyDYsQ==",
"dgSpecHash": "AxJ7bOs4Z9l6KXy2n7OAAZz8U1o7V0AmVQguUWJj3EBLeI36WOpEuQH9YGUPP6QALFeUBw9dZ2Q8IM0H/2kaqA==",
"success": true,
"projectFilePath": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\src\\spworlds.csproj",
"expectedPackageFiles": [],

View File

@@ -5,7 +5,7 @@
},
"projects": {
"C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\src\\spworlds.csproj": {
"version": "1.0.1",
"version": "1.0.4",
"restore": {
"projectUniqueName": "C:\\Users\\losev\\OneDrive\\Рабочий стол\\spworlds\\spworlds-csharp-library\\src\\spworlds.csproj",
"projectName": "spworlds",

View File

@@ -1,120 +1,120 @@
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;
using System.Text.Json.Nodes;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using spworlds.Types;
namespace spworlds;
public class SPWorlds
{
private readonly HttpClient client;
private string token;
public SPWorlds(string id, string token)
{
client = new HttpClient();
var BearerToken = $"{id}:{token}";
this.token = token;
string Base64BearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(BearerToken));
client.BaseAddress = new Uri("https://spworlds.ru/api/public/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Base64BearerToken);
}
private async Task<bool> ValidateWebHook(string webHook, string bodyHash)
{
byte[] body = Encoding.UTF8.GetBytes(bodyHash);
byte[] webhook = Encoding.UTF8.GetBytes(webHook);
var key = new HMACSHA256(Encoding.UTF8.GetBytes(token));
string webhook64 = Convert.ToBase64String(key.ComputeHash(webhook));
return webhook64.Equals(body);
}
private async Task<string> SendRequest(string endpoint, Boolean getResult = true, Dictionary<string, object>? body = null)
{
string respond;
string jsonBody;
if (body == null)
{
return respond = client.GetAsync(endpoint).Result.Content.ReadAsStringAsync().Result;
}
else
{
jsonBody = JsonSerializer.Serialize(body);
var payload = new StringContent(jsonBody, Encoding.UTF8, "application/json");
if (getResult)
return respond = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
else
await client.PostAsync(endpoint, payload);
}
return null;
}
public async Task<int> GetBalance()
{
string respond = await SendRequest("card");
var card = JsonObject.Parse(respond);
var balance = card["balance"];
return (int)balance;
}
public async Task CreateTransaction(string receiver, int amount, string comment)
{
var transitionInfo = new Dictionary<string, object>
{
{ "receiver", receiver },
{ "amount", amount },
{ "comment", comment }
};
await SendRequest(endpoint: "transactions", body: transitionInfo);
}
public async Task<User> GetUser(string discordId)
{
string userName = (string)JsonObject.Parse(await SendRequest($"users/{discordId}"))["username"];
User user = await User.CreateUser(userName);
return (User)user;
}
public async Task<string> InitPayment(int amount, string redirectUrl, string webhookUrl, string data)
{
var paymentInfo = new Dictionary<string, object>
{
{ "amount", amount },
{ "redirectUrl", redirectUrl },
{ "webhookUrl", webhookUrl },
{ "data", data }
};
var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment", body: paymentInfo));
var url = payment["url"];
return (string)url;
}
public async Task<string> InitPayment(PaymentData paymentData)
{
var paymentInfo = new Dictionary<string, object>
{
{ "amount", paymentData.Amount },
{ "redirectUrl", paymentData.RedirectUrl },
{ "webhookUrl", paymentData.WebHookUrl },
{ "data", paymentData.Data }
};
var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment", body: paymentInfo));
var url = payment["url"];
return (string)url;
}
}
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;
using System.Text.Json.Nodes;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using spworlds.Types;
namespace spworlds;
public class SPWorlds
{
private readonly HttpClient client;
private string token;
public SPWorlds(string id, string token)
{
client = new HttpClient();
var BearerToken = $"{id}:{token}";
this.token = token;
string Base64BearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(BearerToken));
client.BaseAddress = new Uri("https://spworlds.ru/api/public/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Base64BearerToken);
}
private async Task<bool> ValidateWebHook(string webHook, string bodyHash)
{
byte[] body = Encoding.UTF8.GetBytes(bodyHash);
byte[] webhook = Encoding.UTF8.GetBytes(webHook);
var key = new HMACSHA256(Encoding.UTF8.GetBytes(token));
string webhook64 = Convert.ToBase64String(key.ComputeHash(webhook));
return webhook64.Equals(body);
}
private async Task<string> SendRequest(string endpoint, Boolean getResult = true, Dictionary<string, object>? body = null)
{
string respond;
string jsonBody;
if (body == null)
{
return respond = client.GetAsync(endpoint).Result.Content.ReadAsStringAsync().Result;
}
else
{
jsonBody = JsonSerializer.Serialize(body);
var payload = new StringContent(jsonBody, Encoding.UTF8, "application/json");
if (getResult)
return respond = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
else
await client.PostAsync(endpoint, payload);
}
return null;
}
public async Task<int> GetBalance()
{
string respond = await SendRequest("card");
var card = JsonObject.Parse(respond);
var balance = card["balance"];
return (int)balance;
}
public async Task CreateTransaction(string receiver, int amount, string comment)
{
var transitionInfo = new Dictionary<string, object>
{
{ "receiver", receiver },
{ "amount", amount },
{ "comment", comment }
};
await SendRequest(endpoint: "transactions", body: transitionInfo);
}
public async Task<User> GetUser(string discordId)
{
string userName = (string)JsonObject.Parse(await SendRequest($"users/{discordId}"))["username"];
User user = await User.CreateUser(userName);
return (User)user;
}
public async Task<string> InitPayment(int amount, string redirectUrl, string webhookUrl, string data)
{
var paymentInfo = new Dictionary<string, object>
{
{ "amount", amount },
{ "redirectUrl", redirectUrl },
{ "webhookUrl", webhookUrl },
{ "data", data }
};
var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment", body: paymentInfo));
var url = payment["url"];
return (string)url;
}
public async Task<string> InitPayment(PaymentData paymentData)
{
var paymentInfo = new Dictionary<string, object>
{
{ "amount", paymentData.Amount },
{ "redirectUrl", paymentData.RedirectUrl },
{ "webhookUrl", paymentData.WebHookUrl },
{ "data", paymentData.Data }
};
var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment", body: paymentInfo));
var url = payment["url"];
return (string)url;
}
}

View File

@@ -7,7 +7,7 @@
<PackageId>spworlds</PackageId>
<Description>данная библиотека предназначена для работы с сайтом spworlds. Ознакомиться с документацией можно в гитхабе проекта</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Version>1.0.1</Version>
<Version>1.0.4</Version>
<Authors>Mih4n</Authors>
<Company>Mih4n</Company>
<RepositoryUrl>https://github.com/Mih4n/spworlds</RepositoryUrl>