Skip to content

Commit

Permalink
同一外部订单号支持创建多个币种的订单,NotifyKey重命名为ApiToken,其他优化
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhangYiQiu committed Sep 20, 2022
1 parent 8aa4608 commit c7776b4
Show file tree
Hide file tree
Showing 9 changed files with 137 additions and 31 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ TokenPay
- `TokenPay`接口文档👉🏻[TokenPay接口文档](Wiki/docs.md)
- **也可参考仓库内现有插件**

## 教程(待完善)
## 教程:
- 宝塔运行`TokenPay`教程👉🏻[宝塔运行TokenPay](Wiki/BT_RUN.md)
- 手动运行`TokenPay`教程👉🏻[手动运行TokenPay](Wiki/manual_RUN.md)

Expand Down
8 changes: 5 additions & 3 deletions Wiki/appsettings.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

**务必保存好`TokenPay.db`文件,此文件内保存了系统生成的收款地址和私钥,一旦丢失,你将损失所收取的款项**

**为保证安全性,务必修改`NotifyKey`**
**为保证安全性,务必修改`ApiToken`**

```json
{
Expand All @@ -29,10 +29,12 @@
//"TRON-Address": [ "Txxxxxx1", "Txxxxxx2" ], // UseDynamicAddress设为false时在此配置收款地址
"OnlyConfirmed": true, //默认仅查询已确认的数据,如果想要回调更快,可以设置为false
"NotifyTimeOut": 3, //异步通知超时时间
"NotifyKey": "666666", //异步通知密钥,请务必修改此密钥为随机字符串,脸滚键盘即可!!!
"Telegram": {
"ApiToken": "666666", //异步通知密钥,请务必修改此密钥为随机字符串,脸滚键盘即可!!!
//"WebSiteUrl": "http://token-pay.xxxxx.com", //配置服务器外网域名,一般不需要配置,能自动识别,如识别不正确请手动配置
"Telegram": {
"AdminUserId": 12345678, // 你的账号ID,如不知道ID,可给https://t.me/EShopFakaBot 发送 /me 获取用户ID
"BotToken": "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" //从https://t.me/BotFather 创建机器人时,会给你BotToken
}
}

```
4 changes: 2 additions & 2 deletions src/TokenPay/BgServices/OrderNotifyService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ private async Task<bool> Notify(TokenOrders order)
dic.Add(nameof(order.ToAddress), order.ToAddress);
dic.Add(nameof(order.Status), (int)order.Status);
var SignatureStr = string.Join("&", dic.Select(x => $"{x.Key}={x.Value}"));
var NotifyKey = _configuration.GetValue<string>("NotifyKey");
SignatureStr += NotifyKey;
var ApiToken = _configuration.GetValue<string>("ApiToken");
SignatureStr += ApiToken;
var Signature = SignatureStr.ToMD5();
dic.Add(nameof(Signature), Signature);
var result = await order.NotifyUrl.WithClient(client).PostJsonAsync(dic);
Expand Down
37 changes: 29 additions & 8 deletions src/TokenPay/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ private bool VerifySignature(CreateOrderViewModel model)
{
dic.Remove("Signature");
var SignatureStr = string.Join("&", dic.Select(x => $"{x.Key}={x.Value}"));
var NotifyKey = _configuration.GetValue<string>("NotifyKey");
SignatureStr += NotifyKey;
var ApiToken = _configuration.GetValue<string>("ApiToken");
SignatureStr += ApiToken;
var md5 = SignatureStr.ToMD5();
return Signature == md5;
}
Expand Down Expand Up @@ -145,7 +145,7 @@ public async Task<IActionResult> CreateOrder([FromBody] CreateOrderViewModel mod
});
}
//订单号已存在
var hasOrder = await _repository.Where(x => x.OutOrderId == model.OutOrderId).FirstAsync();
var hasOrder = await _repository.Where(x => x.OutOrderId == model.OutOrderId && x.Currency == model.Currency).FirstAsync();
if (hasOrder != null)
{
return Json(new ReturnData<string>
Expand Down Expand Up @@ -267,7 +267,7 @@ private string Host
/// <exception cref="TokenPayException"></exception>
private async Task<(string, decimal)> GetUseTokenStaticAdress(CreateOrderViewModel model)
{
var TRON = _configuration.GetSection("TRON-Address").Get<string[]>();
var TRON = _configuration.GetSection("TRON-Address").Get<string[]>() ?? new string[0];

var CurrentAdress = model.Currency switch
{
Expand Down Expand Up @@ -347,13 +347,34 @@ private string Host
}
return (UseTokenAdress, Amount);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
[Route("/error-development")]
public IActionResult HandleErrorDevelopment([FromServices] IHostEnvironment hostEnvironment)
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, Message = context?.Error?.Message });
var exceptionHandlerFeature =
HttpContext.Features.Get<IExceptionHandlerFeature>()!;
var e = exceptionHandlerFeature.Error;

if (!hostEnvironment.IsDevelopment())
{
return Json(new ReturnData
{
Message = e.Message
});
}

return Json(new ReturnData<object>
{
Message = e.Message,
Data = new
{
title = exceptionHandlerFeature.Error.Message,
detail = exceptionHandlerFeature.Error.StackTrace,
}
});
}

[Route("/error")]
public IActionResult HandleError() => Problem();
/// <summary>
/// 创建二维码
/// </summary>
Expand Down
99 changes: 91 additions & 8 deletions src/TokenPay/Helper/TelegramBot.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Flurl;
using Flurl.Http;
using Newtonsoft.Json;
using Serilog;

namespace TokenPay.Helper
Expand All @@ -25,8 +26,8 @@ public TelegramBot(IConfiguration configuration)
client.Settings.HttpClientFactory = new ProxyHttpClientFactory(WebProxy);
}
}

public async Task<object?> GetMeAsync(string? TelegramApiHost = null)
public static TelegramBotInfo BotInfo;
public async Task<TelegramResult<TelegramBotInfo>?> GetMeAsync(string? TelegramApiHost = null)
{
if (string.IsNullOrEmpty(_botToken) || _userId <= 0)
{
Expand All @@ -39,17 +40,18 @@ public TelegramBot(IConfiguration configuration)
.AppendPathSegment($"bot{_botToken}/getMe")
.WithClient(client)
.WithTimeout(10);
var result = await request.GetJsonAsync<object>();
Log.Logger.Information("机器人启动成功!\n{@result}", result);
var result = await request.GetJsonAsync<TelegramResult<TelegramBotInfo>>();
Log.Logger.Information("机器人启动成功!我是{@result}。", result.Result.FirstName);
BotInfo = result.Result;
await SendTextMessageAsync("你好呀~我是TokenPay通知机器人!");
return result;
}
public async Task SendTextMessageAsync(string Message, string? TelegramApiHost = null)
public async Task<TelegramResult<SendMessageResult>?> SendTextMessageAsync(string Message, string? TelegramApiHost = null)
{
if (string.IsNullOrEmpty(_botToken) || _userId <= 0)
{
Log.Logger.Information("未配置机器人Token!");
return;
return null;
}
var ApiHost = TelegramApiHost ?? BaseTelegramApiHost;

Expand All @@ -66,13 +68,94 @@ public async Task SendTextMessageAsync(string Message, string? TelegramApiHost =
.WithTimeout(10);
try
{
var result = await request.GetStringAsync();
Log.Logger.Information("机器人消息发送结果:{result}", result);
var result = await request.GetJsonAsync<TelegramResult<SendMessageResult>>();
Log.Logger.Information("机器人消息发送结果:{result}", result.Ok);
return result;
}
catch (Exception e)
{
Log.Logger.Error(e, "机器人发送消息失败!");
}
return null;
}
}

public class TelegramBotInfo
{
[JsonProperty("id")]
public long Id { get; set; }

[JsonProperty("is_bot")]
public bool IsBot { get; set; }

[JsonProperty("first_name")]
public string FirstName { get; set; }

[JsonProperty("username")]
public string Username { get; set; }

[JsonProperty("can_join_groups")]
public bool CanJoinGroups { get; set; }

[JsonProperty("can_read_all_group_messages")]
public bool CanReadAllGroupMessages { get; set; }

[JsonProperty("supports_inline_queries")]
public bool SupportsInlineQueries { get; set; }
}
public class MessageChat
{
[JsonProperty("id")]
public int Id { get; set; }

[JsonProperty("first_name")]
public string FirstName { get; set; }

[JsonProperty("username")]
public string Username { get; set; }

[JsonProperty("type")]
public string Type { get; set; }
}

public class MessageFrom
{
[JsonProperty("id")]
public long Id { get; set; }

[JsonProperty("is_bot")]
public bool IsBot { get; set; }

[JsonProperty("first_name")]
public string FirstName { get; set; }

[JsonProperty("username")]
public string Username { get; set; }
}

public class SendMessageResult
{
[JsonProperty("message_id")]
public int MessageId { get; set; }

[JsonProperty("from")]
public MessageFrom From { get; set; }

[JsonProperty("chat")]
public MessageChat Chat { get; set; }

[JsonProperty("date")]
public int Date { get; set; }

[JsonProperty("text")]
public string Text { get; set; }
}
public class TelegramResult<T>
{
[JsonProperty("ok")]
public bool Ok { get; set; }

[JsonProperty("result")]
public T Result { get; set; }
}
}
7 changes: 2 additions & 5 deletions src/TokenPay/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,6 @@
o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

builder.Services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
var connectionString = Configuration.GetConnectionString("DB");

IFreeSql fsql = new FreeSqlBuilder()
Expand Down Expand Up @@ -84,10 +80,11 @@

if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseExceptionHandler("/error");
}
else
{
app.UseExceptionHandler("/error-development");
app.UseSwagger();
app.UseSwaggerUI();
}
Expand Down
3 changes: 2 additions & 1 deletion src/TokenPay/TokenPay.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<SatelliteResourceLanguages>en;zh</SatelliteResourceLanguages>
<NoWarn>1591;</NoWarn>
</PropertyGroup>

Expand All @@ -22,7 +23,7 @@
<PackageReference Include="FreeSql.Provider.Sqlite" Version="3.2.669" />
<PackageReference Include="FreeSql.Repository" Version="3.2.669" />
<PackageReference Include="HDWallet.Tron" Version="0.7.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.8" ExcludeAssets="All"/>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.8" ExcludeAssets="All" />
<PackageReference Include="NokitaKaze.Base58Check" Version="0.4.2" />
<PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
<PackageReference Include="Serilog.Sinks.Exceptionless" Version="3.1.5" />
Expand Down
5 changes: 3 additions & 2 deletions src/TokenPay/Views/Home/Pay.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ else
此订单过期时间为:<span class="text-danger">@ViewData["ExpireTime"]</span>
</div>
</div>
}
@section Scripts{

@section Scripts{
<script>
let Time;
$(() => {
Expand Down Expand Up @@ -66,4 +66,5 @@ else
})
}
</script>
}
}
3 changes: 2 additions & 1 deletion src/TokenPay/appsettings.Example.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
//"TRON-Address": [ "Txxxxxx1", "Txxxxxx2" ], // UseDynamicAddress设为false时在此配置收款地址
"OnlyConfirmed": true, //默认仅查询已确认的数据,如果想要回调更快,可以设置为false
"NotifyTimeOut": 3, //异步通知超时时间
"NotifyKey": "666666", //异步通知密钥,请务必修改此密钥为随机字符串,脸滚键盘即可!!!
"ApiToken": "666666", //异步通知密钥,请务必修改此密钥为随机字符串,脸滚键盘即可!!!
//"WebSiteUrl": "http://token-pay.xxxxx.com", //配置服务器外网域名,一般不需要配置,能自动识别,如识别不正确请手动配置
"Telegram": {
"AdminUserId": 12345678, // 你的账号ID,如不知道ID,可给https://t.me/EShopFakaBot 发送 /me 获取用户ID
"BotToken": "1234567890:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" //从https://t.me/BotFather 创建机器人时,会给你BotToken
Expand Down

0 comments on commit c7776b4

Please sign in to comment.