From b6655c1b9e37c2e57db25acc7657513c6bda485b Mon Sep 17 00:00:00 2001 From: Mih4n <50325226+Mih4n@users.noreply.github.com> Date: Mon, 22 May 2023 11:29:41 +0300 Subject: [PATCH] 1.0.2 --- README.md | 107 ++++++++++++- gitignore | 363 ++++++++++++++++++++++++++++++++++++++++++++ src/spworlds.cs | 107 ++++++------- src/spworlds.csproj | 7 +- 4 files changed, 518 insertions(+), 66 deletions(-) create mode 100644 gitignore diff --git a/README.md b/README.md index d65719e..34e428f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,107 @@ -# spworlds +# spworlds-sharp-library данный пак предназначен для использования апи сайта spworlds. Однако к создателям спворлдс отношения не имеет + +# CS Библиотека сайтов СП + +Это библиотека для dotnet для упрощения API сайтов СП. Документация к API [тут](https://github.com/sp-worlds/api-docs). + +## Установка + +Вы можете установить эту библиотеку при помощи +`dotnet` или альтернативного пакетного менеджера. + +```bash +dotnet add package spworlds +``` + +## Использование + +```cs +using spworlds; + +... + +// в теле создаете новый обект типа spworlds в +// констрактор вы ОБЯЗАННЫ передать передать параметры указанные ниже. Тип данных - стринг +SPWorlds sp = new SPworlds("[ваш айди]","[ваш токен]"); + +//так же я советую вам использовать dependancy injection и добавить в него данный обьект как сингл тон т.к он не +//требуется более чем в одном екземпляре и так-же вам не прейдется каждый раз прописывать строки указанные выше + +//пример: +using spworlds; + +SPWorlds sp = new SPworlds("[ваш айди]","[ваш токен]"); + +IServiceProvider = new IServiceColection() + .AddSomething() // какойто добавляемый микросервис может быть что угодно + .AddSingletone(sp) + .AddSomething() // какойто добавляемый микросервис может быть что угодно + .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://eximple.com/success", + "https://api.example.com/webhook", + "SomeString" +); +``` + +### Перевод АРов на другую карту + +Перевод 16 АР на карту с номером 11111 и комментарием "С днем рождения!" + +```cs +sp.CreateTransaction("11111", 16, "С днем рождения!"); +``` + +### Получение баланса карты + +```cs +int balance = await sp.GetCardBalance(); +``` + +### Получение ника игрока + +Метод принимает ID игрока в Discord и возвращает его ник, если у него есть вход на сервер. + +```cs +string username = await sp.GetUser("111111111111111111"); + +if (!username) +{ + // ваша логика дааа +} +``` + +### Подтверждение вебхука + +```cs +// увы пока нет) +``` + +## Contributing + +Если вы хотите дополнить или улучшить библиотеку или документацию к ней, то сделайте pull запрос к этому репозиторию. diff --git a/gitignore b/gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/src/spworlds.cs b/src/spworlds.cs index 3b80f77..361c36e 100644 --- a/src/spworlds.cs +++ b/src/spworlds.cs @@ -1,109 +1,90 @@ -using System.Net.Http; -using System.Net.Http.Headers; +using System.Net.Http.Headers; using System.Text.Json; using System.Text; using System.Text.Json.Nodes; namespace spworlds; -public class SpWorlds +public class SPWorlds { - private readonly HttpClient _client; - JsonSerializerOptions options = new JsonSerializerOptions + private readonly HttpClient client; + + public SPWorlds(string id, string token) { - PropertyNameCaseInsensitive = true - }; + client = new HttpClient(); + var BearerToken = $"{id}:{token}"; + string Base64BearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(BearerToken)); - - public SpWorlds(string id, string token) - { - var StringToken = $"{id}:{token}"; - byte[] bytes = System.Text.Encoding.UTF8.GetBytes(StringToken); - var Base64Token = Convert.ToBase64String(bytes); - - _client = new HttpClient(); - _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Base64Token); + client.BaseAddress = new Uri("https://spworlds.ru/api/public/"); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Base64BearerToken); } - private string SendRequest(string path, T body, Boolean getResult) + private async Task SendRequest(string endpoint, Boolean getResult = true, Dictionary? body = null) { string respond; - string method = (body == null) ? "GET" : "POST"; - string jsonBody = null; + string jsonBody; - var endpoint = new Uri($"https://spworlds.ru/api/public/{path}"); - if(method == "GET") + if(body == null) { - return respond = _client.GetAsync(endpoint).Result.Content.ReadAsStringAsync().Result; + return respond = client.GetAsync(endpoint).Result.Content.ReadAsStringAsync().Result; } else { - jsonBody = JsonSerializer.Serialize(body); + 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; + return respond = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result; else - _client.PostAsync(endpoint, payload); + await client.PostAsync(endpoint, payload); } - return jsonBody; + return null; } - public int GetBalance() + public async Task GetBalance() { - string respond = SendRequest("card", null, true); + string respond = await SendRequest("card"); var card = JsonObject.Parse(respond); var balance = card["balance"]; + return (int)balance; } - public void CreatTransition(string reciverCardId, int amount, string comment) + public async Task CreatTransaction(string receiver, int amount, string comment) { - TransitionInfo transitionInfo = new TransitionInfo(); - transitionInfo.amount = amount; - transitionInfo.comment = comment; - transitionInfo.receiver = reciverCardId; + var transitionInfo = new Dictionary + { + { "receiver", receiver }, + { "amount", amount }, + { "comment", comment } + }; - SendRequest("transactions", transitionInfo, false); + await SendRequest(endpoint: "transactions", body: transitionInfo); } - public string GetUser(string discordId) + public async Task GetUser(string discordId) { - var user = JsonObject.Parse(SendRequest($"users/{discordId}", null, true)); + var user = JsonObject.Parse(await SendRequest($"users/{discordId}")); var userName = user["username"]; + return (string)userName; } - public string InitPayment(int amount, string redirectUrl, string webhookUrl, string data) + public async Task InitPayment(int amount, string redirectUrl, string webhookUrl, string data) { - PaymentInfo paymentInfo = new PaymentInfo(); - paymentInfo.amount = amount; - paymentInfo.redirectUrl = redirectUrl; - paymentInfo.webhookUrl = webhookUrl; - paymentInfo.data = data; + var paymentInfo = new Dictionary + { + { "amount", amount }, + { "redirectUrl", redirectUrl }, + { "webhookUrl", webhookUrl }, + { "data", data } + }; - var jsonBody = JsonSerializer.Serialize(paymentInfo); - - Console.WriteLine(jsonBody); - - var payment = JsonObject.Parse(SendRequest($"payment", paymentInfo, true)); + var payment = JsonObject.Parse(await SendRequest(endpoint: $"payment",body: paymentInfo)); var url = payment["url"]; - return (string) url; - } - class PaymentInfo - { - public int amount { get; set; } - public string redirectUrl { get; set; } - public string webhookUrl { get; set; } - public string data { get; set; } + return (string)url; } - - class TransitionInfo - { - public string receiver { get; set; } - public int amount { get; set; } - public string comment { get; set; } - } -} +} \ No newline at end of file diff --git a/src/spworlds.csproj b/src/spworlds.csproj index cf3c115..d127f1b 100644 --- a/src/spworlds.csproj +++ b/src/spworlds.csproj @@ -4,15 +4,18 @@ net6.0 enable enable - spworlds.17.05.2023.999 + spworlds данная библиотека предназначена для работы с сайтом spworlds. Ознакомиться с документацией можно в гитхабе проекта MIT - 1.0.0 + 1.0.1 Mih4n Mih4n + https://github.com/Mih4n/spworlds + README.md +