Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94ba4b7c5b | ||
|
|
14644e00a5 | ||
|
|
be2ef02923 | ||
|
|
6ccd93a161 | ||
|
|
2edf71dee1 | ||
|
|
86251ac054 | ||
|
|
2f4915a808 | ||
|
|
a596ebc875 | ||
|
|
5e7f9ca701 | ||
|
|
0f4346cd5f | ||
|
|
c4d5e20c7a | ||
|
|
56bf320588 | ||
|
|
e6f8112df2 | ||
|
|
30eb6659d8 | ||
|
|
240da52d11 | ||
|
|
a45003ce3d | ||
|
|
f9bdf1f18a | ||
|
|
a5467d3fbb | ||
|
|
f866db9f1b | ||
|
|
b8df9d1d72 | ||
|
|
0e1e22cebb | ||
|
|
9cfd4b6e1c | ||
|
|
8c4ead0169 | ||
|
|
2992a1f032 | ||
|
|
9e7707588f | ||
|
|
0db728dc52 | ||
|
|
6a2f3b6d6e | ||
|
|
e906090ba6 | ||
|
|
077070b2cb |
+7
-2
@@ -1,9 +1,14 @@
|
||||
# 监听地址,格式为 ip:port,例如 :8080
|
||||
LISTEN=127.0.0.1:8080
|
||||
|
||||
# 日志文件保存路径
|
||||
LOG=/var/log/bepusdt/
|
||||
|
||||
# SQLite 数据库文件路径(如果使用 MySQL,此项可忽略)
|
||||
SQLITE=/var/lib/bepusdt/sqlite.db
|
||||
# MySQL 数据库连接字符串(留空则使用 SQLite)
|
||||
# 格式:user:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local
|
||||
|
||||
# MySQL 数据库
|
||||
# MYSQL_DSN=user:password@tcp(127.0.0.1:3306)/bepusdt?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s&readTimeout=10s&writeTimeout=10s
|
||||
|
||||
# PostgreSQL 数据库
|
||||
# POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3
|
||||
@@ -19,6 +19,8 @@ body:
|
||||
required: true
|
||||
- label: 我明白任何人针对我提交的问题没有义务提供帮助,包括项目维护者。
|
||||
required: true
|
||||
- label: 我没有阅读这个清单,只是闭眼选中了所有的复选框,请关闭这个 Issue 。
|
||||
required: true
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: 问题类型
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 30
|
||||
days-before-issue-stale: 3
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "此议题由于30天内没有任何活动,现在标记为过时。"
|
||||
|
||||
@@ -49,6 +49,8 @@
|
||||
- ✅ 原生兼容`易支付`收单 接入便捷
|
||||
- ✅ 完整独立WEB后台 方便配置管理
|
||||
- ✅ 收银台支持中英适配 助力出海需求
|
||||
- ✅ 地址独占模式 底层支持不定额收款
|
||||
- ✅ 支持MQTT消息发布 交易信息即时广播
|
||||
- ✅ 快速迭代期 超多实用特性功能等你发现
|
||||
|
||||
## 🚀 快捷启动
|
||||
@@ -62,7 +64,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
|
||||
- 安装:[Docker](docs/docker/docker.md) [Linux](docs/linux/install.md) [1Panel](./docs/1panel/README.md) [宝塔](./docs/bt_panel/README.md)
|
||||
- 开发:[API对接](docs/api/api.md) [订单回调](docs/notify/readme.md) [Python](https://github.com/luoyanglang/bepusdt-python-sdk) [PHP](https://github.com/v03413/bepusdt-php-sdk)
|
||||
- 对接:[独角数卡](docs/api/dujiaoka/dujiaoka.md) [彩虹易支付](https://github.com/v03413/Epay-BEpusdt) [whmcs](https://github.com/v03413/whmcs-gateway-epusdt) [其它](docs/api/other.md)
|
||||
- 对接:[独角Next](docs/api/dujiao-next/dujiao-next.md) [彩虹易支付](https://github.com/v03413/Epay-BEpusdt) [whmcs](https://github.com/v03413/whmcs-gateway-epusdt) [其它](docs/api/other.md)
|
||||
- 其它:[https 配置](./docs/ssl.md) [时钟同步](docs/linux/systemd-timesyncd.md) [收银台修改](docs/payment-template/README.md)
|
||||
|
||||
## 🖼 功能截图
|
||||
@@ -78,6 +80,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
- [后台入口账密忘记重置教程](./docs/faq/login-reset.md)
|
||||
- [Telegram 通知 Chat ID 获取教程](docs/faq/telegram-chat-id.md)
|
||||
- [推荐配置提高 Tron 扫块稳定性‼️](./docs/tron-grid/readme.md)
|
||||
- [EVM RPC 节点稳定性说明指南‼️](./docs/faq/evm-rpc-endpoint.md)
|
||||
|
||||
## ⚠️ 重要提示
|
||||
|
||||
@@ -91,7 +94,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
|
||||
## 🙏 致谢
|
||||
|
||||
- [Epusdt](https://github.com/assimon/epusdt)
|
||||
- [EPusdt](./docs/faq/epusdt.md)
|
||||
|
||||
## 🌟 Star 历史
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ var MySQLDSNFlag = &cli.StringFlag{
|
||||
Sources: cli.EnvVars("MYSQL_DSN"),
|
||||
}
|
||||
|
||||
var PostgresDSNFlag = &cli.StringFlag{
|
||||
Name: "postgres",
|
||||
Value: "",
|
||||
Usage: "PostgreSQL 数据库连接字符串 (DSN),例如: postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3",
|
||||
Sources: cli.EnvVars("POSTGRESQL_DSN"),
|
||||
}
|
||||
|
||||
var LogFlag = &cli.StringFlag{
|
||||
Name: "log",
|
||||
Value: "/var/log/bepusdt/",
|
||||
|
||||
+4
-3
@@ -15,11 +15,12 @@ import (
|
||||
var Reset = &cli.Command{
|
||||
Name: "reset",
|
||||
Usage: "忘记密码时,此命令可重置账号密码登录入口",
|
||||
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag},
|
||||
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag, PostgresDSNFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
dsn := c.String("mysql")
|
||||
mysql := c.String("mysql")
|
||||
postgres := c.String("postgres")
|
||||
sqlite := c.String("sqlite")
|
||||
if err := model.Init(sqlite, dsn); err != nil {
|
||||
if err := model.Init(sqlite, mysql, postgres); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -27,11 +27,12 @@ import (
|
||||
var Start = &cli.Command{
|
||||
Name: "start",
|
||||
Usage: "启动收款网关",
|
||||
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag, LogFlag, ListenFlag},
|
||||
Flags: []cli.Flag{SQLiteFlag, MySQLDSNFlag, PostgresDSNFlag, LogFlag, ListenFlag},
|
||||
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
|
||||
dsn := c.String("mysql")
|
||||
mysql := c.String("mysql")
|
||||
postgres := c.String("postgres")
|
||||
sqlite := c.String("sqlite")
|
||||
if err := model.Init(sqlite, dsn); err != nil {
|
||||
if err := model.Init(sqlite, mysql, postgres); err != nil {
|
||||
return ctx, fmt.Errorf("数据库初始化失败 %w", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
Secret = "BEpusdt, a more user-friendly personal cryptocurrency payment gateway!"
|
||||
AdminTokenK = "admin_token"
|
||||
AdminSecureK = "admin_secure"
|
||||
)
|
||||
|
||||
@@ -65,7 +65,7 @@ func (Conf) Del(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
model.Db.Where("`k` = ?", req.Key).Delete(&model.Conf{})
|
||||
model.Db.Where("k = ?", req.Key).Delete(&model.Conf{})
|
||||
|
||||
base.Ok(ctx, "删除成功")
|
||||
}
|
||||
@@ -79,7 +79,7 @@ func (Conf) Gets(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
var items = make([]model.Conf, 0)
|
||||
model.Db.Where("`k` IN ?", req.Keys).Find(&items)
|
||||
model.Db.Where("k IN ?", req.Keys).Find(&items)
|
||||
|
||||
var data = gin.H{}
|
||||
for _, item := range items {
|
||||
@@ -119,7 +119,7 @@ func (Conf) Sets(ctx *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
model.Db.Where("`k` IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Where("k IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Create(&data)
|
||||
|
||||
defer model.RefreshC()
|
||||
@@ -136,7 +136,7 @@ func (Conf) Notifier(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
var keys = []string{string(model.NotifierChannel), string(model.NotifierParams)}
|
||||
model.Db.Where("`k` IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Where("k IN ?", keys).Delete(&model.Conf{})
|
||||
model.Db.Create(&[]model.Conf{
|
||||
{K: model.NotifierChannel, V: req.Channel},
|
||||
{K: model.NotifierParams, V: string(req.Params)},
|
||||
|
||||
@@ -69,6 +69,17 @@ func (e Epay) Submit(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(data.NotifyURL) {
|
||||
ctx.String(200, "notify_url 地址不合法")
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(data.ReturnURL) {
|
||||
ctx.String(200, "return_url 地址不合法")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
money, err := decimal.NewFromString(data.Money)
|
||||
if err != nil {
|
||||
ctx.String(200, "参数 money 解析错误,"+err.Error())
|
||||
@@ -76,7 +87,7 @@ func (e Epay) Submit(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var order, err2 = model.BuildOrder(model.OrderParams{
|
||||
var order, err2 = model.StartBuildOrder(model.OrderParams{
|
||||
Money: money,
|
||||
ApiType: model.OrderApiTypeEpay,
|
||||
Address: data.Address,
|
||||
|
||||
@@ -21,11 +21,11 @@ import (
|
||||
type Epusdt struct{}
|
||||
|
||||
type createReq struct {
|
||||
Amount float64 `json:"amount" binding:"required"`
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
NotifyURL string `json:"notify_url" binding:"required"`
|
||||
RedirectURL string `json:"redirect_url" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
TradeType string `json:"trade_type"`
|
||||
@@ -35,11 +35,11 @@ type createReq struct {
|
||||
}
|
||||
|
||||
type createOrderReq struct {
|
||||
Amount float64 `json:"amount" binding:"required"`
|
||||
OrderID string `json:"order_id" binding:"required"`
|
||||
NotifyURL string `json:"notify_url" binding:"required"`
|
||||
RedirectURL string `json:"redirect_url" binding:"required"`
|
||||
Signature string `json:"signature" binding:"required"`
|
||||
Amount float64 `json:"amount"`
|
||||
Name string `json:"name"`
|
||||
Fiat model.Fiat `json:"fiat"`
|
||||
Currencies string `json:"currencies"`
|
||||
@@ -62,7 +62,7 @@ type methodsReq struct {
|
||||
Currency string `json:"currency"`
|
||||
}
|
||||
|
||||
type methodItem struct {
|
||||
type PaymentItem struct {
|
||||
Amount string `json:"amount"`
|
||||
ActualAmount string `json:"actual_amount"`
|
||||
Fiat string `json:"fiat"`
|
||||
@@ -146,6 +146,17 @@ func (Epusdt) CreateOrder(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(req.NotifyURL) {
|
||||
ctx.JSON(200, respFailJson("notify_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(req.RedirectURL) {
|
||||
ctx.JSON(200, respFailJson("redirect_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
@@ -170,7 +181,6 @@ func (Epusdt) CreateOrder(ctx *gin.Context) {
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("CreateOrder: order create failed: %s", err.Error())))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -186,6 +196,7 @@ func (Epusdt) CreateOrder(ctx *gin.Context) {
|
||||
"amount": order.Money,
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": model.CheckoutCashier(host, order.TradeId),
|
||||
"network": GetPaymentItem("", order),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -261,6 +272,17 @@ func (Epusdt) CreateTransaction(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !utils.IsAllowedCallbackURL(req.NotifyURL) {
|
||||
ctx.JSON(200, respFailJson("notify_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
if !utils.IsAllowedCallbackURL(req.RedirectURL) {
|
||||
ctx.JSON(200, respFailJson("redirect_url 地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if req.Fiat == "" {
|
||||
req.Fiat = model.CNY
|
||||
}
|
||||
@@ -268,18 +290,19 @@ func (Epusdt) CreateTransaction(ctx *gin.Context) {
|
||||
req.TradeType = string(model.UsdtTrc20)
|
||||
}
|
||||
|
||||
order, err := model.BuildOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
Address: req.Address,
|
||||
OrderId: req.OrderID,
|
||||
TradeType: model.TradeType(req.TradeType),
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Rate: req.Rate,
|
||||
Fiat: req.Fiat,
|
||||
order, err := model.StartBuildOrder(model.OrderParams{
|
||||
Money: decimal.NewFromFloat(req.Amount),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
Address: req.Address,
|
||||
AddressLocked: req.Amount == 0,
|
||||
OrderId: req.OrderID,
|
||||
TradeType: model.TradeType(req.TradeType),
|
||||
RedirectUrl: req.RedirectURL,
|
||||
NotifyUrl: req.NotifyURL,
|
||||
Name: req.Name,
|
||||
Timeout: req.Timeout,
|
||||
Rate: req.Rate,
|
||||
Fiat: req.Fiat,
|
||||
})
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单创建失败:%s", err.Error())))
|
||||
@@ -393,6 +416,7 @@ func (Epusdt) CheckoutCashier(ctx *gin.Context) {
|
||||
"name": order.Name,
|
||||
"money": order.Money,
|
||||
"fiat": order.Fiat,
|
||||
"network": GetPaymentItem("", order),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -441,10 +465,15 @@ func (Epusdt) GetPaymentMethods(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 强制使用订单的法币类型
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"methods": GetPaymentItem(model.Crypto(req.Currency), order),
|
||||
}))
|
||||
}
|
||||
|
||||
func GetPaymentItem(crypto model.Crypto, order model.Order) []PaymentItem {
|
||||
fiat := order.Fiat
|
||||
|
||||
var methods []methodItem
|
||||
var methods = make([]PaymentItem, 0)
|
||||
allTrades := model.GetAllTradeConfig()
|
||||
|
||||
// 解析限定币种
|
||||
@@ -463,7 +492,7 @@ func (Epusdt) GetPaymentMethods(ctx *gin.Context) {
|
||||
|
||||
for tradeTypeStr, conf := range allTrades {
|
||||
// 如果指定了货币,则进行过滤
|
||||
if req.Currency != "" && string(conf.Crypto) != req.Currency {
|
||||
if crypto != "" && conf.Crypto != crypto {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -478,10 +507,7 @@ func (Epusdt) GetPaymentMethods(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// 检查是否有可用钱包
|
||||
var count int
|
||||
tradeType := model.TradeType(tradeTypeStr)
|
||||
count = len(model.GetAvailableAddress(tradeType))
|
||||
|
||||
count := len(model.GetAvailableAddress(model.TradeType(tradeTypeStr)))
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
@@ -506,16 +532,15 @@ func (Epusdt) GetPaymentMethods(ctx *gin.Context) {
|
||||
if actualAmount.LessThan(atom) {
|
||||
actualAmount = atom
|
||||
}
|
||||
actualAmountStr := actualAmount.String()
|
||||
|
||||
methods = append(methods, methodItem{
|
||||
methods = append(methods, PaymentItem{
|
||||
Amount: order.Money,
|
||||
ActualAmount: actualAmountStr,
|
||||
ActualAmount: actualAmount.String(),
|
||||
Fiat: string(fiat),
|
||||
ExchangeRate: rate.String(),
|
||||
Currency: string(conf.Crypto),
|
||||
Network: string(conf.Network),
|
||||
TokenNetName: string(conf.NetworkName),
|
||||
TokenNetName: conf.NetworkName,
|
||||
TokenCustomName: "", // 暂为空
|
||||
IsPopular: false, // 暂为 false
|
||||
})
|
||||
@@ -529,9 +554,7 @@ func (Epusdt) GetPaymentMethods(ctx *gin.Context) {
|
||||
return methods[i].Network < methods[j].Network
|
||||
})
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"methods": methods,
|
||||
}))
|
||||
return methods
|
||||
}
|
||||
|
||||
func respFailJson(message string) gin.H {
|
||||
|
||||
+65
-36
@@ -15,10 +15,41 @@ import (
|
||||
)
|
||||
|
||||
var confCache sync.Map
|
||||
var defaultConf = map[ConfKey]string{
|
||||
ApiAppUri: "",
|
||||
RateSyncInterval: "3600",
|
||||
AtomUSDT: "0.01",
|
||||
AtomUSDC: "0.01",
|
||||
AtomTRX: "0.01",
|
||||
AtomBNB: "0.00001",
|
||||
AtomETH: "0.000001",
|
||||
MonitorMinAmount: "0.01",
|
||||
PaymentMinAmount: "0.01",
|
||||
PaymentMaxAmount: "99999",
|
||||
RpcEndpointTron: "grpc.trongrid.io:50051",
|
||||
RpcEndpointBsc: "https://binance-smart-chain-public.nodies.app/",
|
||||
RpcEndpointSolana: "https://solana-rpc.publicnode.com/",
|
||||
RpcEndpointXlayer: "https://xlayerrpc.okx.com/",
|
||||
RpcEndpointPolygon: "https://polygon-public.nodies.app/",
|
||||
RpcEndpointArbitrum: "https://arb1.arbitrum.io/rpc",
|
||||
RpcEndpointEthereum: "https://ethereum-public.nodies.app/",
|
||||
RpcEndpointBase: "https://base-public.nodies.app/",
|
||||
RpcEndpointAptos: "https://aptos-rest.publicnode.com/",
|
||||
RpcEndpointPlasma: "https://rpc.plasma.to/",
|
||||
NotifyMaxRetry: "10",
|
||||
BlockHeightMaxDiff: "1000",
|
||||
BlockOffsetConfirm: "0",
|
||||
PaymentTimeout: "1200", // 20分钟
|
||||
PaymentMatchMode: string(Classic),
|
||||
SystemInstallLock: "0",
|
||||
RateSyncCoingeckoApiUrl: "https://api.coingecko.com",
|
||||
RateSyncHistoryDays: "30",
|
||||
MqttTopicPrefix: "bepusdt",
|
||||
}
|
||||
|
||||
type Conf struct {
|
||||
K ConfKey `gorm:"column:k;type:varchar(32);not null;primaryKey" json:"key"`
|
||||
V string `gorm:"column:v;type:varchar(255);not null" json:"val"`
|
||||
V string `gorm:"column:v;type:varchar(512);not null" json:"val"`
|
||||
}
|
||||
|
||||
func (c Conf) TableName() string {
|
||||
@@ -28,7 +59,7 @@ func (c Conf) TableName() string {
|
||||
|
||||
func SetK(k ConfKey, v string) {
|
||||
if err = Db.Transaction(func(db *gorm.DB) error {
|
||||
if err2 := db.Where("`k` = ?", k).Delete(&Conf{}).Error; err2 != nil {
|
||||
if err2 := db.Where("k = ?", k).Delete(&Conf{}).Error; err2 != nil {
|
||||
|
||||
return err2
|
||||
}
|
||||
@@ -122,45 +153,19 @@ func ConfInit() {
|
||||
var password = hash[20:30]
|
||||
var encrypt, _ = bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
var data = map[ConfKey]string{
|
||||
ApiAppUri: "",
|
||||
ApiAuthToken: token,
|
||||
AdminSecure: secure,
|
||||
AdminUsername: username,
|
||||
AdminPassword: string(encrypt),
|
||||
RateSyncInterval: "3600",
|
||||
AtomUSDT: "0.01",
|
||||
AtomUSDC: "0.01",
|
||||
AtomTRX: "0.01",
|
||||
AtomBNB: "0.00001",
|
||||
AtomETH: "0.000001",
|
||||
MonitorMinAmount: "0.01",
|
||||
PaymentMinAmount: "0.01",
|
||||
PaymentMaxAmount: "99999",
|
||||
RpcEndpointTron: "grpc.trongrid.io:50051",
|
||||
RpcEndpointBsc: "https://binance-smart-chain-public.nodies.app/",
|
||||
RpcEndpointSolana: "https://solana-rpc.publicnode.com/",
|
||||
RpcEndpointXlayer: "https://xlayerrpc.okx.com/",
|
||||
RpcEndpointPolygon: "https://polygon-public.nodies.app/",
|
||||
RpcEndpointArbitrum: "https://arb1.arbitrum.io/rpc",
|
||||
RpcEndpointEthereum: "https://ethereum-public.nodies.app/",
|
||||
RpcEndpointBase: "https://base-public.nodies.app/",
|
||||
RpcEndpointAptos: "https://aptos-rest.publicnode.com/",
|
||||
RpcEndpointPlasma: "https://rpc.plasma.to/",
|
||||
NotifyMaxRetry: "10",
|
||||
BlockHeightMaxDiff: "1000",
|
||||
BlockOffsetConfirm: "0",
|
||||
PaymentTimeout: "1200", // 20分钟
|
||||
PaymentStaticPath: "",
|
||||
PaymentMatchMode: string(Classic),
|
||||
SystemInstallLock: "0",
|
||||
RateSyncCoingeckoApiUrl: "https://api.coingecko.com",
|
||||
RateSyncCoingeckoApiKey: "",
|
||||
ApiAuthToken: token,
|
||||
AdminSecret: utils.StrSha256(hash),
|
||||
AdminSecure: secure,
|
||||
AdminUsername: username,
|
||||
AdminPassword: string(encrypt),
|
||||
}
|
||||
|
||||
var rows = make([]Conf, 0)
|
||||
for k, v := range data {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
for k, v := range defaultConf {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("╔═══════════════════════════════════════════════════════════════════════")
|
||||
@@ -220,3 +225,27 @@ func GetInstallInfo() gin.H {
|
||||
|
||||
return gin.H{}
|
||||
}
|
||||
|
||||
func GetTronGridApiKeys() []string {
|
||||
return strings.Split(GetK(RpcEndpointTronGridApiKey), ",")
|
||||
}
|
||||
|
||||
func FillDefaultConf() {
|
||||
var existKeys []string
|
||||
Db.Model(&Conf{}).Pluck("k", &existKeys)
|
||||
|
||||
existSet := make(map[ConfKey]struct{}, len(existKeys))
|
||||
for _, k := range existKeys {
|
||||
existSet[ConfKey(k)] = struct{}{}
|
||||
}
|
||||
|
||||
var rows []Conf
|
||||
for k, v := range defaultConf {
|
||||
if _, ok := existSet[k]; !ok {
|
||||
rows = append(rows, Conf{K: k, V: v})
|
||||
}
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
Db.Create(&rows)
|
||||
}
|
||||
}
|
||||
|
||||
+14
-3
@@ -31,6 +31,7 @@ const (
|
||||
AdminUsername ConfKey = "admin_username"
|
||||
AdminPassword ConfKey = "admin_password"
|
||||
AdminSecure ConfKey = "admin_secure"
|
||||
AdminSecret ConfKey = "admin_secret"
|
||||
AdminLoginIP ConfKey = "admin_login_ip"
|
||||
AdminLoginAt ConfKey = "admin_login_at"
|
||||
|
||||
@@ -65,9 +66,19 @@ const (
|
||||
RateSyncCoingeckoApiUrl ConfKey = "rate_sync_coingecko_api_url" // 汇率同步 Coingecko Api URL
|
||||
RateSyncCoingeckoApiKey ConfKey = "rate_sync_coingecko_api_key" // 汇率同步 Coingecko Api Key
|
||||
RateSyncInterval ConfKey = "rate_sync_interval" // 汇率同步间隔,单位秒
|
||||
NotifyMaxRetry ConfKey = "notify_max_retry" // 最大重试次数,订单回调失败
|
||||
BlockHeightMaxDiff ConfKey = "block_height_max_diff" // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
BlockOffsetConfirm ConfKey = "block_offset_confirm" // 区块偏移确认数,扫描时以当前区块高度减去此偏移量为准,避免重链导致的订单回调失败
|
||||
RateSyncHistoryDays ConfKey = "rate_sync_history_days" // 历史汇率保存天数
|
||||
|
||||
NotifyMaxRetry ConfKey = "notify_max_retry" // 最大重试次数,订单回调失败
|
||||
BlockHeightMaxDiff ConfKey = "block_height_max_diff" // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
BlockOffsetConfirm ConfKey = "block_offset_confirm" // 区块偏移确认数,扫描时以当前区块高度减去此偏移量为准,避免重链导致的订单回调失败
|
||||
|
||||
MqttHost ConfKey = "mqtt_host"
|
||||
MqttPort ConfKey = "mqtt_port"
|
||||
MqttUser ConfKey = "mqtt_user"
|
||||
MqttPass ConfKey = "mqtt_pass"
|
||||
MqttPublishQos ConfKey = "mqtt_publish_qos"
|
||||
MqttTopicPrefix ConfKey = "mqtt_topic_prefix" // 消息发布 Topic 路径前缀
|
||||
MqttNetworks ConfKey = "mqtt_networks" // 需要持续监控的区块网络
|
||||
|
||||
NotifierParams ConfKey = "notifier_params" // 通知参数 (token, chat_id, email
|
||||
NotifierChannel ConfKey = "notifier_channel" // 通知渠道 (telegram, wechat, email
|
||||
|
||||
+7
-13
@@ -6,17 +6,18 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var localLocation = time.Local
|
||||
|
||||
type Datetime time.Time
|
||||
|
||||
func (d *Datetime) MarshalJSON() ([]byte, error) {
|
||||
tTime := time.Time(*d)
|
||||
tTime := time.Time(*d).In(localLocation)
|
||||
return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
|
||||
}
|
||||
|
||||
func (d Datetime) Value() (driver.Value, error) {
|
||||
var zeroTime time.Time
|
||||
tlt := time.Time(d)
|
||||
// 判断给定时间是否和默认零时间的时间戳相同
|
||||
if tlt.UnixNano() == zeroTime.UnixNano() {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -26,34 +27,27 @@ func (d Datetime) Value() (driver.Value, error) {
|
||||
func (d *Datetime) Scan(v interface{}) error {
|
||||
if value, ok := v.(time.Time); ok {
|
||||
*d = Datetime(value)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("can not convert %v to timestamp", v)
|
||||
}
|
||||
|
||||
func (d *Datetime) String() string {
|
||||
|
||||
return time.Time(*d).Format(time.DateTime)
|
||||
return time.Time(*d).In(localLocation).Format(time.DateTime)
|
||||
}
|
||||
|
||||
func (d *Datetime) Year() string {
|
||||
|
||||
return time.Time(*d).Format("2006")
|
||||
return time.Time(*d).In(localLocation).Format("2006")
|
||||
}
|
||||
|
||||
func (d *Datetime) Before(u time.Time) bool {
|
||||
|
||||
return time.Time(*d).Before(u)
|
||||
}
|
||||
|
||||
func (d *Datetime) Time() time.Time {
|
||||
|
||||
return time.Time(*d)
|
||||
return time.Time(*d).In(localLocation)
|
||||
}
|
||||
|
||||
func (d *Datetime) Format(layout string) string {
|
||||
|
||||
return time.Time(*d).Format(layout)
|
||||
return time.Time(*d).In(localLocation).Format(layout)
|
||||
}
|
||||
|
||||
+51
-6
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -19,14 +20,16 @@ type Id struct {
|
||||
}
|
||||
|
||||
type AutoTimeAt struct {
|
||||
CreatedAt *Datetime `gorm:"column:created_at;type:Datetime;not null;comment:记录创建时间;index" json:"created_at"`
|
||||
UpdatedAt *Datetime `gorm:"column:updated_at;type:Datetime;not null;comment:最后更新时间" json:"updated_at"`
|
||||
CreatedAt *Datetime `gorm:"column:created_at;not null;comment:记录创建时间;index" json:"created_at"`
|
||||
UpdatedAt *Datetime `gorm:"column:updated_at;not null;comment:最后更新时间" json:"updated_at"`
|
||||
}
|
||||
|
||||
func Init(path, dsn string) error {
|
||||
if dsn != "" {
|
||||
|
||||
return initMySQL(dsn)
|
||||
func Init(path, mysql, postgres string) error {
|
||||
if postgres != "" {
|
||||
return initPostgres(postgres)
|
||||
}
|
||||
if mysql != "" {
|
||||
return initMySQL(mysql)
|
||||
}
|
||||
|
||||
return initSqlite(path)
|
||||
@@ -73,6 +76,7 @@ func initSqlite(path string) error {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
@@ -115,6 +119,47 @@ func initMySQL(dsn string) error {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func initPostgres(dsn string) error {
|
||||
// 首次启动可能出现 SLOW SQL 告警,这是由于连接池首次连接预热引起的,后续连接将正常
|
||||
|
||||
var err error
|
||||
Db, err = gorm.Open(postgres.New(postgres.Config{DSN: dsn, PreferSimpleProtocol: true}), &gorm.Config{})
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
{
|
||||
sqlDB, err := Db.DB()
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
sqlDB.SetMaxOpenConns(100)
|
||||
sqlDB.SetConnMaxLifetime(30 * time.Minute)
|
||||
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
|
||||
}
|
||||
|
||||
if err = AutoMigrate(); err != nil {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
var count int64
|
||||
Db.Model(&Conf{}).Count(&count)
|
||||
if count == 0 {
|
||||
ConfInit()
|
||||
}
|
||||
|
||||
FillDefaultConf()
|
||||
RefreshC()
|
||||
|
||||
return nil
|
||||
|
||||
+40
-16
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
@@ -52,8 +51,6 @@ const (
|
||||
OrderApiTypeAdmin = "admin" // 管理后台
|
||||
)
|
||||
|
||||
var calcMutex sync.Mutex
|
||||
|
||||
type Order struct {
|
||||
Id
|
||||
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"`
|
||||
@@ -67,17 +64,18 @@ type Order struct {
|
||||
Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"`
|
||||
Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"`
|
||||
FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"`
|
||||
Status int `gorm:"column:status;type:tinyint(1);not null;default:1;index;comment:交易状态" json:"status"`
|
||||
AddressLocked bool `gorm:"column:address_locked;not null;default:false;comment:地址锁定 1:独占 0:共享" json:"address_locked"`
|
||||
Status int `gorm:"column:status;not null;default:1;index;comment:交易状态" json:"status"`
|
||||
Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"`
|
||||
ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'epusdt';comment:API类型" json:"api_type"`
|
||||
ReturnUrl string `gorm:"column:return_url;type:varchar(255);not null;default:'';comment:同步地址" json:"return_url"`
|
||||
NotifyUrl string `gorm:"column:notify_url;type:varchar(255);not null;default:'';comment:异步地址" json:"notify_url"`
|
||||
NotifyNum int `gorm:"column:notify_num;type:int(11);not null;default:0;comment:回调次数" json:"notify_num"`
|
||||
NotifyState int `gorm:"column:notify_state;type:tinyint(1);not null;default:0;comment:回调状态 1:成功 0:失败" json:"notify_state"`
|
||||
NotifyNum int `gorm:"column:notify_num;not null;default:0;comment:回调次数" json:"notify_num"`
|
||||
NotifyState int `gorm:"column:notify_state;not null;default:0;comment:回调状态 1:成功 0:失败" json:"notify_state"`
|
||||
RefHash string `gorm:"column:ref_hash;type:varchar(128);not null;default:'';index;comment:交易哈希" json:"ref_hash"`
|
||||
RefBlockNum int64 `gorm:"column:ref_block_num;type:varchar(64);not null;default:0;comment:区块索引" json:"ref_block_num"`
|
||||
ExpiredAt time.Time `gorm:"column:expired_at;type:datetime;not null;comment:失效时间" json:"expired_at"`
|
||||
ConfirmedAt *time.Time `gorm:"column:confirmed_at;type:datetime;not null;comment:交易确认时间" json:"confirmed_at"`
|
||||
RefBlockNum int `gorm:"column:ref_block_num;not null;default:0;comment:区块索引" json:"ref_block_num"`
|
||||
ExpiredAt time.Time `gorm:"column:expired_at;not null;comment:失效时间" json:"expired_at"`
|
||||
ConfirmedAt *time.Time `gorm:"column:confirmed_at;not null;comment:交易确认时间" json:"confirmed_at"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
@@ -105,12 +103,17 @@ func (o *Order) SetFailed() {
|
||||
Db.Save(o)
|
||||
}
|
||||
|
||||
func (o *Order) MarkConfirming(blockNum int64, from, hash string, at time.Time) {
|
||||
func (o *Order) MarkConfirming(blockNum int, from, hash string, at time.Time, amount decimal.Decimal) {
|
||||
o.FromAddress = from
|
||||
o.ConfirmedAt = &at
|
||||
o.RefHash = hash
|
||||
o.RefBlockNum = blockNum
|
||||
o.Status = OrderStatusConfirming
|
||||
if o.AddressLocked {
|
||||
rate, _ := decimal.NewFromString(o.Rate)
|
||||
o.Amount = amount.String()
|
||||
o.Money = rate.Mul(amount).String()
|
||||
}
|
||||
|
||||
Db.Save(o)
|
||||
}
|
||||
@@ -185,28 +188,31 @@ func GetNotifyFailedTradeOrders() ([]Order, error) {
|
||||
}
|
||||
|
||||
// CalcTradeAmount 计算当前实际可用的交易金额
|
||||
func CalcTradeAmount(address []string, rate, money decimal.Decimal, t TradeType) (string, string, error) {
|
||||
calcMutex.Lock()
|
||||
defer calcMutex.Unlock()
|
||||
func CalcTradeAmount(address []string, rate decimal.Decimal, p OrderParams) (string, string, error) {
|
||||
if p.AddressLocked {
|
||||
return LockTradeAddress(address, p.TradeType)
|
||||
}
|
||||
|
||||
var orders []Order
|
||||
lock := make(map[string]bool)
|
||||
status := []int{OrderStatusConfirming, OrderStatusWaiting}
|
||||
Db.Where("status in (?) and trade_type = ?", status, t).Find(&orders)
|
||||
Db.Where("status in (?) and trade_type = ?", status, p.TradeType).Find(&orders)
|
||||
for _, order := range orders {
|
||||
lock[order.Address+order.Amount] = true
|
||||
}
|
||||
|
||||
atom, precision := GetAtomicity(t)
|
||||
atom, precision := GetAtomicity(p.TradeType)
|
||||
if rate.LessThanOrEqual(decimal.Zero) || precision <= 0 {
|
||||
return "", "", errors.New(fmt.Sprintf("[%v - %v]原子颗粒度计算异常,联系管理员处理!", atom, precision))
|
||||
}
|
||||
|
||||
amount := money.DivRound(rate, precision)
|
||||
amount := p.Money.DivRound(rate, precision)
|
||||
if amount.LessThan(atom) { // 低于最小原子精度,从最小原子精度开始计算
|
||||
amount = atom
|
||||
}
|
||||
|
||||
var i = 0
|
||||
var m = 100
|
||||
for {
|
||||
for _, addr := range address {
|
||||
k := addr + amount.String()
|
||||
@@ -219,9 +225,27 @@ func CalcTradeAmount(address []string, rate, money decimal.Decimal, t TradeType)
|
||||
|
||||
// 已经被占用,每次递增一个原子精度
|
||||
amount = amount.Add(atom)
|
||||
if i++; i > m {
|
||||
return "", "", errors.New("计算交易金额异常,联系管理员处理!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LockTradeAddress 检测交易地址,独占使用
|
||||
func LockTradeAddress(address []string, t TradeType) (string, string, error) {
|
||||
zero := decimal.Zero.String()
|
||||
status := []int{OrderStatusConfirming, OrderStatusWaiting}
|
||||
for _, addr := range address {
|
||||
var o Order
|
||||
Db.Where("address = ? and status in (?) and trade_type = ? and address_locked = ?", addr, status, t, true).Order("id desc").Limit(1).Find(&o)
|
||||
if o.ID == 0 {
|
||||
return addr, zero, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", zero, errors.New("暂无可用钱包地址")
|
||||
}
|
||||
|
||||
// CalcTradeExpiredAt 计算订单过期时间 最小180,最大3600,默认1200
|
||||
func CalcTradeExpiredAt(sec int64) time.Time {
|
||||
if sec >= 180 && sec <= 3600 {
|
||||
|
||||
+41
-45
@@ -25,6 +25,7 @@ type OrderParams struct {
|
||||
Rate string `json:"rate"` // 强制指定汇率
|
||||
Fiat Fiat `json:"fiat"` // 法币类型
|
||||
CurrencyLimit string `json:"currency_limit"` // 限定币种
|
||||
AddressLocked bool `json:"address_locked"` // 地址独占锁定
|
||||
}
|
||||
|
||||
type Trade struct {
|
||||
@@ -34,7 +35,9 @@ type Trade struct {
|
||||
Amount string
|
||||
}
|
||||
|
||||
func BuildOrder(p OrderParams) (Order, error) {
|
||||
var buildMutex sync.Mutex
|
||||
|
||||
func StartBuildOrder(p OrderParams) (Order, error) {
|
||||
var order Order
|
||||
|
||||
if p.Address != "" {
|
||||
@@ -47,18 +50,14 @@ func BuildOrder(p OrderParams) (Order, error) {
|
||||
}
|
||||
}
|
||||
if _, ok := registry[p.TradeType]; !ok {
|
||||
|
||||
return order, fmt.Errorf("不支持的交易类型:%s", p.TradeType)
|
||||
}
|
||||
if _, ok := supportFiat[p.Fiat]; !ok {
|
||||
|
||||
return order, fmt.Errorf("不支持的法币类型:%s", p.Fiat)
|
||||
}
|
||||
|
||||
maxAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMaxAmount)))
|
||||
minAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMinAmount)))
|
||||
if p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount) {
|
||||
|
||||
if !p.AddressLocked && (p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount)) {
|
||||
return order, fmt.Errorf("交易金额必须在 %s - %s 之间", minAmount.String(), maxAmount.String())
|
||||
}
|
||||
|
||||
@@ -67,50 +66,26 @@ func BuildOrder(p OrderParams) (Order, error) {
|
||||
return order, nil
|
||||
}
|
||||
|
||||
buildMutex.Lock()
|
||||
defer buildMutex.Unlock()
|
||||
|
||||
Db.Where("order_id = ?", p.OrderId).Order("id desc").Limit(1).Find(&order)
|
||||
if order.Status == OrderStatusSuccess || order.Status == OrderStatusConfirming {
|
||||
return order, nil
|
||||
}
|
||||
if order.Status == OrderStatusWaiting {
|
||||
return RebuildOrder(order, p)
|
||||
}
|
||||
|
||||
var lock sync.Mutex
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return order, err
|
||||
}
|
||||
|
||||
return NewOrder(p, data)
|
||||
return BuildOrder(p, data)
|
||||
}
|
||||
|
||||
func RebuildOrder(t Order, p OrderParams) (Order, error) {
|
||||
if p.OrderId == t.OrderId &&
|
||||
p.TradeType == t.TradeType &&
|
||||
p.Money.String() == t.Money &&
|
||||
p.Fiat == t.Fiat {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
var lock sync.Mutex
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
|
||||
t.Amount = data.Amount
|
||||
t.TradeType = p.TradeType
|
||||
t.Address = data.Address
|
||||
t.Crypto = data.Crypto
|
||||
t.Rate = fmt.Sprintf("%v", data.Rate)
|
||||
t.ExpiredAt = CalcTradeExpiredAt(p.Timeout)
|
||||
|
||||
return t, Db.Save(&t).Error
|
||||
}
|
||||
|
||||
func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
func BuildOrder(p OrderParams, data Trade) (Order, error) {
|
||||
tradeId, err := utils.GenerateTradeId()
|
||||
if err != nil {
|
||||
return Order{}, err
|
||||
@@ -126,6 +101,7 @@ func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
Amount: data.Amount,
|
||||
Money: p.Money.String(),
|
||||
Address: data.Address,
|
||||
AddressLocked: p.Money.IsZero(), // 零值订单,地址锁定 独占
|
||||
Status: OrderStatusWaiting,
|
||||
Name: p.Name,
|
||||
ApiType: p.ApiType,
|
||||
@@ -143,7 +119,6 @@ func NewOrder(p OrderParams, data Trade) (Order, error) {
|
||||
if tradeOrder.Name == "" {
|
||||
tradeOrder.Name = tradeOrder.OrderId
|
||||
}
|
||||
|
||||
if err = Db.Create(&tradeOrder).Error; err != nil {
|
||||
log.Error("订单创建失败:", err.Error())
|
||||
return Order{}, err
|
||||
@@ -181,7 +156,7 @@ func BuildTrade(p OrderParams) (Trade, error) {
|
||||
}
|
||||
|
||||
// 计算交易金额
|
||||
address, amount, err := CalcTradeAmount(wallet, rate, p.Money, p.TradeType)
|
||||
address, amount, err := CalcTradeAmount(wallet, rate, p)
|
||||
if err != nil {
|
||||
|
||||
return Trade{}, err
|
||||
@@ -195,13 +170,35 @@ func BuildTrade(p OrderParams) (Trade, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func RebuildOrder(t Order, p OrderParams) (Order, error) {
|
||||
if p.OrderId == t.OrderId && p.TradeType == t.TradeType && p.Money.String() == t.Money && p.Fiat == t.Fiat {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
data, err := BuildTrade(p)
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
|
||||
t.Fiat = p.Fiat
|
||||
t.Address = data.Address
|
||||
t.Crypto = data.Crypto
|
||||
t.Amount = data.Amount
|
||||
t.Money = p.Money.String()
|
||||
t.TradeType = p.TradeType
|
||||
t.Rate = fmt.Sprintf("%v", data.Rate)
|
||||
t.ExpiredAt = CalcTradeExpiredAt(p.Timeout)
|
||||
|
||||
return t, Db.Save(&t).Error
|
||||
}
|
||||
|
||||
// BuildPendingOrder 创建待支付订单(不锁定地址和汇率)
|
||||
func BuildPendingOrder(p OrderParams) (Order, error) {
|
||||
var order Order
|
||||
|
||||
maxAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMaxAmount)))
|
||||
minAmount := decimal.NewFromFloat(cast.ToFloat64(GetC(PaymentMinAmount)))
|
||||
if p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount) {
|
||||
if !p.Money.IsZero() && (p.Money.GreaterThan(maxAmount) || p.Money.LessThan(minAmount)) {
|
||||
return order, fmt.Errorf("交易金额必须在 %s - %s 之间", minAmount.String(), maxAmount.String())
|
||||
}
|
||||
|
||||
@@ -217,15 +214,14 @@ func BuildPendingOrder(p OrderParams) (Order, error) {
|
||||
if err == nil {
|
||||
crypto = c
|
||||
}
|
||||
} else if p.CurrencyLimit != "" {
|
||||
// 如果指定了唯一的币种限制,且不是黑名单模式,则使用该币种
|
||||
} else if p.CurrencyLimit != "" { // 如果指定了唯一的币种限制,且不是黑名单模式,则使用该币种
|
||||
cur := strings.ToUpper(p.CurrencyLimit)
|
||||
if !strings.Contains(cur, ",") && !strings.HasPrefix(cur, "-") {
|
||||
crypto = Crypto(cur)
|
||||
}
|
||||
}
|
||||
|
||||
return NewOrder(p, Trade{
|
||||
return BuildOrder(p, Trade{
|
||||
Crypto: crypto,
|
||||
Rate: decimal.Zero,
|
||||
Amount: "0",
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ type TronTransfer struct {
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType TradeType
|
||||
BlockNum int64
|
||||
BlockNum int
|
||||
}
|
||||
|
||||
type TronResource struct {
|
||||
|
||||
+2
-2
@@ -14,11 +14,11 @@ const (
|
||||
type Wallet struct {
|
||||
Id
|
||||
Name string `gorm:"column:name;type:varchar(32);not null;default:-';comment:名称" json:"name"`
|
||||
Status uint8 `gorm:"column:status;type:tinyint(1);not null;default:1;comment:地址状态" json:"status"`
|
||||
Status uint8 `gorm:"column:status;not null;default:1;comment:地址状态" json:"status"`
|
||||
Address string `gorm:"column:address;type:varchar(128);not null;index;comment:钱包地址" json:"address"`
|
||||
MatchAddr string `gorm:"column:match_addr;type:varchar(128);not null;uniqueIndex:idx_address;comment:匹配地址" json:"match_addr"`
|
||||
TradeType string `gorm:"column:trade_type;type:varchar(20);not null;uniqueIndex:idx_address;comment:交易类型" json:"trade_type"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;type:tinyint(1);not null;default:0;comment:其它通知" json:"other_notify"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;not null;default:0;comment:其它通知" json:"other_notify"`
|
||||
Remark string `gorm:"column:remark;type:varchar(255);not null;default:'';comment:备注" json:"remark"`
|
||||
AutoTimeAt
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
type activeConf struct {
|
||||
host string
|
||||
port string
|
||||
user string
|
||||
pass string
|
||||
}
|
||||
|
||||
var (
|
||||
client mqtt.Client
|
||||
mu sync.RWMutex
|
||||
curConf activeConf
|
||||
)
|
||||
|
||||
// Reload 按最新配置连接MQTT服务器
|
||||
func Reload() error {
|
||||
host := model.GetC(model.MqttHost)
|
||||
port := model.GetC(model.MqttPort)
|
||||
if host == "" || port == "" {
|
||||
return nil // 未配置 MQTT,跳过
|
||||
}
|
||||
|
||||
newConf := activeConf{
|
||||
host: host,
|
||||
port: port,
|
||||
user: model.GetC(model.MqttUser),
|
||||
pass: model.GetC(model.MqttPass),
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if newConf == curConf { // 配置未变更,无需重连
|
||||
return nil
|
||||
}
|
||||
|
||||
// 断开旧连接(给 250ms 优雅退出)
|
||||
if client != nil {
|
||||
client.Disconnect(250)
|
||||
log.Info("🔄 MQTT 配置变动,正在连接...")
|
||||
}
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
// 暂时只支持 tcp 模式
|
||||
opts.AddBroker(fmt.Sprintf("tcp://%s:%s", newConf.host, newConf.port))
|
||||
opts.SetUsername(newConf.user)
|
||||
opts.SetPassword(newConf.pass)
|
||||
opts.SetClientID(fmt.Sprintf("BEpusdt %d", os.Getpid()))
|
||||
opts.SetAutoReconnect(true)
|
||||
opts.SetOrderMatters(false)
|
||||
opts.SetOnConnectHandler(onConnectHandler)
|
||||
opts.SetConnectionLostHandler(onConnectionLost)
|
||||
|
||||
newClient := mqtt.NewClient(opts)
|
||||
if token := newClient.Connect(); token.Wait() && token.Error() != nil {
|
||||
return fmt.Errorf("MQTT 连接失败: %s", token.Error())
|
||||
}
|
||||
|
||||
client = newClient
|
||||
curConf = newConf
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func onConnectHandler(c mqtt.Client) {
|
||||
for topic, cb := range subscribeMap {
|
||||
c.Subscribe(topic, cb.Qos, cb.Handler).Wait()
|
||||
}
|
||||
|
||||
log.Info("✅ MQTT 连接成功")
|
||||
}
|
||||
|
||||
func onConnectionLost(_ mqtt.Client, err error) {
|
||||
log.Warn(fmt.Sprintf("❌ MQTT 连接断开: %s", err.Error()))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
)
|
||||
|
||||
// Publish 发布消息。若 MQTT 未连接则静默丢弃,返回 nil。
|
||||
func Publish(topic string, qos byte, retained bool, payload interface{}) mqtt.Token {
|
||||
mu.RLock()
|
||||
c := client
|
||||
mu.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
token := c.Publish(topic, qos, retained, payload)
|
||||
if qos > 0 {
|
||||
go func() {
|
||||
token.Wait()
|
||||
if err := token.Error(); err != nil {
|
||||
log.Warn("MQTT publish error: " + err.Error())
|
||||
return
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return token
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package mqtt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
)
|
||||
|
||||
type callback struct {
|
||||
Qos byte
|
||||
Handler mqtt.MessageHandler
|
||||
}
|
||||
|
||||
var subscribeMap = make(map[string]callback)
|
||||
|
||||
// Subscribe 注册订阅。topic 会持久保存在 subscribeMap,
|
||||
// 重连后由 onConnectHandler 自动恢复所有订阅。
|
||||
func Subscribe(topic string, qos byte, handler mqtt.MessageHandler) {
|
||||
subscribeMap[topic] = callback{Qos: qos, Handler: handler}
|
||||
|
||||
mu.RLock()
|
||||
c := client
|
||||
mu.RUnlock()
|
||||
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if token := c.Subscribe(topic, qos, handler); token.Wait() && token.Error() == nil {
|
||||
log.Info(fmt.Sprintf("✅ 订阅主题: %s", topic))
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func (t *Telegram) Success(o model.Order) {
|
||||
\-\-\-
|
||||
` + "```" + `
|
||||
🚦商户订单:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💰请求金额:%v ` + string(o.Fiat) + `(%v)
|
||||
💲支付数额:%v ` + tradeType + `
|
||||
💎交易哈希:%s
|
||||
✅收款地址:%s
|
||||
@@ -111,7 +111,7 @@ func (t *Telegram) NotifyFail(o model.Order, reason string) {
|
||||
`+"```"+`
|
||||
🚦商户订单:%v
|
||||
💲支付数额:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💰请求金额:%v `+string(o.Fiat)+`(%v)
|
||||
💍交易类别:%s
|
||||
⚖️️确认时间:%s
|
||||
⏰下次回调:%s
|
||||
|
||||
@@ -23,8 +23,7 @@ func Handler() *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
engine = gin.New()
|
||||
|
||||
session := memstore.NewStore([]byte(conf.Secret))
|
||||
session := memstore.NewStore([]byte(model.GetK(model.AdminSecret)))
|
||||
session.Options(sessions.Options{
|
||||
MaxAge: 86400,
|
||||
HttpOnly: true,
|
||||
|
||||
+9
-9
@@ -22,17 +22,17 @@ import (
|
||||
)
|
||||
|
||||
type aptos struct {
|
||||
versionChunkSize int64
|
||||
versionConfirmedOffset int64
|
||||
lastVersion int64
|
||||
versionChunkSize int
|
||||
versionConfirmedOffset int
|
||||
lastVersion int
|
||||
versionQueue *chanx.UnboundedChan[version]
|
||||
client *http.Client
|
||||
earliestBlockTs atomic.Int64
|
||||
}
|
||||
|
||||
type version struct {
|
||||
Start int64
|
||||
Limit int64
|
||||
Start int
|
||||
Limit int
|
||||
}
|
||||
|
||||
var apt aptos
|
||||
@@ -96,7 +96,7 @@ func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "ledger_version").Int()
|
||||
now := int(gjson.GetBytes(body, "ledger_version").Int())
|
||||
if now <= 0 {
|
||||
log.Task.Warn("syncVersionForward Error: invalid ledger_version:", now)
|
||||
|
||||
@@ -116,7 +116,7 @@ func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
a.versionQueue.In <- version{Start: a.lastVersion, Limit: sub}
|
||||
} else {
|
||||
chunks := (sub + a.versionChunkSize - 1) / a.versionChunkSize
|
||||
for i := int64(0); i < chunks; i++ {
|
||||
for i := 0; i < chunks; i++ {
|
||||
limit := a.versionChunkSize
|
||||
start := a.lastVersion + a.versionChunkSize*i
|
||||
if i == chunks-1 {
|
||||
@@ -133,7 +133,7 @@ func (a *aptos) syncVersionForward(ctx context.Context) {
|
||||
a.lastVersion = now
|
||||
}
|
||||
|
||||
func (a *aptos) syncVersionBackward(ctx context.Context, now int64) {
|
||||
func (a *aptos) syncVersionBackward(ctx context.Context, now int) {
|
||||
var o model.Order
|
||||
trade := model.GetNetworkTrades(conf.Aptos)
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)",
|
||||
@@ -247,7 +247,7 @@ func (a *aptos) versionParse(n any) {
|
||||
timestamp := time.Unix(tsNano/1e9, tsNano%1e9)
|
||||
a.recordEarliestBlockTs(timestamp.Unix())
|
||||
|
||||
ver := trans.Get("version").Int()
|
||||
ver := int(trans.Get("version").Int())
|
||||
hash := trans.Get("hash").String()
|
||||
addrOwner := make(map[string]string) // [address] => owner address
|
||||
addrType := make(map[string]model.TradeType) // [address] => tradeType
|
||||
|
||||
+9
-13
@@ -8,7 +8,6 @@ import (
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -33,7 +32,7 @@ var chainBlockNum sync.Map
|
||||
|
||||
type block struct {
|
||||
RollDelayOffset int64 // 延迟偏移量,某些RPC节点如果不延迟,会报错 block is out of range,目前发现 https://rpc.xlayer.tech/ 存在此问题
|
||||
ConfirmedOffset int64 // 确认偏移量,开启交易确认后,区块高度需要减去此值认为交易已确认
|
||||
ConfirmedOffset int // 确认偏移量,开启交易确认后,区块高度需要减去此值认为交易已确认
|
||||
}
|
||||
|
||||
type evmNative struct {
|
||||
@@ -256,7 +255,7 @@ func (e *evm) getBlockByNumber(a any) {
|
||||
var array = itm.Get("result.transactions").Array()
|
||||
if e.Native.Parse && len(array) != 0 {
|
||||
|
||||
nativeTransfers = append(nativeTransfers, e.parseNativeTransfer(array, utils.HexStr2Int(blockNumHex).Int64(), blockTime)...)
|
||||
nativeTransfers = append(nativeTransfers, e.parseNativeTransfer(array, int(utils.HexStr2Int(blockNumHex).Int64()), blockTime)...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +278,7 @@ func (e *evm) getBlockByNumber(a any) {
|
||||
log.Task.Info(fmt.Sprintf("区块扫描完成(%s): %d → %d 成功率:%s", e.Network, b.From, b.To, conf.GetSuccessRate(e.Network)))
|
||||
}
|
||||
|
||||
func (e *evm) parseNativeTransfer(array []gjson.Result, num int64, timestamp time.Time) []transfer {
|
||||
func (e *evm) parseNativeTransfer(array []gjson.Result, num int, timestamp time.Time) []transfer {
|
||||
nativeTransfers := make([]transfer, 0)
|
||||
for _, tx := range array {
|
||||
if tx.Get("input").String() != "0x" {
|
||||
@@ -372,20 +371,13 @@ func (e *evm) parseEventTransfer(b evmBlock, timestamp map[string]time.Time) ([]
|
||||
continue
|
||||
}
|
||||
|
||||
blockNum, err := strconv.ParseInt(itm.Get("blockNumber").String(), 0, 64)
|
||||
if err != nil {
|
||||
log.Task.Warn("evmBlockParse Error parsing block number:", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: e.Network,
|
||||
FromAddress: from,
|
||||
RecvAddress: recv,
|
||||
Amount: decimal.NewFromBigInt(amount, model.GetContractDecimal(to)),
|
||||
TxHash: itm.Get("transactionHash").String(),
|
||||
BlockNum: blockNum,
|
||||
BlockNum: cast.ToInt(itm.Get("blockNumber").String()),
|
||||
Timestamp: timestamp[itm.Get("blockNumber").String()],
|
||||
TradeType: tradeType,
|
||||
})
|
||||
@@ -404,7 +396,7 @@ func (e *evm) tradeConfirmHandle(ctx context.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if last.(int64)-o.RefBlockNum < e.Block.ConfirmedOffset {
|
||||
if last.(int)-o.RefBlockNum < e.Block.ConfirmedOffset {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -469,6 +461,10 @@ func syncBreak(network string, num int) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
if mqttSubscribed(network) {
|
||||
return false
|
||||
}
|
||||
|
||||
trades := model.GetNetworkTrades(model.Network(network))
|
||||
if len(trades) == 0 {
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
appMqtt "github.com/v03413/bepusdt/app/mqtt"
|
||||
"github.com/v03413/go-cache"
|
||||
)
|
||||
|
||||
type mqttTransfer struct {
|
||||
Network string `json:"network"`
|
||||
TxHash string `json:"tx_hash"`
|
||||
Amount decimal.Decimal `json:"amount"`
|
||||
FromAddress string `json:"from_address"`
|
||||
RecvAddress string `json:"recv_address"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
TradeType model.TradeType `json:"trade_type"`
|
||||
BlockNum int `json:"block_num"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
Register(Task{Duration: time.Second * 5, Callback: mqttWatcher})
|
||||
}
|
||||
|
||||
func mqttWatcher(_ context.Context) {
|
||||
if err := appMqtt.Reload(); err != nil {
|
||||
log.Printf("❌ MQTT 连接失败: %s\n", err.Error())
|
||||
}
|
||||
|
||||
networks := strings.Split(model.GetC(model.MqttNetworks), ",")
|
||||
for _, n := range networks {
|
||||
cache.Set("mqtt_subscribed_"+n, true, time.Second*8)
|
||||
}
|
||||
}
|
||||
|
||||
func mqttPublish(t transfer) {
|
||||
if !mqttSubscribed(t.Network) {
|
||||
return
|
||||
}
|
||||
|
||||
var qos = cast.ToUint8(model.GetC(model.MqttPublishQos))
|
||||
var topic = model.GetC(model.MqttTopicPrefix) + "/transfer/" + t.Network
|
||||
var data = mqttTransfer{
|
||||
Network: t.Network,
|
||||
TxHash: t.TxHash,
|
||||
Amount: t.Amount,
|
||||
FromAddress: t.FromAddress,
|
||||
RecvAddress: t.RecvAddress,
|
||||
Timestamp: t.Timestamp.Unix(),
|
||||
TradeType: t.TradeType,
|
||||
BlockNum: t.BlockNum,
|
||||
}
|
||||
go func() {
|
||||
payload, _ := json.Marshal(data)
|
||||
|
||||
appMqtt.Publish(topic, qos, false, payload)
|
||||
}()
|
||||
}
|
||||
|
||||
func mqttSubscribed(n string) bool {
|
||||
_, found := cache.Get("mqtt_subscribed_" + n)
|
||||
return found
|
||||
}
|
||||
+70
-78
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/v03413/bepusdt/app/utils"
|
||||
|
||||
"github.com/v03413/go-cache"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type EpNotify struct {
|
||||
@@ -166,90 +167,81 @@ func Bepusdt(o model.Order) {
|
||||
return
|
||||
}
|
||||
|
||||
var todo = func() error {
|
||||
var db = model.Db.Begin()
|
||||
if err := db.Where("trade_id = ? and status = ?", o.TradeId, o.Status).Limit(1).Find(&o).Error; err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
var key = fmt.Sprintf("bepusdt_notify_%d_%s", o.Status, o.TradeId)
|
||||
if _, ok := cache.Get(key); ok {
|
||||
db.Rollback()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
cache.Set(key, true, time.Minute)
|
||||
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: o.TradeId,
|
||||
OrderId: o.OrderId,
|
||||
Amount: cast.ToFloat64(o.Money),
|
||||
ActualAmount: o.Amount,
|
||||
Token: o.Address,
|
||||
BlockTransactionId: o.RefHash,
|
||||
Status: o.Status,
|
||||
}
|
||||
var jsonBody, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// 签名
|
||||
body.Signature = utils.EpusdtSign(data, model.AuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, _ = json.Marshal(body)
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var req, err2 = http.NewRequest("POST", o.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err2 != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err2
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Powered-By", "https://github.com/v03413/BEpusdt")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
db.Rollback()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
db.Rollback()
|
||||
|
||||
return fmt.Errorf("resp.StatusCode != 200")
|
||||
}
|
||||
|
||||
all, _ := io.ReadAll(resp.Body)
|
||||
|
||||
log.Info(fmt.Sprintf("订单回调成功[%d]:%s %s", o.Status, o.TradeId, string(all)))
|
||||
|
||||
db.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
var authToken = model.AuthToken()
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
go func() {
|
||||
if err := todo(); err != nil {
|
||||
if err := deliverBepusdtStatusUpdate(model.Db, client, authToken, o); err != nil {
|
||||
log.Warn("notify BEpusdt Error:", err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func deliverBepusdtStatusUpdate(db *gorm.DB, client *http.Client, authToken string, o model.Order) error {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: time.Second * 5}
|
||||
}
|
||||
|
||||
var current model.Order
|
||||
tx := db.Where("trade_id = ? and status = ?", o.TradeId, o.Status).Limit(1).Find(¤t)
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var key = fmt.Sprintf("bepusdt_notify_%d_%s", current.Status, current.TradeId)
|
||||
if _, ok := cache.Get(key); ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
cache.Set(key, true, time.Minute)
|
||||
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: current.TradeId,
|
||||
OrderId: current.OrderId,
|
||||
Amount: cast.ToFloat64(current.Money),
|
||||
ActualAmount: current.Amount,
|
||||
Token: current.Address,
|
||||
BlockTransactionId: current.RefHash,
|
||||
Status: current.Status,
|
||||
}
|
||||
jsonBody, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body.Signature = utils.EpusdtSign(data, authToken)
|
||||
|
||||
jsonBody, _ = json.Marshal(body)
|
||||
req, err := http.NewRequest("POST", current.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Powered-By", "https://github.com/v03413/BEpusdt")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return fmt.Errorf("resp.StatusCode != 200")
|
||||
}
|
||||
|
||||
all, _ := io.ReadAll(resp.Body)
|
||||
log.Info(fmt.Sprintf("订单回调成功[%d]:%s %s", current.Status, current.TradeId, string(all)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func markNotifyFail(o model.Order, reason string) {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):%s %v", o.TradeId, reason, o.SetNotifyState(model.OrderNotifyStateFail)))
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
applog "github.com/v03413/bepusdt/app/log"
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newNotifyTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
|
||||
dbPath := filepath.Join(t.TempDir(), "notify-test.db")
|
||||
db, err := gorm.Open(sqlite.Open(dbPath+"?cache=shared&mode=rwc&_pragma=journal_mode(WAL)&_pragma=busy_timeout(1000)"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open test db: %v", err)
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get sql db: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
sqlDB.SetMaxIdleConns(1)
|
||||
|
||||
if err := db.AutoMigrate(&model.Order{}); err != nil {
|
||||
t.Fatalf("auto migrate order: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func initNotifyTestLog(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
if err := applog.Init(filepath.Join(t.TempDir(), "logs")); err != nil {
|
||||
t.Fatalf("init log: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
applog.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func newWaitingOrder(notifyURL string) model.Order {
|
||||
now := time.Now()
|
||||
confirmedAt := now
|
||||
|
||||
return model.Order{
|
||||
OrderId: "merchant-order-1",
|
||||
TradeId: "trade-order-1",
|
||||
TradeType: model.UsdtTrc20,
|
||||
Fiat: "CNY",
|
||||
Crypto: "USDT",
|
||||
Rate: "7.00",
|
||||
Amount: "1.00",
|
||||
Money: "7.00",
|
||||
Address: "TTestAddress1234567890",
|
||||
Status: model.OrderStatusWaiting,
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
NotifyUrl: notifyURL,
|
||||
ExpiredAt: now.Add(10 * time.Minute),
|
||||
ConfirmedAt: &confirmedAt,
|
||||
AutoTimeAt: model.AutoTimeAt{CreatedAt: (*model.Datetime)(&now), UpdatedAt: (*model.Datetime)(&now)},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliverBepusdtStatusUpdateDoesNotHoldDBWhileHTTPIsPending(t *testing.T) {
|
||||
db := newNotifyTestDB(t)
|
||||
initNotifyTestLog(t)
|
||||
|
||||
requestStarted := make(chan struct{}, 1)
|
||||
releaseResponse := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestStarted <- struct{}{}
|
||||
<-releaseResponse
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
order := newWaitingOrder(server.URL)
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
t.Fatalf("seed order: %v", err)
|
||||
}
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- deliverBepusdtStatusUpdate(db, &http.Client{Timeout: 2 * time.Second}, "test-auth-token", order)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-requestStarted:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("notification request never reached test server")
|
||||
}
|
||||
|
||||
queryDone := make(chan error, 1)
|
||||
go func() {
|
||||
var count int64
|
||||
queryDone <- db.Model(&model.Order{}).Where("status = ?", model.OrderStatusWaiting).Count(&count).Error
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-queryDone:
|
||||
if err != nil {
|
||||
t.Fatalf("concurrent query failed: %v", err)
|
||||
}
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
close(releaseResponse)
|
||||
<-errCh
|
||||
t.Fatal("database query was blocked while notification HTTP request was in flight")
|
||||
}
|
||||
|
||||
close(releaseResponse)
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatalf("deliver notification: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
func init() {
|
||||
var rate = Rate{}
|
||||
|
||||
Register(Task{Duration: time.Hour, Callback: rate.Clear})
|
||||
Register(Task{Duration: time.Second * 5, Callback: rate.Sync})
|
||||
}
|
||||
|
||||
@@ -34,3 +35,13 @@ func (Rate) Sync(ctx context.Context) {
|
||||
log.Warn(fmt.Sprintf("同步汇率失败: %s", err.Error()))
|
||||
}
|
||||
}
|
||||
|
||||
func (Rate) Clear(ctx context.Context) {
|
||||
days := cast.ToInt(model.GetC(model.RateSyncHistoryDays))
|
||||
if days <= 0 {
|
||||
days = 1
|
||||
}
|
||||
|
||||
createdAt := time.Now().AddDate(0, 0, -days)
|
||||
model.Db.Where("created_at < ?", createdAt).Delete(&model.Rate{})
|
||||
}
|
||||
|
||||
+10
-10
@@ -28,9 +28,9 @@ import (
|
||||
// - https://github.com/solana-program/token/blob/6d18ff73b1dd30703a30b1ca941cb0f1d18c2b2a/program/src/instruction.rs
|
||||
|
||||
type solana struct {
|
||||
slotConfirmedOffset int64
|
||||
lastSlotNum int64
|
||||
slotQueue *chanx.UnboundedChan[int64]
|
||||
slotConfirmedOffset int
|
||||
lastSlotNum int
|
||||
slotQueue *chanx.UnboundedChan[int]
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func newSolana() solana {
|
||||
return solana{
|
||||
slotConfirmedOffset: 60,
|
||||
lastSlotNum: 0,
|
||||
slotQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
slotQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
|
||||
client: utils.NewHttpClient(),
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "result").Int()
|
||||
now := int(gjson.GetBytes(body, "result").Int())
|
||||
if now <= 0 {
|
||||
log.Task.Warn("syncSlotForward Error: invalid slot number:", now)
|
||||
|
||||
@@ -99,7 +99,7 @@ func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
s.syncSlotBackward(now)
|
||||
}
|
||||
|
||||
if now-s.lastSlotNum > cast.ToInt64(model.GetC(model.BlockHeightMaxDiff)) { // 区块高度变化过大,强制丢块重扫
|
||||
if now-s.lastSlotNum > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) { // 区块高度变化过大,强制丢块重扫
|
||||
s.lastSlotNum = now
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func (s *solana) syncSlotForward(ctx context.Context) {
|
||||
s.lastSlotNum = now
|
||||
}
|
||||
|
||||
func (s *solana) syncSlotBackward(now int64) {
|
||||
func (s *solana) syncSlotBackward(now int) {
|
||||
if now == 0 || s.lastSlotNum != 0 {
|
||||
|
||||
return
|
||||
@@ -132,13 +132,13 @@ func (s *solana) syncSlotBackward(now int64) {
|
||||
}
|
||||
|
||||
// Solana 大概1秒3个区块(大概值,实际存在波动)
|
||||
num := (time.Now().Unix() - o.CreatedAt.Time().Unix() + 1) * 3 // 计算需要反向扫描的区块数量
|
||||
num := int((time.Now().Unix() - o.CreatedAt.Time().Unix() + 1) * 3) // 计算需要反向扫描的区块数量
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Millisecond * 125)
|
||||
defer ticker.Stop()
|
||||
|
||||
for i := int64(0); i < num; i++ {
|
||||
for i := 0; i < num; i++ {
|
||||
if syncBreak(conf.Solana, s.slotQueue.Len()) {
|
||||
|
||||
return
|
||||
@@ -179,7 +179,7 @@ func (s *solana) slotDispatch(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (s *solana) slotParse(n any) {
|
||||
slot := n.(int64)
|
||||
slot := n.(int)
|
||||
post := []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"getBlock","params":[%d,{"encoding":"json","maxSupportedTransactionVersion":0,"transactionDetails":"full","rewards":false}]}`, slot))
|
||||
network := conf.Solana
|
||||
|
||||
|
||||
+32
-20
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notifier"
|
||||
"github.com/v03413/bepusdt/app/task/notify"
|
||||
@@ -16,14 +17,14 @@ import (
|
||||
)
|
||||
|
||||
type transfer struct {
|
||||
Network string
|
||||
TxHash string
|
||||
Amount decimal.Decimal
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType model.TradeType
|
||||
BlockNum int64
|
||||
Network string `json:"network"`
|
||||
TxHash string `json:"tx_hash"`
|
||||
Amount decimal.Decimal `json:"amount"`
|
||||
FromAddress string `json:"from_address"`
|
||||
RecvAddress string `json:"recv_address"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
TradeType model.TradeType `json:"trade_type"`
|
||||
BlockNum int `json:"block_num"`
|
||||
}
|
||||
|
||||
type resource struct {
|
||||
@@ -40,7 +41,7 @@ var resourceQueue = chanx.NewUnboundedChan[[]resource](context.Background(), 30)
|
||||
var notOrderQueue = chanx.NewUnboundedChan[[]transfer](context.Background(), 30) // 非订单队列
|
||||
var transferQueue = chanx.NewUnboundedChan[[]transfer](context.Background(), 30) // 交易转账队列
|
||||
|
||||
const batchInterval = time.Second * 1 // 批处理缓解数据库读取压力
|
||||
const batchInterval = time.Second * 1 // 批处理缓解数据库读取压力
|
||||
const orderCheckInterval = time.Second * 10 // 订单过期检查间隔
|
||||
|
||||
func init() {
|
||||
@@ -76,8 +77,7 @@ func orderTransferHandle(ctx context.Context) {
|
||||
}
|
||||
|
||||
var other = make([]transfer, 0)
|
||||
// getAllWaitingOrders 内部包含过期检查逻辑
|
||||
var orders = getAllWaitingOrders()
|
||||
var orders = getAllWaitingOrders() // 内部包含过期检查逻辑
|
||||
if len(batch) == 0 {
|
||||
continue
|
||||
}
|
||||
@@ -87,6 +87,8 @@ func orderTransferHandle(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
mqttPublish(t)
|
||||
|
||||
key := fmt.Sprintf("%s%s", t.RecvAddress, t.TradeType)
|
||||
orderList, ok := orders[key]
|
||||
if !ok {
|
||||
@@ -95,21 +97,22 @@ func orderTransferHandle(ctx context.Context) {
|
||||
}
|
||||
|
||||
var matched bool
|
||||
for _, o := range orderList {
|
||||
// 金额前缀匹配
|
||||
if !amountMatch(t.Amount, o.Amount, string(o.TradeType)) {
|
||||
|
||||
for i, o := range orderList {
|
||||
// 金额匹配
|
||||
if !o.AddressLocked && !amountMatch(t.Amount, o.Amount, string(o.TradeType)) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 有效期检测
|
||||
if !o.CreatedAt.Before(t.Timestamp) || !o.ExpiredAt.After(t.Timestamp) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 找到匹配的订单
|
||||
o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp)
|
||||
// 从内存 map 中移除已匹配订单,防止同批次其他 transfer 重复匹配
|
||||
orders[key] = append(orderList[:i], orderList[i+1:]...)
|
||||
|
||||
// 订单匹配 进入确认流程
|
||||
o.MarkConfirming(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp, t.Amount)
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
@@ -277,10 +280,20 @@ func amountMatch(amount decimal.Decimal, target, tradeType string) bool {
|
||||
case model.Classic:
|
||||
return amount.String() == target
|
||||
case model.HasPrefix:
|
||||
return strings.HasPrefix(amount.String(), target)
|
||||
s := amount.String()
|
||||
if !strings.HasPrefix(s, target) {
|
||||
return false
|
||||
}
|
||||
rest := s[len(target):]
|
||||
if rest == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
return strings.Contains(target, ".") || strings.HasPrefix(rest, ".")
|
||||
case model.RoundOff:
|
||||
t, err := decimal.NewFromString(target)
|
||||
if err != nil {
|
||||
log.Warn(err.Error())
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -288,7 +301,6 @@ func amountMatch(amount decimal.Decimal, target, tradeType string) bool {
|
||||
_, precision := model.GetAtomicity(model.TradeType(tradeType)) // 标准精度
|
||||
precision2 := abs(t.Exponent()) // 实际精度
|
||||
if precision2 != precision {
|
||||
|
||||
precision = precision2
|
||||
}
|
||||
|
||||
|
||||
+20
-16
@@ -32,9 +32,9 @@ var usdtTrc20ContractAddress = []byte{0x41, 0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd,
|
||||
var usdcTrc20ContractAddress = []byte{0x41, 0x34, 0x87, 0xb6, 0x3d, 0x30, 0xb5, 0xb2, 0xc8, 0x7f, 0xb7, 0xff, 0xa8, 0xbc, 0xfa, 0xde, 0x38, 0xea, 0xac, 0x1a, 0xbe}
|
||||
|
||||
type tron struct {
|
||||
lastBlockNum int64
|
||||
blockConfirmedOffset int64
|
||||
blockScanQueue *chanx.UnboundedChan[int64]
|
||||
lastBlockNum int
|
||||
blockConfirmedOffset int
|
||||
blockScanQueue *chanx.UnboundedChan[int]
|
||||
conn map[string]*grpc.ClientConn
|
||||
connMu sync.RWMutex
|
||||
}
|
||||
@@ -52,7 +52,7 @@ func newTron() tron {
|
||||
return tron{
|
||||
lastBlockNum: 0,
|
||||
blockConfirmedOffset: 30,
|
||||
blockScanQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
blockScanQueue: chanx.NewUnboundedChan[int](context.Background(), 30),
|
||||
conn: make(map[string]*grpc.ClientConn),
|
||||
}
|
||||
}
|
||||
@@ -81,10 +81,10 @@ func (t *tron) syncBlocksForward(context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var now = block.BlockHeader.RawData.Number
|
||||
var now = int(block.BlockHeader.RawData.Number)
|
||||
|
||||
// 区块高度变化过大,强制丢块重扫
|
||||
if now-t.lastBlockNum > cast.ToInt64(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
if now-t.lastBlockNum > cast.ToInt(model.GetC(model.BlockHeightMaxDiff)) {
|
||||
t.syncBlocksBackward(now)
|
||||
t.lastBlockNum = now - 1
|
||||
}
|
||||
@@ -105,7 +105,7 @@ func (t *tron) syncBlocksForward(context.Context) {
|
||||
}
|
||||
|
||||
// syncBlocksBackward 反向同步区块,针对程序启动前就已经存在待支付订单时,补齐之前的区块数据,自适应偏移数量
|
||||
func (t *tron) syncBlocksBackward(now int64) {
|
||||
func (t *tron) syncBlocksBackward(now int) {
|
||||
var o model.Order
|
||||
trade := model.GetNetworkTrades(conf.Tron)
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Order("created_at asc").Limit(1).Find(&o)
|
||||
@@ -116,7 +116,7 @@ func (t *tron) syncBlocksBackward(now int64) {
|
||||
|
||||
// 波场出块速度大概3秒一个,同时再冗余5个区块
|
||||
num := (time.Now().Unix() - o.CreatedAt.Time().Unix() + 1) / 3 // 计算需要反向扫描的区块数量
|
||||
start := now - num - 5 // 计算反向扫描的起始区块高度
|
||||
start := now - int(num) - 5 // 计算反向扫描的起始区块高度
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
@@ -158,7 +158,7 @@ func (t *tron) blockDispatch(context.Context) {
|
||||
}
|
||||
|
||||
func (t *tron) blockParse(n any) {
|
||||
var num = n.(int64)
|
||||
var num = n.(int)
|
||||
|
||||
var conn *grpc.ClientConn
|
||||
var err error
|
||||
@@ -171,11 +171,11 @@ func (t *tron) blockParse(n any) {
|
||||
conf.RecordSuccess(conf.Tron)
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
|
||||
bok, err2 := api.NewWalletClient(conn).GetBlockByNum2(ctx, &api.NumberMessage{Num: num})
|
||||
bok, err2 := api.NewWalletClient(conn).GetBlockByNum2(ctx, &api.NumberMessage{Num: int64(num)})
|
||||
cancel()
|
||||
if err2 != nil {
|
||||
conf.RecordFailure(conf.Tron)
|
||||
t.blockScanQueue.In <- num
|
||||
t.blockScanQueue.In <- int(num)
|
||||
log.Task.Warn("GetBlockByNum2 ", err2)
|
||||
|
||||
return
|
||||
@@ -250,7 +250,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: t.base58CheckEncode(foo.ToAddress),
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.TronTrx,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -280,7 +280,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: receiver,
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.UsdtTrc20,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -306,7 +306,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: receiver,
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -321,7 +321,7 @@ func (t *tron) blockParse(n any) {
|
||||
RecvAddress: to,
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
BlockNum: cast.ToInt(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -474,6 +474,10 @@ func (t *tron) syncBreak() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
if mqttSubscribed(conf.Tron) {
|
||||
return false
|
||||
}
|
||||
|
||||
var count int64 = 0
|
||||
trade := []model.TradeType{model.TronTrx, model.UsdtTrc20, model.UsdcTrc20}
|
||||
model.Db.Model(&model.Order{}).Where("status = ? and trade_type in (?)", model.OrderStatusWaiting, trade).Count(&count)
|
||||
@@ -521,7 +525,7 @@ func (t *tron) client() (*grpc.ClientConn, error) {
|
||||
c.Close()
|
||||
}
|
||||
|
||||
conn, err := utils.NewTronGrpcClient(endpoint, model.GetK(model.RpcEndpointTronGridApiKey))
|
||||
conn, err := utils.NewTronGrpcClient(endpoint, model.GetTronGridApiKeys())
|
||||
if err != nil {
|
||||
|
||||
return nil, fmt.Errorf("连接失败: %w", err)
|
||||
|
||||
+8
-6
@@ -14,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
// NewTronGrpcClient 目前很多 TRON API 基本都有QPS限制,过于激进或者过于保守的重试策略都不合适
|
||||
func NewTronGrpcClient(apiNode, apiKey string) (*grpc.ClientConn, error) {
|
||||
func NewTronGrpcClient(apiNode string, apiKey []string) (*grpc.ClientConn, error) {
|
||||
apiNode = strings.TrimSpace(apiNode)
|
||||
if apiNode == "" {
|
||||
return nil, errors.New("tron api node address is empty")
|
||||
@@ -41,7 +41,7 @@ func NewTronGrpcClient(apiNode, apiKey string) (*grpc.ClientConn, error) {
|
||||
}),
|
||||
}
|
||||
|
||||
if apiKey != "" {
|
||||
if len(apiKey) > 0 {
|
||||
opts = append(opts,
|
||||
grpc.WithUnaryInterceptor(tronGridApiKeyUnaryInterceptor(apiKey)),
|
||||
grpc.WithStreamInterceptor(tronGridApiKeyStreamInterceptor(apiKey)),
|
||||
@@ -51,18 +51,20 @@ func NewTronGrpcClient(apiNode, apiKey string) (*grpc.ClientConn, error) {
|
||||
return grpc.NewClient(apiNode, opts...)
|
||||
}
|
||||
|
||||
func tronGridApiKeyUnaryInterceptor(apiKey string) grpc.UnaryClientInterceptor {
|
||||
func tronGridApiKeyUnaryInterceptor(apiKeys []string) grpc.UnaryClientInterceptor {
|
||||
return func(ctx context.Context, method string, req, reply interface{},
|
||||
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKey)
|
||||
i := time.Now().UnixMicro() % int64(len(apiKeys))
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKeys[i])
|
||||
return invoker(ctx, method, req, reply, cc, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
func tronGridApiKeyStreamInterceptor(apiKey string) grpc.StreamClientInterceptor {
|
||||
func tronGridApiKeyStreamInterceptor(apiKeys []string) grpc.StreamClientInterceptor {
|
||||
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn,
|
||||
method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKey)
|
||||
i := time.Now().UnixMicro() % int64(len(apiKeys))
|
||||
ctx = addTronGridApiKeyToContext(ctx, apiKeys[i])
|
||||
return streamer(ctx, desc, cc, method, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"math"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
@@ -206,6 +207,22 @@ func StrSha256(str string) string {
|
||||
return fmt.Sprintf("%x", hash.Sum(nil))
|
||||
}
|
||||
|
||||
func IsAllowedCallbackURL(raw string) bool {
|
||||
// IsAllowedCallbackURL 校验回调/跳转地址格式是否合法
|
||||
// 规则:必须是合法 URL,且 scheme 只允许 http 或 https
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
u, err := url.ParseRequestURI(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
return u.Host != ""
|
||||
}
|
||||
|
||||
// GetRequestHost 识别完整的请求主机地址
|
||||
func GetRequestHost(r *http.Request) string {
|
||||
scheme := "http"
|
||||
|
||||
+100
-125
@@ -1,5 +1,11 @@
|
||||
## 📚 API 对接文档
|
||||
|
||||
> 📡 **MQTT 实时推送**:系统支持将扫描到的链上交易广播到 MQTT 服务器,其它系统通过订阅即可实时获取数据,无需轮询
|
||||
> API。详见 [《MQTT 对接开发文档》](./mqtt.md)。
|
||||
|
||||
> 💡 **推荐阅读**:在开始对接前,建议先阅读 [《BEpusdt 执行原理说明》](./how-it-works.md)
|
||||
> ,了解订单匹配机制、金额匹配模式与汇率浮动等核心原理,有助于更准确地理解本文档中的参数设计。
|
||||
|
||||
### 基础信息
|
||||
|
||||
**认证方式**:签名认证(详见[签名算法](#签名算法))
|
||||
@@ -12,6 +18,17 @@
|
||||
|
||||
## 接口列表
|
||||
|
||||
> **两种订单模式说明**
|
||||
>
|
||||
> BEpusdt 的订单创建接口支持两种工作模式,通过 `amount` 参数决定:
|
||||
>
|
||||
> | 模式 | 触发条件 | 地址分配 | 匹配规则 | 典型场景 |
|
||||
> |------|---------|---------|---------|---------|
|
||||
> | **普通模式** | `amount > 0` | 地址 + 金额同时锁定 | 到账金额须匹配订单金额(±匹配容差) | 商城购物、固定金额收款 |
|
||||
> | **独占模式** | `amount = 0` 或不传 | 仅锁定地址,金额不限 | 任意金额到账均触发回调 | 充值场景、钱包监控、不定额收款 |
|
||||
>
|
||||
> 独占模式下,回调中的 `amount`(法币)和 `actual_amount`(加密货币)均以**实际到账金额**为准,创建订单时无需预设金额。
|
||||
|
||||
### 1. 创建交易
|
||||
|
||||
创建支付订单并获取收银台付款地址。
|
||||
@@ -29,15 +46,15 @@ POST /api/v1/order/create-transaction
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| order_id | string | ✅ | 商户订单编号(唯一标识) |
|
||||
| amount | number | ✅ | 支付金额(法币金额) |
|
||||
| notify_url | string | ✅ | 支付结果异步回调地址 |
|
||||
| redirect_url | string | ✅ | 支付成功后商户跳转地址 |
|
||||
| signature | string | ✅ | 签名字符串(详见[签名算法](#签名算法)) |
|
||||
| amount | number | ❌ | 支付金额(法币金额);留空或传 `0` 则进入**地址独占模式**,收到任意金额均触发回调(详见[执行原理](./how-it-works.md)) |
|
||||
| trade_type | string | ❌ | 交易类型,默认 `usdt.trc20`<br/>完整列表:[trade-type.md](../trade-type.md) |
|
||||
| fiat | string | ❌ | 法币类型,默认 `CNY`<br/>可选:`CNY`、`USD`、`EUR`、`GBP`、`JPY` |
|
||||
| address | string | ❌ | 指定收款地址(留空则自动分配) |
|
||||
| name | string | ❌ | 商品名称 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 120 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 120 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| rate | string | ❌ | 强制指定汇率,支持多种写法:<br/>• `7.4` - 固定汇率 7.4<br/>• `~1.02` - 最新汇率上浮 2%<br/>• `~0.97` - 最新汇率下浮 3%<br/>• `+0.3` - 最新汇率加 0.3<br/>• `-0.2` - 最新汇率减 0.2<br/>留空则使用系统配置汇率 |
|
||||
|
||||
#### 请求示例
|
||||
@@ -72,7 +89,7 @@ POST /api/v1/order/create-transaction
|
||||
| data.status | string | 订单状态,1 表示待付款 |
|
||||
| data.token | string | 收款地址 |
|
||||
| data.expiration_time | number | 订单有效期(秒) |
|
||||
| data.payment_url | string | 收银台付款链接地址 |
|
||||
| data.payment_url | string | 收银台付款链接地址 |
|
||||
|
||||
> **计算公式**:`actual_amount` = `amount` ÷ 汇率
|
||||
|
||||
@@ -99,9 +116,8 @@ POST /api/v1/order/create-transaction
|
||||
|
||||
---
|
||||
|
||||
### 2. 取消交易订单
|
||||
|
||||
取消指定订单,系统将停止监控该订单并释放金额占用。
|
||||
<details>
|
||||
<summary><strong>2. 取消交易</strong> 取消指定订单,系统将停止监控该订单并释放金额占用。</summary>
|
||||
|
||||
#### 请求地址
|
||||
|
||||
@@ -138,13 +154,14 @@ POST /api/v1/order/cancel-transaction
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 3. 创建订单
|
||||
<details>
|
||||
<summary><strong>3. 创建订单</strong> 创建收银台订单,让用户在付款页自由选择支付方式。</summary>
|
||||
|
||||
创建支付订单并获取收银台付款链接,让用户自由选择已添加的付款方式。
|
||||
|
||||
> **注意**:使用相同 `order_id` 创建订单时,系统会根据最新参数重建订单(订单金额、交易类型、收款地址、法币类型),同时超时时间重置。这意味着商户可以基于同一订单号实现独立收银台,灵活变更支付参数。
|
||||
> **注意**:使用相同 `order_id` 创建订单时,系统会根据最新参数重建订单(订单金额、交易类型、收款地址、法币类型),同时超时时间重置。
|
||||
|
||||
#### 请求地址
|
||||
|
||||
@@ -154,17 +171,17 @@ POST /api/v1/order/create-order
|
||||
|
||||
#### 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| order_id | string | ✅ | 商户订单编号(唯一标识) |
|
||||
| amount | number | ✅ | 支付金额(法币金额) |
|
||||
| notify_url | string | ✅ | 支付结果异步回调地址 |
|
||||
| redirect_url | string | ✅ | 支付成功后商户跳转地址 |
|
||||
| signature | string | ✅ | 签名字符串(详见[签名算法](#签名算法)) |
|
||||
| currencies | string | ❌ | 限定交易币种,留空则提不限制付款币种。<br/>多个币种请使用半角逗号分隔,黑名单模式以短横线开头。<br/>例如可配置为:<br/>`USDT`(仅限 USDT)<br/>`USDT,USDC` (限 USDT/USDC)<br/>`-ETH,-BNB` (表示排除 ETH/BNB 两个币种) |
|
||||
| fiat | string | ❌ | 法币类型,默认 `CNY`<br/>可选:`CNY`、`USD`、`EUR`、`GBP`、`JPY` |
|
||||
| name | string | ❌ | 商品名称 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 180 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| order_id | string | ✅ | 商户订单编号(唯一标识) |
|
||||
| notify_url | string | ✅ | 支付结果异步回调地址 |
|
||||
| redirect_url | string | ✅ | 支付成功后商户跳转地址 |
|
||||
| signature | string | ✅ | 签名字符串(详见[签名算法](#签名算法)) |
|
||||
| amount | number | ❌ | 支付金额(法币金额);留空或传 `0` 则进入**地址独占模式**,收到任意金额均触发回调(详见[执行原理](./how-it-works.md)) |
|
||||
| currencies | string | ❌ | 限定交易币种,留空则不限制付款币种。<br/>多个币种请使用半角逗号分隔,黑名单模式以短横线开头。<br/>例如:<br/>`USDT`(仅限 USDT)<br/>`USDT,USDC` (限 USDT/USDC)<br/>`-ETH,-BNB` (排除 ETH/BNB) |
|
||||
| fiat | string | ❌ | 法币类型,默认 `CNY`<br/>可选:`CNY`、`USD`、`EUR`、`GBP`、`JPY` |
|
||||
| name | string | ❌ | 商品名称 |
|
||||
| timeout | number | ❌ | 订单超时时间(秒),最低 180 秒<br/>留空则使用配置 `payment_timeout`,默认 600 秒 |
|
||||
|
||||
#### 请求示例
|
||||
|
||||
@@ -188,7 +205,6 @@ POST /api/v1/order/create-order
|
||||
|----------------------|--------|--------------|
|
||||
| status_code | number | 状态码,200 表示成功 |
|
||||
| message | string | 响应消息 |
|
||||
| data | object | 订单数据 |
|
||||
| data.fiat | string | 交易法币类型 |
|
||||
| data.trade_id | string | 系统交易 ID |
|
||||
| data.order_id | string | 商户订单编号 |
|
||||
@@ -197,8 +213,6 @@ POST /api/v1/order/create-order
|
||||
| data.expiration_time | number | 订单有效期(秒) |
|
||||
| data.payment_url | string | 收银台订单链接 |
|
||||
|
||||
> **计算公式**:`actual_amount` = `amount` ÷ 汇率
|
||||
|
||||
#### 响应示例
|
||||
|
||||
```json
|
||||
@@ -211,17 +225,18 @@ POST /api/v1/order/create-order
|
||||
"order_id": "20250120001",
|
||||
"amount": "28.88",
|
||||
"expiration_time": 1200,
|
||||
"payment_url": "https://example.com/pay/order/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
"payment_url": "https://example.com/pay/cashier/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 4. 更新订单付款方式
|
||||
|
||||
用于向订单付款链接传递付款方式,得到收银台付款地址。
|
||||
<details>
|
||||
<summary><strong>4. 更新订单付款方式</strong> 为收银台订单选定支付链,获取具体收款地址与金额。</summary>
|
||||
|
||||
> **注意**:使用相同 `trade_id` 更新订单时,系统会根据最新交易类型更新订单付款方式。
|
||||
|
||||
@@ -233,11 +248,11 @@ POST /api/v1/pay/update-order
|
||||
|
||||
#### 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------------|--------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| trade_id | string | ✅ | 系统交易 ID |
|
||||
| currency | string | ✅ | 加密货币币种<br/>您已添加的加密货币币种,可选:`USDT`、`USDC`、`TRX` 等。 |
|
||||
| network | string | ✅ | 加密货币所属的网络名<br/>例如:`tron`、`polygon`、`bsc` 等。 |
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|----------|--------|----|-------------------------------------|
|
||||
| trade_id | string | ✅ | 系统交易 ID |
|
||||
| currency | string | ✅ | 加密货币币种,可选:`USDT`、`USDC`、`TRX` 等 |
|
||||
| network | string | ✅ | 加密货币所属网络,如:`tron`、`polygon`、`bsc` 等 |
|
||||
|
||||
#### 请求示例
|
||||
|
||||
@@ -254,8 +269,6 @@ POST /api/v1/pay/update-order
|
||||
| 参数名 | 类型 | 说明 |
|
||||
|----------------------|--------|--------------|
|
||||
| status_code | number | 状态码,200 表示成功 |
|
||||
| message | string | 响应消息 |
|
||||
| data | object | 订单数据 |
|
||||
| data.fiat | string | 交易法币类型 |
|
||||
| data.trade_id | string | 系统交易 ID |
|
||||
| data.order_id | string | 商户订单编号 |
|
||||
@@ -263,9 +276,7 @@ POST /api/v1/pay/update-order
|
||||
| data.actual_amount | string | 实际支付金额(加密货币) |
|
||||
| data.status | string | 订单状态,1 表示待付款 |
|
||||
| data.expiration_time | number | 订单有效期(秒) |
|
||||
| data.payment_url | string | 收银台订单链接 |
|
||||
|
||||
> **计算公式**:`actual_amount` = `amount` ÷ 汇率
|
||||
| data.payment_url | string | 收银台付款链接 |
|
||||
|
||||
#### 响应示例
|
||||
|
||||
@@ -281,65 +292,56 @@ POST /api/v1/pay/update-order
|
||||
"actual_amount": "4.25",
|
||||
"expiration_time": 1200,
|
||||
"status": 1,
|
||||
"payment_url": "https://example.com/pay/order/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
"payment_url": "https://example.com/pay/checkout-counter/b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 订单可用付款方式列表:
|
||||
|
||||
## 接口说明
|
||||
- **URL**:`POST /api/v1/pay/methods`
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 请求参数
|
||||
<details>
|
||||
<summary><strong>5. 订单可用付款方式列表</strong> 返回指定订单当前所有可用的支付方式及实时报价。</summary>
|
||||
|
||||
### 请求体(JSON)
|
||||
#### 请求地址
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| trade_id | string | 是 | 系统交易 ID |
|
||||
| currency | string | 否 | 货币名称(如 USDT / USDC / TRX),不传则返回全部可用方式 |
|
||||
```http
|
||||
POST /api/v1/pay/methods
|
||||
```
|
||||
|
||||
#### 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|----------|--------|----|---------------------------------------|
|
||||
| trade_id | string | ✅ | 系统交易 ID |
|
||||
| currency | string | ❌ | 货币名称(如 USDT / USDC / TRX),不传则返回全部可用方式 |
|
||||
|
||||
#### 请求示例
|
||||
|
||||
### 请求示例
|
||||
```json
|
||||
{
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
#### methods 字段说明
|
||||
|
||||
## 响应参数
|
||||
| 字段 | 类型 | 说明 |
|
||||
|-------------------|---------|--------------|
|
||||
| amount | string | 应付金额(法币) |
|
||||
| actual_amount | string | 实际支付金额(加密货币) |
|
||||
| fiat | string | 法币单位 |
|
||||
| exchange_rate | string | 汇率 |
|
||||
| currency | string | 货币名称 |
|
||||
| network | string | 网络名称 |
|
||||
| token_net_name | string | 代币协议标准名 |
|
||||
| token_custom_name | string | 用户自定义显示名称 |
|
||||
| is_popular | boolean | 是否为流行网络 |
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| status_code | number | 状态码,200 表示成功 |
|
||||
| message | string | 响应消息 |
|
||||
| data | object | 数据对象 |
|
||||
| data.methods | array | 可用付款方式列表 |
|
||||
#### 响应示例
|
||||
|
||||
### methods 字段说明
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| amount | number | 应付金额(法币) |
|
||||
| actual_amount | number | 实际支付金额(加密货币) |
|
||||
| fiat | string | 应付金额法币单位 |
|
||||
| exchange_rate | number | 汇率 |
|
||||
| currency | string | 货币名称 |
|
||||
| network | string | 网络名称 |
|
||||
| token_net_name | string | 代币协议标准名 |
|
||||
| token_custom_name | string | 用户自定义显示名称 |
|
||||
| is_popular | boolean | 是否为流行网络 |
|
||||
|
||||
---
|
||||
|
||||
## 响应示例
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
@@ -350,63 +352,27 @@ POST /api/v1/pay/update-order
|
||||
"amount": "28.88",
|
||||
"actual_amount": "4.25",
|
||||
"fiat": "CNY",
|
||||
"exchange_rate": "",
|
||||
"exchange_rate": "6.79",
|
||||
"currency": "USDT",
|
||||
"network": "bsc",
|
||||
"token_net_name": "BEP20",
|
||||
"token_custom_name": "",
|
||||
"is_popular": true
|
||||
},
|
||||
{
|
||||
"amount": "28.88",
|
||||
"actual_amount": "4.25",
|
||||
"fiat": "CNY",
|
||||
"exchange_rate": "",
|
||||
"currency": "USDC",
|
||||
"network": "arbitrum",
|
||||
"token_net_name": "Arbitrum",
|
||||
"token_custom_name": "ARBITRUM-ONE",
|
||||
"is_popular": true
|
||||
},
|
||||
{
|
||||
"amount": "34.28",
|
||||
"actual_amount": "10",
|
||||
"fiat": "CNY",
|
||||
"exchange_rate": "",
|
||||
"currency": "TRX",
|
||||
"network": "tron",
|
||||
"token_net_name": "TRC20",
|
||||
"token_custom_name": "",
|
||||
"is_popular": true
|
||||
},
|
||||
"is_popular": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
|
||||
TODO: `is_popular` 当前临时返回为 `false` 待后期完善该功能。
|
||||
> TODO: `is_popular` 与 `token_custom_name` 当前为占位值,待后期完善。
|
||||
|
||||
TODO: `token_custom_name` 当前临时返回为空字符串,待后期完善该功能。
|
||||
|
||||
## 如果货币不存在则不响应内容
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"methods": [
|
||||
]
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 6. 支付回调通知
|
||||
|
||||
订单状态变更时,系统会向 `notify_url` 发送 POST 请求。
|
||||
<details>
|
||||
<summary><strong>6. 支付回调通知</strong> 订单状态变更时系统主动推送至 <code>notify_url</code>。</summary>
|
||||
|
||||
#### 通知参数
|
||||
|
||||
@@ -438,12 +404,15 @@ TODO: `token_custom_name` 当前临时返回为空字符串,待后期完善该
|
||||
|
||||
#### 响应要求
|
||||
|
||||
- **成功响应**:返回字符串 `success`(不区分大小写)
|
||||
- **失败响应**:返回其他内容,系统将重试通知
|
||||
- **成功**:返回字符串 `success`(不区分大小写)
|
||||
- **失败**:返回其他内容,系统将按退避策略重试通知
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 签名算法
|
||||
<details>
|
||||
<summary><strong>签名算法</strong></summary>
|
||||
|
||||
### 签名流程
|
||||
|
||||
@@ -490,7 +459,8 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
|
||||
### 代码参考
|
||||
|
||||
- **PHP 实现**:[点击查看](https://github.com/v03413/Epay-BEpusdt/blob/b7fa8fd608d71ce50e0f8eabb1717783c96761ac/bepusdt_plugin.php#L108:L127)
|
||||
- **PHP 实现
|
||||
**:[点击查看](https://github.com/v03413/Epay-BEpusdt/blob/b7fa8fd608d71ce50e0f8eabb1717783c96761ac/bepusdt_plugin.php#L108:L127)
|
||||
- **Python 实现**:[BEpusdt Python SDK](https://github.com/luoyanglang/bepusdt-python-sdk)
|
||||
|
||||
### 签名规则总结
|
||||
@@ -503,9 +473,12 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
| 必须按字典序排序 | 确保双方计算结果一致 |
|
||||
| MD5 结果必须小写 | 统一使用小写字母 |
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
<details>
|
||||
<summary><strong>常见问题</strong></summary>
|
||||
|
||||
### 1. 如何获取 API Token?
|
||||
|
||||
@@ -543,6 +516,8 @@ MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&re
|
||||
4. 测试回调通知处理逻辑
|
||||
5. 确认超时和取消场景
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 参考资料
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 104 KiB |
@@ -1,202 +1,67 @@
|
||||
# Dujiao-Next 对接教程
|
||||
# DuJiao Next 对接 BEpusdt 集成指南
|
||||
|
||||
本文档介绍如何在 [Dujiao-Next](https://github.com/dujiao-next/dujiao-next)(独角next)中对接 BEpusdt。
|
||||
**当前教程针对的是新版独角 [Dujiao Next](https://dujiao-next.com/),旧版独角数卡对接[请看这个](../dujiaoka/dujiaoka.md)**
|
||||
|
||||
## 前置条件
|
||||
## 前提条件
|
||||
|
||||
- BEpusdt 已成功安装并运行
|
||||
- Dujiao-Next 已部署
|
||||
在开始配置前,请确保已满足以下条件:
|
||||
|
||||
**BEpusdt 部署信息**
|
||||
|
||||
- API 服务地址:`https://your-bepusdt.com`
|
||||
- API 密钥:`your_api_token`
|
||||
|
||||
**DuJiao Next 部署信息**
|
||||
|
||||
- 部署地址:`https://your-dujiao.com`
|
||||
- 已进入后台管理界面
|
||||
- 已找到支付渠道管理 > 新增渠道功能
|
||||
|
||||
## 配置步骤
|
||||
|
||||
### 1. 进入支付渠道配置
|
||||
在 DuJiao Next 后台中选择渠道类型为 BEpusdt,按照以下格式进行配置。
|
||||
|
||||
Dujiao-Next 后台 → 支付渠道 → 新增渠道
|
||||

|
||||
|
||||
### 2. 基本参数填写
|
||||
**必填配置项**
|
||||
|
||||
| 参数名称 | 填写内容 | 说明 |
|
||||
|---------|---------|------|
|
||||
| 渠道名称 | USDT-TRC20 支付 | 自定义名称,建议包含币种 |
|
||||
| 渠道类型 | `epusdt` | 固定值,选择 BEpusdt |
|
||||
| 支付方式 | `usdt-trc20` / `usdc-trc20` / `trx` | 选择支持的币种 |
|
||||
| 交互方式 | `qr` 或 `redirect` | 二维码或跳转收银台 |
|
||||
| 配置项 | 说明 | 示例 |
|
||||
|-----------|--------------------|----------------------------------------------------|
|
||||
| 网关地址 | BEpusdt 的 API 服务地址 | `https://your-bepusdt.com` |
|
||||
| API Token | BEpusdt 的 API 密钥 | `your_api_token` |
|
||||
| 支付币种 | 支持的加密资产类型,严格区分大小写 | `usdt.trc20` |
|
||||
| 法币类型 | 支持的法定货币类型 | `CNY`、`USD`、`EUR`、`JPY`、`GBP` |
|
||||
| 异步通知地址 | 交易完成时的服务器异步回调地址 | `https://your-dujiao.com/api/v1/payments/callback` |
|
||||
| 同步回跳地址 | 用户支付完成后的页面跳转地址 | `https://your-dujiao.com/pay` |
|
||||
|
||||
### 3. 支持的渠道类型
|
||||
**配置说明**
|
||||
|
||||
Dujiao-Next 支持以下 BEpusdt 币种:
|
||||
- **支付币种**:详见 [支持的币种列表](https://github.com/v03413/BEpusdt/blob/main/docs/trade-type.md),必须严格区分大小写。
|
||||
- **法币类型**:仅支持 `CNY`、`USD`、`EUR`、`JPY`、`GBP` 五种,必须严格区分大小写。
|
||||
|
||||
| 渠道类型 | 说明 | 对应 trade_type |
|
||||
|---------|------|----------------|
|
||||
| `usdt-trc20` | USDT (TRC20) | `usdt.trc20` |
|
||||
| `usdc-trc20` | USDC (TRC20) | `usdc.trc20` |
|
||||
| `trx` | TRX | `tron.trx` |
|
||||
**⚠️ 重要说明:异步通知地址和同步回跳地址**
|
||||
|
||||
> **注意**:选择渠道类型后,系统会自动设置对应的 `trade_type`,无需手动填写。
|
||||
这两个地址的路由部分 **严格按要求修改**,只需将域名部分替换为您实际部署的 DuJiao Next 服务器地址:
|
||||
|
||||
### 4. 渠道配置参数
|
||||
- **异步通知地址**:`https://your-dujiao.com/api/v1/payments/callback`
|
||||
- 路由固定为 `/api/v1/payments/callback`
|
||||
- 示例:若部署地址为 `https://example.com`,则填写 `https://example.com/api/v1/payments/callback`
|
||||
|
||||
在「渠道配置」中填写以下 JSON:
|
||||
- **同步回跳地址**:`https://your-dujiao.com/pay`
|
||||
- 路由固定为 `/pay`
|
||||
- 示例:若部署地址为 `https://example.com`,则填写 `https://example.com/pay`
|
||||
|
||||
```json
|
||||
{
|
||||
"gateway_url": "https://your-bepusdt-domain.com",
|
||||
"auth_token": "your-api-token",
|
||||
"fiat": "CNY",
|
||||
"notify_url": "https://your-api-domain.com/api/v1/payments/callback",
|
||||
"return_url": "https://your-user-domain.com/pay"
|
||||
}
|
||||
```
|
||||
## 配置验证
|
||||
|
||||
### 5. 配置参数说明
|
||||
配置完成后,请按照以下步骤进行测试:
|
||||
|
||||
| 参数 | 必填 | 说明 | 示例 |
|
||||
|------|------|------|------|
|
||||
| `gateway_url` | ✅ | BEpusdt 网关地址 | `https://pay.example.com` |
|
||||
| `auth_token` | ✅ | BEpusdt API Token | 从 BEpusdt 后台获取 |
|
||||
| `trade_type` | ❌ | 交易类型(自动设置) | `usdt.trc20` / `usdc.trc20` / `tron.trx` |
|
||||
| `fiat` | ❌ | 法币类型,默认 `CNY` | `CNY` / `USD` |
|
||||
| `notify_url` | ✅ | 异步回调地址 | `https://api.example.com/api/v1/payments/callback` |
|
||||
| `return_url` | ✅ | 支付成功跳转地址 | `https://shop.example.com/pay` |
|
||||
1. 进入 DuJiao Next 前台,进行支付测试。
|
||||
2. 观察是否正常跳转到支付页面。
|
||||
|
||||
> **重要提示**:
|
||||
> - `trade_type` 会根据「支付方式」自动设置,无需在配置中填写
|
||||
> - `notify_url` 路径必须是 `/api/v1/payments/callback`(不是 `/api/public/payment/callback`)
|
||||
> - `return_url` 路径必须是 `/pay`(不是 `/order` 或 `/payment`)
|
||||
## 故障排查
|
||||
|
||||
## 获取 API Token
|
||||
若出现网关错误提示,请按照以下步骤排查:
|
||||
|
||||
1. 登录 BEpusdt 后台
|
||||
2. 系统管理 → 基本设置 → API 设置
|
||||
3. 复制「对接令牌」
|
||||
|
||||
## 配置示例
|
||||
|
||||
### 示例 1:USDT-TRC20 支付
|
||||
|
||||
```
|
||||
渠道名称: USDT-TRC20 支付
|
||||
渠道类型: epusdt
|
||||
支付方式: usdt-trc20
|
||||
交互方式: qr
|
||||
|
||||
渠道配置:
|
||||
{
|
||||
"gateway_url": "http://127.0.0.1:8088",
|
||||
"auth_token": "your-token-here",
|
||||
"fiat": "CNY",
|
||||
"notify_url": "https://api.example.com/api/v1/payments/callback",
|
||||
"return_url": "https://shop.example.com/pay"
|
||||
}
|
||||
```
|
||||
|
||||
### 示例 2:TRX 支付
|
||||
|
||||
```
|
||||
渠道名称: TRX 支付
|
||||
渠道类型: epusdt
|
||||
支付方式: trx
|
||||
交互方式: redirect
|
||||
|
||||
渠道配置:
|
||||
{
|
||||
"gateway_url": "http://127.0.0.1:8088",
|
||||
"auth_token": "your-token-here",
|
||||
"fiat": "CNY",
|
||||
"notify_url": "https://api.example.com/api/v1/payments/callback",
|
||||
"return_url": "https://shop.example.com/pay"
|
||||
}
|
||||
```
|
||||
|
||||
## 回调机制说明
|
||||
|
||||
### 异步通知(notify_url)
|
||||
|
||||
BEpusdt 会在支付状态变化时,向 `notify_url` 发送 POST 请求:
|
||||
|
||||
```
|
||||
POST /api/v1/payments/callback
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
order_id=xxx&trade_id=xxx&amount=xxx&actual_amount=xxx&token=xxx&...&signature=xxx
|
||||
```
|
||||
|
||||
Dujiao-Next 会验证签名并更新订单状态。
|
||||
|
||||
### 同步跳转(return_url)
|
||||
|
||||
用户支付完成后,BEpusdt 会跳转到 `return_url`,并附带参数:
|
||||
|
||||
```
|
||||
https://shop.example.com/pay?order_id=xxx&epusdt_return=1
|
||||
```
|
||||
|
||||
Dujiao-Next 前端会检测 `epusdt_return=1` 参数,自动查询订单状态并显示支付结果。
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 1. 支付创建失败
|
||||
|
||||
**可能原因**:
|
||||
- `gateway_url` 配置错误或 BEpusdt 服务未运行
|
||||
- `auth_token` 与 BEpusdt 配置不一致
|
||||
- 网络连接问题(检查防火墙)
|
||||
|
||||
**解决方法**:
|
||||
- 检查 BEpusdt 服务状态:`curl http://your-bepusdt/health`
|
||||
- 验证 API Token 是否正确
|
||||
- 查看 Dujiao-Next 后端日志
|
||||
|
||||
### 2. 回调未收到或订单状态未更新
|
||||
|
||||
**可能原因**:
|
||||
- `notify_url` 配置错误(路径必须是 `/api/v1/payments/callback`)
|
||||
- BEpusdt 无法访问回调地址(网络/防火墙问题)
|
||||
- 签名验证失败
|
||||
|
||||
**解决方法**:
|
||||
- 确认回调地址可被外网访问:`curl https://your-api/api/v1/payments/callback`
|
||||
- 检查 BEpusdt 日志中的回调错误
|
||||
- 检查 Dujiao-Next 后端日志中的签名验证信息
|
||||
|
||||
### 3. 支付完成后跳转错误
|
||||
|
||||
**可能原因**:
|
||||
- `return_url` 路径配置错误(必须是 `/pay` 不是 `/payment` 或 `/order`)
|
||||
- 前端路由配置问题
|
||||
|
||||
**解决方法**:
|
||||
- 确认 `return_url` 配置为:`https://your-user-domain.com/pay`
|
||||
- 清除浏览器缓存后重试
|
||||
|
||||
### 4. 签名验证失败
|
||||
|
||||
**可能原因**:
|
||||
- `auth_token` 不一致(注意前后空格)
|
||||
- 回调参数被中间件修改
|
||||
|
||||
**解决方法**:
|
||||
- 确保 `auth_token` 完全一致
|
||||
- 检查是否有反向代理修改了请求参数
|
||||
|
||||
### 5. 金额不匹配
|
||||
|
||||
**可能原因**:
|
||||
- 汇率波动导致实际支付金额与订单金额不同
|
||||
- BEpusdt 配置的汇率源问题
|
||||
|
||||
**解决方法**:
|
||||
- BEpusdt 会返回 `actual_amount`(实际支付金额),Dujiao-Next 会记录此金额
|
||||
- 可在订单详情中查看实际支付金额
|
||||
|
||||
## 技术支持
|
||||
|
||||
- Dujiao-Next: [GitHub Issues](https://github.com/dujiao-next/dujiao-next/issues)
|
||||
- BEpusdt: [Telegram 群组](https://t.me/BEpusdtChat)
|
||||
|
||||
---
|
||||
|
||||
**贡献者**: 狼哥 ([@luoyanglang](https://github.com/luoyanglang) | Telegram: [@luoyanglang](https://t.me/luoyanglang))
|
||||
|
||||
> 本文档适用于 Dujiao-Next 最新版本和 BEpusdt 最新版本
|
||||
> 最后更新:2026-02-13
|
||||
- **检查网络连通性**:确认 DuJiao Next API 所在服务器能够正常访问 BEpusdt API 地址。
|
||||
- **检查 API Token**:确认所配置的 API Token 与 BEpusdt 中的密钥一致。
|
||||
- **查看日志**:检查 DuJiao Next 和 BEpusdt 的应用日志,获取更详细的错误信息。
|
||||
|
||||
@@ -0,0 +1,508 @@
|
||||
# BEpusdt 执行原理说明
|
||||
|
||||
> 本文档基于源代码逐层拆解 BEpusdt 的核心运行机制,适合开发者对接或二次开发时参考。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
1. [底层区块扫描](#1-底层区块链持续扫描)
|
||||
2. [订单匹配原理](#2-订单匹配原理)
|
||||
3. [地址独占模式](#3-地址独占模式)
|
||||
4. [汇率浮动说明](#4-汇率浮动说明)
|
||||
|
||||
---
|
||||
|
||||
## 1. 底层区块链持续扫描
|
||||
|
||||
### 1.1 整体扫描架构
|
||||
|
||||
BEpusdt 的区块扫描采用 **全链路扫块 + 本地匹配** 的方式,而非对每个地址发起单独的查询请求。
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ 区块链网络节点 (RPC) │
|
||||
│ Tron gRPC EVM JSON-RPC (BSC / ETH / Polygon…) │
|
||||
└──────────┬──────────────────────────┬───────────────────────────┘
|
||||
│ 每 ~3s 拉取最新区块高度 │ 每 ~5s 拉取最新区块高度
|
||||
▼ ▼
|
||||
┌──────────────────┐ ┌──────────────────────┐
|
||||
│ syncBlocksForward│ │ syncBlocksForward │
|
||||
│ (Tron 正向同步) │ │ (EVM 正向同步) │
|
||||
└────────┬─────────┘ └──────────┬───────────┘
|
||||
│ 待扫区块编号入队 │ 待扫区块范围入队 (批量最多10个)
|
||||
▼ ▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ blockScanQueue (无界异步队列) │
|
||||
│ chanx.UnboundedChan · 最大堆积 100 个 │
|
||||
└──────────────────────┬─────────────────────────────────┘
|
||||
│ 消费
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ blockDispatch (goroutine worker pool) │
|
||||
│ Tron: 2 个并发 Worker EVM: 3 个并发 Worker │
|
||||
└──────────────────────┬─────────────────────────────────┘
|
||||
│ 解析完成
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ transferQueue │
|
||||
│ 提取出的 transfer 记录入队 │
|
||||
└──────────────────────┬─────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────┐
|
||||
│ orderTransferHandle (订单匹配) │
|
||||
└────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
> 源码位置:`app/task/tron.go` · `app/task/evm.go` · `app/task/transfer.go`
|
||||
|
||||
---
|
||||
|
||||
### 1.2 扫块两种方向
|
||||
|
||||
| 方向 | 触发条件 | 目的 |
|
||||
|---------------------------------|--------------------|-----------------------------|
|
||||
| **正向扫描** (`syncBlocksForward`) | 定时循环 | 实时跟随链上最新区块,保证新交易不漏掉 |
|
||||
| **反向扫描** (`syncBlocksBackward`) | 程序首次启动,或检测到已有待支付订单 | 补扫程序 **未运行期间** 产生的历史区块,防止漏单 |
|
||||
|
||||
反向扫描回溯量的计算逻辑(以 Tron 为例):
|
||||
|
||||
```
|
||||
回溯区块数 = (当前时间 - 最早待支付订单创建时间) / 3秒(波场出块速度) + 冗余5个区块
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 1.3 对比「单地址轮询」的优势
|
||||
|
||||
市面上许多同类项目的做法是:对每个收款地址,定时调用 `getTransactionsByAddress` 之类的 API 来查询该地址的交易记录。
|
||||
|
||||
BEpusdt 采用 **全量扫块** 的策略,具体区别如下:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ 传统「单地址轮询」模式 │
|
||||
│ │
|
||||
│ 地址A ──→ getTransactions(A) ──→ API 调用 ×1 │
|
||||
│ 地址B ──→ getTransactions(B) ──→ API 调用 ×1 │
|
||||
│ 地址C ──→ getTransactions(C) ──→ API 调用 ×1 │
|
||||
│ ⋮ ⋮ │
|
||||
│ 地址N ──→ getTransactions(N) ──→ API 调用 ×N │
|
||||
│ │
|
||||
│ 总 API 调用次数 = 地址数量 × 轮询频率 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ BEpusdt「全量扫块」模式 │
|
||||
│ │
|
||||
│ 区块 #N ──→ getBlock(N) ──→ API 调用 ×1 │
|
||||
│ │ │
|
||||
│ ├─ 解析出所有 transfer │
|
||||
│ └─ 本地内存匹配:地址A / 地址B / 地址C / … 地址N │
|
||||
│ │
|
||||
│ 总 API 调用次数 = 区块数 (与地址数量无关) │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**核心优势:**
|
||||
|
||||
| 维度 | 单地址轮询 | 全量扫块 (BEpusdt) |
|
||||
|----------|------------------|-------------------|
|
||||
| API 调用量 | 与地址数线性增长 | **固定**,与地址数无关 |
|
||||
| RPC 节点压力 | 高(易触发限流) | **低**,易满足免费节点限额 |
|
||||
| 地址扩展性 | 增加地址 = 增加 API 压力 | **随意添加**地址,无额外成本 |
|
||||
| 实时性 | 受限于轮询间隔 | 与出块速度对齐(秒级) |
|
||||
| 漏单风险 | 较高(轮询窗口期) | **低**,区块连续无跳跃 |
|
||||
| 历史回溯 | 依赖节点接口能力 | **内建支持**,自动补扫历史区块 |
|
||||
|
||||
---
|
||||
|
||||
### 1.4 Tron 与 EVM 扫块的技术差异
|
||||
|
||||
| 项目 | Tron | EVM 系列 |
|
||||
|-------------|-------------------|--------------------------------------|
|
||||
| 通信协议 | gRPC(长连接复用) | HTTP JSON-RPC |
|
||||
| 出块时间 | ~3 秒 | 1~12 秒不等 |
|
||||
| 扫块触发频率 | 每 3 秒 | 每 5 秒 |
|
||||
| 每次批量区块数 | 1 个 | 最多 10 个 |
|
||||
| Token 事件解析 | 手动解析合约 ABI 数据 | `eth_getLogs` + ERC-20 Transfer 事件签名 |
|
||||
| Gas Free 支持 | ✅ 特殊解析 GasFree 合约 | — |
|
||||
|
||||
---
|
||||
|
||||
## 2. 订单匹配原理
|
||||
|
||||
### 2.1 匹配键:地址 + 交易类型
|
||||
|
||||
系统在内存中维护一张等待匹配的订单索引表,Key 由 **收款地址 + 交易类型** 组成:
|
||||
|
||||
```go
|
||||
// app/task/transfer.go · getAllWaitingOrders()
|
||||
key := t.Address + string(t.TradeType)
|
||||
// 例:
|
||||
// "TRX123...abcusdt.trc20"
|
||||
// "0xABC...defusdt.bep20"
|
||||
```
|
||||
|
||||
每当从区块中解析出一笔 `transfer`,就以 `RecvAddress + TradeType` 为 Key 在索引表中查找候选订单,再进一步做金额比对。
|
||||
|
||||
---
|
||||
|
||||
### 2.2 同地址同金额冲突的处理
|
||||
|
||||
**创建订单时**的冲突检测与自动规避(`app/model/order.go · CalcTradeAmount`):
|
||||
|
||||
```
|
||||
创建订单
|
||||
│
|
||||
▼
|
||||
查询当前所有「等待中」和「确认中」的订单
|
||||
│
|
||||
▼
|
||||
构建冲突锁表:lock["地址+金额"] = true
|
||||
│
|
||||
▼
|
||||
计算本次订单金额(法币 ÷ 汇率,保留精度)
|
||||
│
|
||||
▼
|
||||
检查 lock["地址A + 金额X"] 是否存在?
|
||||
│
|
||||
├─ 不存在 ──→ 直接分配,订单创建成功
|
||||
│
|
||||
└─ 已存在 ──→ 金额 += 1个原子精度单位,重新检查
|
||||
最多尝试 100 次,超出则报错
|
||||
|
||||
```
|
||||
|
||||
**示例:**
|
||||
|
||||
```
|
||||
已有订单:地址A / 10.01 USDT
|
||||
新订单金额计算结果也是:10.01 USDT
|
||||
→ 冲突!自动调整为 10.02 USDT
|
||||
再有同地址订单:
|
||||
→ 调整为 10.03 USDT
|
||||
```
|
||||
|
||||
**扫块匹配时**的防重(`app/task/transfer.go · orderTransferHandle`):
|
||||
|
||||
同一批次 `transfer` 中,一旦某笔交易匹配了订单,该订单会被**立即从内存 Map 中移除**,确保批次内其他 transfer 不会重复命中同一订单。
|
||||
|
||||
---
|
||||
|
||||
### 2.3 金额匹配三种模式
|
||||
|
||||
系统提供三种金额匹配策略,可在后台「支付设置」中配置(`payment_match_mode`):
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式一:Classic(经典精确匹配) │
|
||||
│ │
|
||||
│ 规则:实际到账金额字符串 == 订单金额字符串(完全相等) │
|
||||
│ │
|
||||
│ 订单金额:10.01 │
|
||||
│ 到账金额:10.01 ✅ 匹配 │
|
||||
│ 到账金额:10.011 ❌ 不匹配 │
|
||||
│ 到账金额:10.02 ❌ 不匹配 │
|
||||
│ │
|
||||
│ 适用场景:对收款金额精确控制,防止多付混淆 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式二:HasPrefix(前缀匹配 / 允许多付) │
|
||||
│ │
|
||||
│ 规则:实际到账金额以订单金额为前缀,允许多付小数 │
|
||||
│ │
|
||||
│ 订单金额:10.01 │
|
||||
│ 到账金额:10.01 ✅ 匹配(完全等于) │
|
||||
│ 到账金额:10.011 ✅ 匹配(以 10.01 为前缀) │
|
||||
│ 到账金额:10.019 ✅ 匹配(以 10.01 为前缀) │
|
||||
│ 到账金额:10.02 ❌ 不匹配 │
|
||||
│ │
|
||||
│ 适用场景:用户手动转账时可能多付小数,允许容错 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 模式三:RoundOff(数值修约 / 四舍五入) │
|
||||
│ │
|
||||
│ 规则:将两边金额按精度四舍五入后比较 │
|
||||
│ 精度取:订单金额的实际小数位 与 币种标准精度 中较大值 │
|
||||
│ │
|
||||
│ 订单金额:10.01 (精度2位) │
|
||||
│ 到账金额:10.014 → 四舍五入 → 10.01 ✅ 匹配 │
|
||||
│ 到账金额:10.015 → 四舍五入 → 10.02 ❌ 不匹配 │
|
||||
│ 到账金额:10.009 → 四舍五入 → 10.01 ✅ 匹配 │
|
||||
│ │
|
||||
│ 适用场景:链上转账因精度截断导致微小误差,允许容错 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
> 源码位置:`app/task/transfer.go · amountMatch()`
|
||||
|
||||
---
|
||||
|
||||
### 2.4 完整匹配流程图
|
||||
|
||||
```
|
||||
区块扫描 ──→ 解析出 transfer 列表 ──→ transferQueue
|
||||
│
|
||||
▼
|
||||
每 1 秒批量处理(batchInterval)
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 获取所有等待中订单 │
|
||||
│ 构建内存索引 Map │
|
||||
│ Key = 地址 + 交易类型 │
|
||||
└──────────┬──────────┘
|
||||
│
|
||||
遍历 transfer 列表
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ 按 Key 查找候选订单 │
|
||||
└──────────┬──────────┘
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ 金额范围是否合法? │
|
||||
└──────────┬──────────┘
|
||||
否 ↙ ↘ 是
|
||||
进入非订单流 检查独占 or amountMatch
|
||||
(notOrderQueue) │
|
||||
┌──────▼──────┐
|
||||
│ 有效期验证 │
|
||||
│ 创建时间 < │
|
||||
│ 交易时间 < │
|
||||
│ 过期时间 │
|
||||
└──────┬──────┘
|
||||
│ 通过
|
||||
┌──────▼──────┐
|
||||
│ 内存移除订单 │
|
||||
│ 标记确认中 │
|
||||
│ 写入区块/Hash │
|
||||
└──────┬──────┘
|
||||
│
|
||||
等待区块确认偏移
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ 标记成功 │
|
||||
│ 触发回调 │
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 地址独占模式
|
||||
|
||||
### 3.1 什么是地址独占
|
||||
|
||||
普通订单:分配 **地址 + 金额**,系统根据「地址+金额」双重维度匹配交易。
|
||||
|
||||
地址独占模式:**只分配地址,不指定金额**。该地址在订单存续期间被独占,任何金额的收款都会触发回调。
|
||||
|
||||
**触发条件:** 创建订单时不传 `amount` 字段(或传 `0`)。
|
||||
|
||||
```go
|
||||
// app/handler/epusdt/epusdt.go · CreateTransaction()
|
||||
AddressLocked: req.Amount == 0, // 金额为0 → 独占模式
|
||||
|
||||
// app/model/trade.go · BuildOrder()
|
||||
AddressLocked: p.Money.IsZero(), // 零值订单 → 地址锁定
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.2 地址独占分配逻辑
|
||||
|
||||
```
|
||||
创建独占订单
|
||||
│
|
||||
▼
|
||||
LockTradeAddress(addressPool, tradeType)
|
||||
│
|
||||
遍历所有可用地址
|
||||
│
|
||||
├─ 地址A:查询是否有「等待中」或「确认中」的独占订单?
|
||||
│ → 有 → 跳过(该地址已被占用)
|
||||
│ → 无 → ✅ 分配此地址,Amount = "0"
|
||||
│
|
||||
├─ 地址B:同上检测 …
|
||||
│
|
||||
└─ 全部地址已被占用 → 返回错误「暂无可用钱包地址」
|
||||
```
|
||||
|
||||
> 独占模式下,同一地址不会同时存在两个有效的独占订单。
|
||||
|
||||
---
|
||||
|
||||
### 3.3 独占订单的匹配行为
|
||||
|
||||
```go
|
||||
// app/task/transfer.go · orderTransferHandle()
|
||||
// 独占订单跳过金额匹配,任何入账均可命中
|
||||
if !o.AddressLocked && !amountMatch(t.Amount, o.Amount, string(o.TradeType)) {
|
||||
continue // 普通订单:金额不符则跳过
|
||||
}
|
||||
// 独占订单:o.AddressLocked = true,直接跳过此 if,进入有效期检查
|
||||
```
|
||||
|
||||
收款后,系统用实际到账金额和订单创建时锁定的汇率,**动态计算法币金额**并写入订单:
|
||||
|
||||
```go
|
||||
// app/model/order.go · MarkConfirming()
|
||||
if o.AddressLocked {
|
||||
rate, _ := decimal.NewFromString(o.Rate)
|
||||
o.Amount = amount.String() // 实际到账加密货币数量
|
||||
o.Money = rate.Mul(amount).String() // 折算法币金额
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.4 独占模式 vs 普通模式对比
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 普通订单(带金额) │
|
||||
│ │
|
||||
│ 创建 → 分配:地址A + 金额 10.01 USDT │
|
||||
│ 收款条件:必须向地址A 转入 10.01 USDT(±匹配模式容差) │
|
||||
│ 回调内容:包含约定金额 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ 独占订单(不带金额) │
|
||||
│ │
|
||||
│ 创建 → 分配:地址A(独占,金额=0) │
|
||||
│ 收款条件:向地址A 转入 任意金额(大于监控最小金额即可) │
|
||||
│ 回调内容:包含实际到账金额 + 汇率折算法币金额 │
|
||||
│ 典型用途:充值场景、不定额收款、钱包监控 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 汇率浮动说明
|
||||
|
||||
### 4.1 汇率来源
|
||||
|
||||
BEpusdt 通过 **CoinGecko API** 定期同步加密货币对多种法币(CNY / USD / JPY / EUR / GBP)的实时汇率。
|
||||
|
||||
```
|
||||
定时任务(默认间隔 3600 秒)
|
||||
│
|
||||
▼
|
||||
GET https://api.coingecko.com/api/v3/simple/price
|
||||
?ids=tether,usd-coin,tron,binancecoin,ethereum
|
||||
&vs_currencies=cny,usd,jpy,eur,gbp
|
||||
│
|
||||
▼
|
||||
写入数据库 bep_rate 表
|
||||
(含 raw_rate 原始汇率 + syntax 浮动语法 + 最终 rate)
|
||||
```
|
||||
|
||||
> 同步间隔可在后台「系统设置」中调整,最短可设置为数秒级。
|
||||
|
||||
---
|
||||
|
||||
### 4.2 汇率浮动语法
|
||||
|
||||
除直接使用 CoinGecko 的原始汇率外,系统支持为每种 **加密货币 × 法币** 对单独设置浮动语法,实现灵活调价。
|
||||
|
||||
浮动语法规则(配置键:`rate_float_<CRYPTO>_<FIAT>`,如 `rate_float_USDT_CNY`):
|
||||
|
||||
```
|
||||
┌────────────┬───────────────────────────────────────────────────────┐
|
||||
│ 语法格式 │ 说明 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ 7.25 │ 固定汇率,直接使用该数值,忽略 CoinGecko 原始价格 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ ~1.05 │ 乘以系数:最终汇率 = 原始汇率 × 1.05(上浮 5%) │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ +0.1 │ 加固定值:最终汇率 = 原始汇率 + 0.1 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ -0.05 │ 减固定值:最终汇率 = 原始汇率 - 0.05 │
|
||||
├────────────┼───────────────────────────────────────────────────────┤
|
||||
│ (空) │ 不浮动,直接使用 CoinGecko 原始汇率 │
|
||||
└────────────┴───────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**示例计算:**
|
||||
|
||||
```
|
||||
CoinGecko 当前 USDT/CNY = 7.2456
|
||||
|
||||
语法 ~1.03 → 最终汇率 = 7.2456 × 1.03 = 7.4630
|
||||
语法 +0.20 → 最终汇率 = 7.2456 + 0.20 = 7.4456
|
||||
语法 7.30 → 最终汇率 = 7.30(固定,不参考市价)
|
||||
语法 (空) → 最终汇率 = 7.2456(原始市价)
|
||||
```
|
||||
|
||||
> 最终汇率保留 4 位小数。源码:`app/model/rate.go · ParseFloatRate()`
|
||||
|
||||
---
|
||||
|
||||
### 4.3 汇率在订单生命周期中的作用
|
||||
|
||||
```
|
||||
创建订单
|
||||
│
|
||||
├─ 从 bep_rate 获取最新汇率(含浮动计算)
|
||||
│
|
||||
├─ 法币金额 ÷ 汇率 = 加密货币金额(按精度取整)
|
||||
│
|
||||
└─ 汇率快照写入订单 rate 字段(后续不再变更)
|
||||
│
|
||||
▼
|
||||
订单支付期间
|
||||
│
|
||||
汇率波动不影响本次订单
|
||||
│
|
||||
▼
|
||||
收款成功
|
||||
│
|
||||
├─ 普通订单:以创建时约定金额为准,回调包含法币金额
|
||||
│
|
||||
└─ 独占订单:以实际到账金额 × 快照汇率计算法币金额
|
||||
```
|
||||
|
||||
> 汇率快照机制保证了**下单瞬间确定交易金额**,不因支付期间行情波动而产生金额争议。
|
||||
|
||||
---
|
||||
|
||||
### 4.4 创建订单时指定汇率(高级用法)
|
||||
|
||||
API 支持通过 `rate` 参数**强制指定本次订单汇率**,此时将忽略数据库中的汇率记录:
|
||||
|
||||
```json
|
||||
POST /api/v1/epusdt/create
|
||||
{
|
||||
"order_id": "xxx",
|
||||
"amount": 100.0,
|
||||
"fiat": "CNY",
|
||||
"rate": "7.30",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
若传入 `rate` 参数,则浮动语法也不再生效,直接以传入值为准。
|
||||
|
||||
---
|
||||
|
||||
## 附录:关键配置项速查
|
||||
|
||||
| 配置键 | 默认值 | 说明 |
|
||||
|-------------------------|-----------|-----------------------------------------------|
|
||||
| `payment_match_mode` | `classic` | 金额匹配模式:`classic` / `has_prefix` / `round_off` |
|
||||
| `payment_timeout` | `1200` | 订单默认超时时间(秒),范围 180~3600 |
|
||||
| `rate_sync_interval` | `3600` | 汇率同步间隔(秒) |
|
||||
| `atom_usdt` | `0.01` | USDT 最小原子精度(影响同地址冲突递增步长) |
|
||||
| `block_height_max_diff` | `1000` | 区块高度跳跃容忍值,超过则强制重新对齐 |
|
||||
| `block_offset_confirm` | `0` | 开启后需等待 N 个区块确认才回调(防回滚) |
|
||||
| `monitor_min_amount` | `0.01` | 非订单监控最小入账金额 |
|
||||
| `rate_float_USDT_CNY` | (空) | USDT/CNY 汇率浮动语法 |
|
||||
|
||||
---
|
||||
|
||||
*文档生成时间:2026-04-14 · 基于 BEpusdt 源码分析*
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
# 📡 MQTT 对接开发文档
|
||||
|
||||
> 系统可将扫描到的交易信息广播到 MQTT 服务器,其它系统通过订阅 MQTT 即可实时获取数据。
|
||||
|
||||
---
|
||||
|
||||
## 概述
|
||||
|
||||
BEpusdt 内置了 MQTT 发布能力,每当区块扫描器捕获到一笔**金额合法**的链上转账时,系统会立即将该交易信息以 JSON 格式发布到对应的
|
||||
MQTT Topic。
|
||||
|
||||
外部系统(如监控大屏、自动充值系统、风控系统等)只需连接同一 MQTT Broker 并订阅对应 Topic,即可**实时、被动地**获取链上交易数据,无需轮询
|
||||
API。
|
||||
|
||||
```
|
||||
区块链网络
|
||||
│
|
||||
▼
|
||||
BEpusdt(扫块)
|
||||
│ 检测到合法转账
|
||||
▼
|
||||
MQTT Broker(广播)
|
||||
│
|
||||
├──► 订阅方 A(充值系统)
|
||||
├──► 订阅方 B(数据分析)
|
||||
└──► 订阅方 C(监控告警)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 一、后台配置
|
||||
|
||||
在 BEpusdt 后台 → **系统管理 → 基本设置 → MQTT 设置** 中填写以下参数:
|
||||
|
||||
| 配置项 | 说明 | 示例 |
|
||||
|-----------|--------------------------------------------|---------------------|
|
||||
| MQTT Host | Broker 服务器地址(仅支持 TCP 模式) | `mqtt.example.com` |
|
||||
| MQTT Port | Broker 端口 | `1883` |
|
||||
| MQTT 用户名 | Broker 认证用户名,无认证可留空 | `admin` |
|
||||
| MQTT 密码 | Broker 认证密码,无认证可留空 | `password` |
|
||||
| 发布 QoS | 消息服务质量:`0` 最多一次 / `1` 至少一次 / `2` 恰好一次 | `1` |
|
||||
| 持续监控网络 | 需要**持续扫块**的网络列表,多个用英文逗号分隔;配置后即使无待支付订单也持续推送 | `tron,bsc,ethereum` |
|
||||
|
||||
> ⚠️ **注意**:系统当前仅支持 `tcp://` 连接协议,不支持 WebSocket(`ws://`)或 TLS(`ssl://`)。
|
||||
>
|
||||
> 客户端 ID 由系统自动生成,格式为 `BEpusdt {进程PID}`,每次启动可能不同,请勿依赖客户端 ID 做业务判断。
|
||||
|
||||
---
|
||||
|
||||
## 二、Topic 规则
|
||||
|
||||
系统按**区块链网络**维度发布消息,Topic 格式如下:
|
||||
|
||||
```
|
||||
bepusdt/transfer/{network}
|
||||
```
|
||||
|
||||
### 网络标识对照表
|
||||
|
||||
| 网络 | Topic | 支持币种 |
|
||||
|----------|-----------------------------|-------------------------------|
|
||||
| Tron | `bepusdt/transfer/tron` | USDT (TRC20)、USDC (TRC20)、TRX |
|
||||
| Ethereum | `bepusdt/transfer/ethereum` | USDT (ERC20)、USDC (ERC20)、ETH |
|
||||
| BSC | `bepusdt/transfer/bsc` | USDT (BEP20)、USDC (BEP20)、BNB |
|
||||
| Polygon | `bepusdt/transfer/polygon` | USDT、USDC |
|
||||
| Arbitrum | `bepusdt/transfer/arbitrum` | USDT、USDC |
|
||||
| Base | `bepusdt/transfer/base` | USDC |
|
||||
| Solana | `bepusdt/transfer/solana` | USDT、USDC |
|
||||
| Aptos | `bepusdt/transfer/aptos` | USDT、USDC |
|
||||
| X Layer | `bepusdt/transfer/xlayer` | USDT、USDC |
|
||||
| Plasma | `bepusdt/transfer/plasma` | USDT |
|
||||
|
||||
### 订阅示例
|
||||
|
||||
```
|
||||
# 仅订阅 Tron 网络
|
||||
bepusdt/transfer/tron
|
||||
|
||||
# 同时订阅 BSC 和 Polygon(分两次 Subscribe)
|
||||
bepusdt/transfer/bsc
|
||||
bepusdt/transfer/polygon
|
||||
|
||||
# 使用通配符订阅所有网络(MQTT v3.1.1)
|
||||
bepusdt/transfer/#
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、消息格式
|
||||
|
||||
消息体为 **UTF-8 编码的 JSON 字符串**,结构如下:
|
||||
|
||||
### 字段说明
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|----------------|--------|----------------------------------------------|
|
||||
| `network` | string | 区块链网络标识,如 `tron`、`bsc`、`ethereum` |
|
||||
| `tx_hash` | string | 链上交易哈希(全局唯一,可作为幂等键) |
|
||||
| `amount` | string | 实际到账的**加密货币数量**(非法币金额) |
|
||||
| `from_address` | string | 发款方钱包地址 |
|
||||
| `recv_address` | string | 收款方钱包地址 |
|
||||
| `timestamp` | number | 交易发生时间,Unix 时间戳(秒) |
|
||||
| `trade_type` | string | 交易类型,完整列表见 [trade-type.md](../trade-type.md) |
|
||||
| `block_num` | number | 交易所在区块高度 |
|
||||
|
||||
### 消息示例
|
||||
|
||||
```json
|
||||
{
|
||||
"network": "tron",
|
||||
"tx_hash": "12ef6267b42e43959795cf31808d0cc72b3d0a48953ed19c61d4b6665a341d10",
|
||||
"amount": "4.25",
|
||||
"from_address": "TJRabPrwbZy45sbavfcjinPJC18iYKbPa5",
|
||||
"recv_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
"timestamp": 1744732800,
|
||||
"trade_type": "usdt.trc20",
|
||||
"block_num": 68123456
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、注意事项
|
||||
|
||||
### 消息去重
|
||||
|
||||
同一笔交易**可能被发布多次**(例如系统重启、扫块重叠时),建议以 `tx_hash` 作为幂等键,在业务层去重处理。
|
||||
|
||||
### 消息触发时机
|
||||
|
||||
MQTT 消息在**扫块阶段**触发,此时交易已出现在区块链上,但系统层面尚未完成订单匹配或回调流程。如果需要确认订单是否支付成功,应以
|
||||
**订单回调通知**(`notify_url`)为准;MQTT 消息可作为辅助的实时感知手段。
|
||||
|
||||
### 金额过滤
|
||||
|
||||
系统仅广播金额在合法范围内的交易(由后台「监控最小金额」配置决定)。超出范围的链上转账不会触发 MQTT 推送。
|
||||
|
||||
### 网络断线重连
|
||||
|
||||
BEpusdt 的 MQTT 客户端已启用自动重连,断线后会自动恢复并重新订阅所有 Topic。订阅方同样建议使用支持自动重连的 MQTT 客户端库。
|
||||
|
||||
### QoS 建议
|
||||
|
||||
| 场景 | 推荐 QoS |
|
||||
|-------------------|--------|
|
||||
| 数据监控、日志记录(允许少量丢失) | `0` |
|
||||
| 充值到账、财务类业务(不能漏消息) | `1` |
|
||||
| 对消息重复极度敏感的场景 | `2` |
|
||||
|
||||
---
|
||||
|
||||
## 五、常见问题
|
||||
|
||||
**Q:MQTT 消息和订单回调(notify_url)有什么区别?**
|
||||
|
||||
> MQTT 是对**所有捕获到的合法链上转账**广播,不区分是否匹配到订单,实时性更高;订单回调仅针对成功匹配的支付订单,包含完整订单信息。两者可结合使用。
|
||||
|
||||
**Q:如何只监听特定收款地址的转账?**
|
||||
|
||||
> MQTT 消息包含 `recv_address` 字段,订阅方自行在消费逻辑中按地址过滤即可,Topic 层面暂不支持按地址过滤。
|
||||
|
||||
**Q:没有活跃订单时为什么收不到消息?**
|
||||
|
||||
> 默认情况下,BEpusdt 仅在有待支付订单时才对对应网络扫块。需在后台**「持续监控网络」**中填入目标网络标识(如 `tron,bsc`
|
||||
> ),才能保证无订单时也持续推送。
|
||||
|
||||
**Q:支持 WebSocket 或 TLS 连接吗?**
|
||||
|
||||
> 当前版本仅支持 TCP 模式(`tcp://`),暂不支持 `ws://` / `wss://` / `ssl://`。
|
||||
|
||||
**Q:`amount` 字段的单位是什么?**
|
||||
|
||||
> `amount` 为**加密货币数量**(如 USDT 数量),并非法币金额。例如 `"amount": "4.25"` 表示实际到账 4.25 USDT。
|
||||
|
||||
---
|
||||
|
||||
## 参考资料
|
||||
|
||||
- [交易类型完整列表](../trade-type.md)
|
||||
- [API 对接文档](./api.md)
|
||||
- [订单回调通知](../notify/readme.md)
|
||||
- [BEpusdt GitHub](https://github.com/v03413/BEpusdt)
|
||||
+2
-1
@@ -15,7 +15,8 @@
|
||||
|
||||
以下是常见程序的对接文档,请根据您的实际需求选择相应教程进行配置。如遇问题,请仔细核对操作步骤,或在相关技术社区寻求协助。
|
||||
|
||||
- [独角数卡](./dujiaoka/dujiaoka.md)
|
||||
- [独角Dujiao-Next](./dujiao-next/dujiao-next.md)
|
||||
- [独角数卡(旧版)](./dujiaoka/dujiaoka.md)
|
||||
- [彩虹易支付](https://github.com/v03413/Epay-BEpusdt)
|
||||
- [WHMCS](https://github.com/v03413/whmcs-gateway-epusdt)
|
||||
- [异次元发卡](acg-faka/README.md)
|
||||
|
||||
+34
-5
@@ -27,7 +27,7 @@ docker run -d --restart=unless-stopped -p 8080:8080 v03413/bepusdt:latest
|
||||
- `v03413/bepusdt:latest` - 稳定发行版(推荐生产环境使用)
|
||||
- `v03413/bepusdt:nightly` - 每日构建开发版(包含最新特性,适合测试环境)
|
||||
|
||||
## 数据持久化配置
|
||||
## 数据持久化
|
||||
|
||||
### SQLite 数据库(默认)
|
||||
|
||||
@@ -47,18 +47,45 @@ docker run -d --restart=unless-stopped -p 8080:8080 -v [挂载路径]:/var/lib/b
|
||||
docker run -d --restart=unless-stopped -p 8080:8080 -v /opt/bepusdt:/var/lib/bepusdt v03413/bepusdt:latest
|
||||
```
|
||||
|
||||
### MySQL 数据库(可选)
|
||||
<details>
|
||||
<summary><strong>PostgreSQL 数据库(推荐)</strong></summary>
|
||||
|
||||
系统支持使用 MySQL 作为数据存储方案,适用于需要更强大数据库功能的场景。
|
||||
系统支持使用 PostgreSQL 作为数据存储方案,适用于生产环境。这是目前推荐的数据库方案。
|
||||
|
||||
**前置准备:**
|
||||
|
||||
- MySQL 版本:5.7 或更高版本
|
||||
- 需提前完成 MySQL 安装及安全配置
|
||||
- PostgreSQL 版本:18 或更高版本
|
||||
- 需提前完成 PostgreSQL 安装及安全配置
|
||||
- 已创建专用数据库(如 `bepusdt`)
|
||||
|
||||
**部署命令:**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--restart unless-stopped \
|
||||
-p 8080:8080 \
|
||||
-e POSTGRESQL_DSN=postgres://user:password@localhost:5432/bepusdt?sslmode=disable&connect_timeout=3 \
|
||||
v03413/bepusdt:latest
|
||||
```
|
||||
|
||||
**配置说明:**
|
||||
|
||||
- 将 `user` 替换为 PostgreSQL 用户名
|
||||
- 将 `password` 替换为 PostgreSQL 密码
|
||||
- 将 `localhost:5432` 替换为 PostgreSQL 服务器地址和端口
|
||||
- 将 `bepusdt` 替换为实际数据库名称
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>MySQL 数据库(已弃用)</strong></summary>
|
||||
|
||||
> **注意:** MySQL 支持将逐步弃用,建议使用 PostgreSQL 替代。
|
||||
|
||||
系统仍支持使用 MySQL 作为数据存储方案,但不再推荐用于新部署。
|
||||
|
||||
**部署命令:**
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--restart unless-stopped \
|
||||
@@ -74,6 +101,8 @@ docker run -d \
|
||||
- 将 `127.0.0.1:3306` 替换为 MySQL 服务器地址和端口
|
||||
- 将 `bepusdt` 替换为实际数据库名称(如需要)
|
||||
|
||||
</details>
|
||||
|
||||
## 部署验证
|
||||
|
||||
### 查看容器日志
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# BEpusdt 与 EPusdt 项目说明
|
||||
|
||||
## 项目背景
|
||||
|
||||
### EPusdt
|
||||
|
||||
EPusdt 是与独角数卡(开源数字商品销售系统)配套的个人 USDT 收款网关,两个项目由同一作者
|
||||
@assimon 开发。
|
||||
|
||||
### BEpusdt
|
||||
|
||||
BEpusdt 由独立作者开发;由于 EPusdt 在一段时间内缺乏积极维护,结合个人需求和对区块链技术的兴趣,才开发了 BEpusdt 项目。
|
||||
BEpusdt 项目名称含义:在 EPusdt 前添加字母 `B`(代表 `Better`),寓意更简单、更好用的 USDT 收款网关。
|
||||
|
||||
## 项目演进
|
||||
|
||||
| 时间 | 事件 |
|
||||
|-------------|-----------------------------|
|
||||
| 2022 年 3 月 | EPusdt 项目发布,4 月基本完善,后续基本无更新 |
|
||||
| 2023 年 10 月 | BEpusdt 项目建立,持续迭代更新至今 |
|
||||
| 2026 年 3 月 | EPusdt 项目转让给其他开发者接手维护 |
|
||||
|
||||
## ⚠️ 重要声明
|
||||
|
||||
**BEpusdt 与转让后的 EPusdt 项目没有任何联系、无共同维护者。两个项目完全独立运营。**
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢原作者 [@assimon](https://github.com/assimon) 开源的 EPusdt 项目,为本项目的诞生提供了灵感和参考。
|
||||
@@ -0,0 +1,48 @@
|
||||
# EVM RPC 节点配置指南
|
||||
|
||||
### RPC 节点在 BEpusdt 中的作用
|
||||
|
||||
BEpusdt 在区块扫描过程中,所有区块数据均通过 RPC 节点获取。因此,**RPC 节点的性能和稳定性直接影响系统的收款体验**。
|
||||
|
||||
## 内置公益节点
|
||||
|
||||
BEpusdt 默认内置了一批公益 RPC
|
||||
节点,详见[源代码配置](https://github.com/v03413/BEpusdt/blob/0e1e22cebbf4a2127786e62b2b8b4d2175054c0b/app/model/conf.go#L140)。
|
||||
|
||||
### 公益节点的局限性
|
||||
|
||||
- **稳定性难以保证**:公益节点由第三方维护,服务质量无法长期保障
|
||||
- **网络质量差异大**:部分 VPS 的网络状况本身较差,容易导致请求失败
|
||||
- **覆盖面不完整**:虽然这些节点已在开发中测试,但无法覆盖所有场景
|
||||
|
||||
这也是常见问题"为什么无法收款"或"为什么换台服务器就好了"的主要原因。
|
||||
|
||||
### 建议
|
||||
|
||||
- 优先选择大型云服务提供商的服务器部署 BEpusdt,确保国际网络连接质量
|
||||
- 在非必要情况下,考虑禁用钱包交易监控功能,以降低 RPC 节点的请求压力
|
||||
|
||||
## 第三方 RPC 服务
|
||||
|
||||
### Chainlist
|
||||
|
||||
**官网**:https://chainlist.org/
|
||||
|
||||
Chainlist 是一个聚合各类区块链网络 RPC 节点信息的平台,用户可以:
|
||||
|
||||
- 查找适合自己需求的 RPC 节点
|
||||
- 一键复制配置信息
|
||||
- 直接集成到应用中
|
||||
|
||||
> **注意**:第三方提供的节点质量需自行测试和评估。
|
||||
|
||||
### Nodies
|
||||
|
||||
**官网**:https://www.nodies.app/
|
||||
|
||||
Nodies 是一个商业 RPC 服务提供商,具有以下特点:
|
||||
|
||||
- 提供企业级的高质量 RPC 节点服务
|
||||
- 性能和稳定性有保障,适合生产环境使用
|
||||
- 提供免费配额,可满足个人单节点的使用需求
|
||||
- 需付费才能获得更高的配额和优先级支持
|
||||
@@ -5,12 +5,14 @@ go 1.24.3
|
||||
require (
|
||||
github.com/btcsuite/btcd/btcutil v1.1.6
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/gin-contrib/sessions v1.0.4
|
||||
github.com/gin-gonic/gin v1.10.1
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/go-telegram/bot v1.17.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||
github.com/natefinch/lumberjack v2.0.0+incompatible
|
||||
github.com/panjf2000/ants/v2 v2.11.3
|
||||
github.com/shopspring/decimal v1.4.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
@@ -20,14 +22,16 @@ require (
|
||||
github.com/urfave/cli/v3 v3.5.0
|
||||
github.com/v03413/go-cache v0.0.0-20250922030915-0ab5b738a932
|
||||
github.com/v03413/tronprotocol v0.0.0-20240824084238-bbd62f5e0158
|
||||
golang.org/x/crypto v0.39.0
|
||||
golang.org/x/crypto v0.42.0
|
||||
google.golang.org/grpc v1.73.0
|
||||
gorm.io/driver/mysql v1.6.0
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.1
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||
github.com/bytedance/sonic v1.13.3 // indirect
|
||||
github.com/bytedance/sonic/loader v0.2.4 // indirect
|
||||
github.com/cloudwego/base64x v0.1.5 // indirect
|
||||
@@ -44,6 +48,11 @@ require (
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.4.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
@@ -52,7 +61,6 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/natefinch/lumberjack v2.0.0+incompatible // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
@@ -64,14 +72,14 @@ require (
|
||||
github.com/ugorji/go/codec v1.2.14 // indirect
|
||||
golang.org/x/arch v0.18.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect
|
||||
golang.org/x/net v0.41.0 // indirect
|
||||
golang.org/x/net v0.44.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250324211829-b45e905df463 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.65.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
|
||||
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
|
||||
github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M=
|
||||
@@ -42,6 +44,8 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeC
|
||||
github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
@@ -105,7 +109,17 @@ github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pw
|
||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
@@ -220,8 +234,8 @@ golang.org/x/arch v0.18.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
|
||||
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 h1:bsqhLWFR6G6xiQcb+JoGqdKdRU6WzPWmK8E0jxTjzo4=
|
||||
golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
@@ -231,8 +245,8 @@ golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73r
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
|
||||
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
|
||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
@@ -247,8 +261,8 @@ golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
@@ -274,18 +288,23 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
modernc.org/cc/v4 v4.26.1 h1:+X5NtzVBn0KgsBCBe+xkDC7twLb/jNVj9FPgiwSQO3s=
|
||||
|
||||
@@ -51,7 +51,9 @@
|
||||
}
|
||||
|
||||
fetch('/payment/assets/locales/' + currentLang + '.json')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (r) {
|
||||
return r.json();
|
||||
})
|
||||
.then(function (translations) {
|
||||
i18next.addResourceBundle(currentLang, 'translation', translations);
|
||||
i18nInitialized = true;
|
||||
@@ -79,7 +81,9 @@
|
||||
|
||||
if (!hasLanguage) {
|
||||
fetch('/payment/assets/locales/' + lang + '.json')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (r) {
|
||||
return r.json();
|
||||
})
|
||||
.then(function (translations) {
|
||||
i18next.addResourceBundle(lang, 'translation', translations);
|
||||
return i18next.changeLanguage(lang);
|
||||
@@ -111,8 +115,8 @@
|
||||
const config = getPaymentConfig();
|
||||
|
||||
let token = (config.token || '--').toUpperCase();
|
||||
let network = (config.network || '--').toUpperCase();
|
||||
let networkName = (config.networkName || '--').toUpperCase();
|
||||
let network = selectedMethod ? (selectedMethod.network || '--').toUpperCase() : '--';
|
||||
let networkName = selectedMethod ? (selectedMethod.token_net_name || '--').toUpperCase() : '--';
|
||||
|
||||
if (selectedMethod) {
|
||||
token = selectedMethod.currency.toUpperCase();
|
||||
@@ -202,45 +206,17 @@
|
||||
// but the event listener for global click is needed once.
|
||||
}
|
||||
|
||||
function fetchPaymentMethods() {
|
||||
fetch('/api/v1/pay/methods', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
trade_id: tradeId
|
||||
})
|
||||
})
|
||||
.then(function (response) { return response.json(); })
|
||||
.then(function (res) {
|
||||
if (res.status_code === 200) {
|
||||
paymentMethods = res.data.methods;
|
||||
initSelection();
|
||||
} else {
|
||||
// Suppress alert for expired orders
|
||||
if (res.status_code === 400 && (res.message && (res.message.includes('过期') || res.message.toLowerCase().includes('expired')))) {
|
||||
showTimeoutMessage();
|
||||
return;
|
||||
}
|
||||
showMessage(res.message || t('payment.loadMethodsFailed', 'Failed to load payment methods'));
|
||||
}
|
||||
})
|
||||
.catch(function (err) {
|
||||
console.error('API Error:', err);
|
||||
showMessage(t('payment.networkError', 'Network error, please refresh'));
|
||||
});
|
||||
}
|
||||
|
||||
function initSelection() {
|
||||
if (!paymentMethods || paymentMethods.length === 0) return;
|
||||
|
||||
// Extract unique currencies
|
||||
const currencies = [...new Set(paymentMethods.map(function (m) { return m.currency; }))];
|
||||
const currencies = [...new Set(paymentMethods.map(function (m) {
|
||||
return m.currency;
|
||||
}))];
|
||||
|
||||
// Render Currency Options
|
||||
renderOptions(currencySelectEl, currencies.map(function (c) {
|
||||
return { value: c, label: c, badge: '' };
|
||||
return {value: c, label: c, badge: ''};
|
||||
}), function (val) {
|
||||
selectedCurrency = val;
|
||||
updateNetworkOptions();
|
||||
@@ -255,7 +231,9 @@
|
||||
|
||||
function updateNetworkOptions() {
|
||||
const networks = paymentMethods
|
||||
.filter(function (m) { return m.currency === selectedCurrency; })
|
||||
.filter(function (m) {
|
||||
return m.currency === selectedCurrency;
|
||||
})
|
||||
.map(function (m) {
|
||||
return {
|
||||
value: m.token_net_name,
|
||||
@@ -326,7 +304,9 @@
|
||||
if (!parent) return;
|
||||
|
||||
const items = parent.querySelectorAll('.option-item');
|
||||
items.forEach(function (item) { item.classList.remove('selected'); });
|
||||
items.forEach(function (item) {
|
||||
item.classList.remove('selected');
|
||||
});
|
||||
|
||||
let selected = null;
|
||||
items.forEach(function (item) {
|
||||
@@ -417,7 +397,9 @@
|
||||
network: selectedMethod.network
|
||||
})
|
||||
})
|
||||
.then(function (response) { return response.json(); })
|
||||
.then(function (response) {
|
||||
return response.json();
|
||||
})
|
||||
.then(function (res) {
|
||||
if (res.status_code === 200 && res.data.payment_url) {
|
||||
window.location.href = res.data.payment_url;
|
||||
@@ -670,7 +652,9 @@
|
||||
if (!tradeId) return;
|
||||
|
||||
fetch('/pay/check-status/' + tradeId)
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (r) {
|
||||
return r.json();
|
||||
})
|
||||
.then(function (data) {
|
||||
// status: 1=pending, 2=success, 3=expired, 5=waiting_confirmation
|
||||
if (data.status === 1) {
|
||||
@@ -703,7 +687,9 @@
|
||||
// Close dropdowns when clicking outside
|
||||
document.addEventListener('click', function () {
|
||||
const selects = document.querySelectorAll('.coin-select');
|
||||
selects.forEach(function (el) { el.classList.remove('active'); });
|
||||
selects.forEach(function (el) {
|
||||
el.classList.remove('active');
|
||||
});
|
||||
});
|
||||
|
||||
setupDropdown(currencySelectEl);
|
||||
@@ -714,7 +700,13 @@
|
||||
}
|
||||
|
||||
initI18n().then(function () {
|
||||
fetchPaymentMethods();
|
||||
if (paymentConfig.network && Array.isArray(paymentConfig.network) && paymentConfig.network.length > 0) {
|
||||
paymentMethods = paymentConfig.network;
|
||||
initSelection();
|
||||
} else {
|
||||
showMessage(t('payment.loadPaymentNetworkFailed', 'Failed to load payment network, please check if the wallet has been added'));
|
||||
}
|
||||
|
||||
startCountdown();
|
||||
// Poll status every 5s
|
||||
statusCheckTimer = setInterval(checkPaymentStatus, 5000);
|
||||
|
||||
Vendored
+23
-3
@@ -300,7 +300,11 @@
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">⏰</div>
|
||||
<div style="margin-bottom: 20px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="#e53e3e" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2"/><path d="M5 3 2 6"/><path d="m22 6-3-3"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 style="color: #e53e3e; margin-bottom: 15px;">${t('payment.paymentTimeout')}</h3>
|
||||
<p style="color: #666; margin-bottom: 25px; line-height: 1.5;">
|
||||
${t('payment.timeoutMessage')}
|
||||
@@ -363,7 +367,13 @@
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px; animation: spin 2s linear infinite;">⏳</div>
|
||||
<div style="margin-bottom: 20px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="#667eea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="animation: spin 2s linear infinite;">
|
||||
<path d="M5 22h14"/><path d="M5 2h14"/>
|
||||
<path d="M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22"/>
|
||||
<path d="M7 2v4.172a2 2 0 0 1 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 style="color: #667eea; margin-bottom: 15px;">${t('payment.waitingConfirmation')}</h3>
|
||||
<p style="color: #666; margin-bottom: 20px; line-height: 1.5;">
|
||||
<span style="color: #059669; font-weight: 600; background: linear-gradient(135deg, #ecfdf5, #f0fdf4); padding: 8px 12px; border-radius: 6px; border-left: 3px solid #10b981;">${t('payment.confirmationMessage')}</span><br>
|
||||
@@ -375,6 +385,9 @@
|
||||
<p style="color: #999; font-size: 12px;">
|
||||
${t('payment.estimatedTime')}
|
||||
</p>
|
||||
<div style="margin-top: 15px; padding-top: 12px; border-top: 1px solid #f0f0f0; font-size: 12px; color: #aaa;">
|
||||
Powered by <a href="https://github.com/v03413/BEpusdt" target="_blank" style="color: #667eea; text-decoration: none; font-weight: 600;">BEpusdt</a> · Github
|
||||
</div>
|
||||
`;
|
||||
|
||||
const style = document.createElement('style');
|
||||
@@ -434,7 +447,11 @@
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">✅</div>
|
||||
<div style="margin-bottom: 20px;">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="#48bb78" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h3 style="color: #48bb78; margin-bottom: 15px;">${t('payment.paymentSuccess')}</h3>
|
||||
<p style="color: #666; margin-bottom: 20px; line-height: 1.5;">
|
||||
${t('payment.transactionHash')}<br>
|
||||
@@ -451,6 +468,9 @@
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
">${t('payment.returnToMerchant')}</button>
|
||||
<div style="margin-top: 15px; padding-top: 12px; border-top: 1px solid #f0f0f0; font-size: 12px; color: #aaa;">
|
||||
Powered by <a href="https://github.com/v03413/BEpusdt" target="_blank" style="color: #667eea; text-decoration: none; font-weight: 600;">BEpusdt</a> · Github
|
||||
</div>
|
||||
`;
|
||||
|
||||
overlay.appendChild(modal);
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"estimatedTime": "Estimated confirmation time: 1-3 minutes",
|
||||
"paymentSuccess": "Payment Successful!",
|
||||
"transactionHash": "Your payment has been confirmed. Transaction hash:",
|
||||
"processing": "Processing..."
|
||||
"processing": "Processing...",
|
||||
"loadPaymentNetworkFailed": "Failed to load payment network, please check if wallet is added."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"estimatedTime": "预计确认时间:1-3分钟",
|
||||
"paymentSuccess": "支付成功!",
|
||||
"transactionHash": "您的支付已确认,交易哈希:",
|
||||
"processing": "处理中..."
|
||||
"processing": "处理中...",
|
||||
"loadPaymentNetworkFailed": "无法加载付款网络,请检查是否已经完成钱包地址添加。"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,9 +99,8 @@
|
||||
<ol>
|
||||
<li data-i18n="payment.cashierInstr1">请选择您喜欢的付款方式进行转账</li>
|
||||
<li data-i18n="payment.instruction2">转账完成后系统会自动确认到账</li>
|
||||
<li data-i18n="payment.instruction3">实际到账金额必须与本页面显示的金额完全一致,差一分钱都不行的!</li>
|
||||
<li data-i18n="payment.instruction4">如果有其它疑问,请联系电报 <a href="https://t.me/hellotaozi" target="_blank"
|
||||
rel="nofollow">@hellotaozi</a></li>
|
||||
<li data-i18n="payment.instruction3">转账金额必须与显示金额完全一致</li>
|
||||
<li data-i18n="payment.instruction4">如果有其它疑问,请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
@@ -124,7 +123,8 @@
|
||||
name: "{{.name}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
order_id: "{{.order_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
return_url: "{{.return_url}}",
|
||||
network: {{.network}},
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -151,6 +151,17 @@
|
||||
<a-input v-model="syncForm.apiKey" placeholder="请输入 API Key(可选)" allow-clear style="width: 100%" />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item label="汇率保留天数">
|
||||
<a-input-number
|
||||
v-model="syncForm.historyDays"
|
||||
:min="1"
|
||||
:max="365"
|
||||
:precision="0"
|
||||
placeholder="请输入汇率保留天数"
|
||||
style="width: 100%"
|
||||
/>
|
||||
</a-form-item>
|
||||
|
||||
<div class="sync-tip">
|
||||
<a-typography-text type="secondary">
|
||||
<icon-info-circle style="margin-right: 4px" />
|
||||
@@ -487,8 +498,9 @@ const syncFormRef = ref();
|
||||
|
||||
const syncForm = reactive({
|
||||
minutes: 60,
|
||||
apiUrl: "https://api.coingecko.com", // 默认官方接口
|
||||
apiKey: ""
|
||||
apiUrl: "https://api.coingecko.com",
|
||||
apiKey: "",
|
||||
historyDays: 30
|
||||
});
|
||||
|
||||
// API 接口选项
|
||||
@@ -507,11 +519,10 @@ const apiUrlOptions = [
|
||||
const showSyncModal = async () => {
|
||||
try {
|
||||
const res = await getsConfAPI({
|
||||
keys: ["rate_sync_interval", "rate_sync_coingecko_api_url", "rate_sync_coingecko_api_key"]
|
||||
keys: ["rate_sync_interval", "rate_sync_coingecko_api_url", "rate_sync_coingecko_api_key", "rate_sync_history_days"]
|
||||
});
|
||||
|
||||
if (res.data) {
|
||||
// 设置同步频率
|
||||
if (res.data.rate_sync_interval) {
|
||||
const seconds = parseInt(res.data.rate_sync_interval);
|
||||
const minutes = Math.round(seconds / 60);
|
||||
@@ -522,16 +533,19 @@ const showSyncModal = async () => {
|
||||
|
||||
syncForm.apiUrl = res.data.rate_sync_coingecko_api_url || "https://api.coingecko.com";
|
||||
syncForm.apiKey = res.data.rate_sync_coingecko_api_key || "";
|
||||
syncForm.historyDays = res.data.rate_sync_history_days ? parseInt(res.data.rate_sync_history_days) : 30;
|
||||
} else {
|
||||
syncForm.minutes = 60;
|
||||
syncForm.apiUrl = "https://api.coingecko.com";
|
||||
syncForm.apiKey = "";
|
||||
syncForm.historyDays = 30;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("获取同步频率配置失败:", error);
|
||||
syncForm.minutes = 60;
|
||||
syncForm.apiUrl = "https://api.coingecko.com";
|
||||
syncForm.apiKey = "";
|
||||
syncForm.historyDays = 30;
|
||||
Message.warning("获取当前配置失败,使用默认值");
|
||||
}
|
||||
|
||||
@@ -550,13 +564,19 @@ const handleSyncSubmit = async () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!syncForm.historyDays || syncForm.historyDays < 1 || syncForm.historyDays > 365) {
|
||||
Message.error("请输入有效的汇率保留天数(1-365天)");
|
||||
return;
|
||||
}
|
||||
|
||||
syncLoading.value = true;
|
||||
const seconds = syncForm.minutes * 60;
|
||||
|
||||
await setsConfAPI([
|
||||
{ key: "rate_sync_interval", value: seconds.toString() },
|
||||
{ key: "rate_sync_coingecko_api_url", value: syncForm.apiUrl },
|
||||
{ key: "rate_sync_coingecko_api_key", value: syncForm.apiKey }
|
||||
{ key: "rate_sync_coingecko_api_key", value: syncForm.apiKey },
|
||||
{ key: "rate_sync_history_days", value: syncForm.historyDays.toString() }
|
||||
]);
|
||||
|
||||
Message.success("汇率同步配置已保存");
|
||||
@@ -575,6 +595,7 @@ const handleSyncCancel = () => {
|
||||
syncForm.minutes = 60;
|
||||
syncForm.apiUrl = "https://api.coingecko.com";
|
||||
syncForm.apiKey = "";
|
||||
syncForm.historyDays = 30;
|
||||
};
|
||||
|
||||
// 支付颗粒度相关状态
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
<a-row align="center" :gutter="[0, 16]">
|
||||
<a-col :span="24">
|
||||
<a-card title="API设置">
|
||||
<a-alert type="info" style="margin-bottom: 16px">
|
||||
系统兼容彩虹易支付 <strong>submit.php</strong> 接口收单,对接时 PID 固定为 <strong>1000</strong>,KEY
|
||||
则是和对接令牌保持一致。
|
||||
</a-alert>
|
||||
<a-form :model="form" :rules="rules" :style="{ width: '600px' }" @submit="onSubmit">
|
||||
<a-form-item field="api_auth_token" label="对接令牌" extra="API对接的身份验证令牌,请妥善保管">
|
||||
<a-input-group class="token-input-group">
|
||||
|
||||
@@ -43,6 +43,9 @@
|
||||
<a-tab-pane key="4" title="API设置">
|
||||
<Api v-model="Conf" @refresh="refresh" />
|
||||
</a-tab-pane>
|
||||
<a-tab-pane key="5" title="MQTT设置">
|
||||
<Mqtt v-model="Conf" @refresh="refresh" />
|
||||
</a-tab-pane>
|
||||
<a-tab-pane key="3" title="安全设置">
|
||||
<Security v-model="Conf" @refresh="refresh" />
|
||||
</a-tab-pane>
|
||||
@@ -60,6 +63,7 @@ import Security from "@/views/system/base/security.vue";
|
||||
import Api from "@/views/system/base/api.vue";
|
||||
import { getsConfAPI } from "@/api/modules/conf/index";
|
||||
import Notifier from "./notifier.vue";
|
||||
import Mqtt from "./mqtt.vue";
|
||||
|
||||
const route = useRoute();
|
||||
const type = ref("rounded");
|
||||
@@ -97,7 +101,14 @@ const getConf = async () => {
|
||||
"payment_static_path",
|
||||
"payment_timeout",
|
||||
"notifier_params",
|
||||
"notifier_channel"
|
||||
"notifier_channel",
|
||||
"mqtt_host",
|
||||
"mqtt_port",
|
||||
"mqtt_user",
|
||||
"mqtt_pass",
|
||||
"mqtt_publish_qos",
|
||||
"mqtt_networks",
|
||||
"mqtt_topic_prefix"
|
||||
]
|
||||
});
|
||||
Conf.value = data.data;
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
<template>
|
||||
<div>
|
||||
<a-row align="center" :gutter="[0, 16]">
|
||||
<a-col :span="24">
|
||||
<a-card title="MQTT 发布设置">
|
||||
<a-alert type="info" style="margin-bottom: 16px">
|
||||
系统可将扫描到的交易信息发布到 MQTT 服务器,其它系统通过订阅实时获取数据,
|
||||
<a href="https://github.com/v03413/BEpusdt/blob/main/docs/api/mqtt.md" target="_blank">查看文档</a>
|
||||
</a-alert>
|
||||
<a-alert type="warning" style="margin-bottom: 16px">
|
||||
<template #icon><icon-exclamation-circle-fill /></template>
|
||||
目前 MQTT 通信协议为 <strong>MQTT over TCP</strong>,该功能只有在 <strong>Host</strong> 和
|
||||
<strong>Port</strong> 均配置后才会正常启用
|
||||
</a-alert>
|
||||
<a-form :model="form" :rules="rules" :style="{ width: '600px' }" @submit="onSubmit">
|
||||
<a-form-item field="mqtt_host" label="MQTT Host" extra="MQTT 服务器地址">
|
||||
<a-input v-model="form.mqtt_host" placeholder="例如:127.0.0.1" allow-clear />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item field="mqtt_port" label="MQTT Port" extra="MQTT 服务器端口">
|
||||
<a-input v-model="form.mqtt_port" placeholder="例如:1883" allow-clear />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item field="mqtt_user" label="用户名" extra="MQTT 连接用户名,无则留空">
|
||||
<a-input v-model="form.mqtt_user" placeholder="请输入用户名" allow-clear />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item field="mqtt_pass" label="密码" extra="MQTT 连接密码,无则留空">
|
||||
<a-input-password v-model="form.mqtt_pass" placeholder="请输入密码" allow-clear />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item
|
||||
field="mqtt_topic_prefix"
|
||||
label="消息路径前缀"
|
||||
extra="消息发布的 Topic 路径前缀,只允许字母、数字、下划线和斜杠,默认为 bepusdt"
|
||||
>
|
||||
<a-input v-model="form.mqtt_topic_prefix" placeholder="例如:bepusdt" allow-clear />
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item field="mqtt_publish_qos" label="Publish QoS" extra="消息发布服务质量等级">
|
||||
<a-radio-group v-model="form.mqtt_publish_qos">
|
||||
<a-radio value="0">0 - 最多一次</a-radio>
|
||||
<a-radio value="1">1 - 至少一次</a-radio>
|
||||
<a-radio value="2">2 - 恰好一次</a-radio>
|
||||
</a-radio-group>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item field="mqtt_networks" label="区块链网络" extra="选择需要持续监听的区块链网络,多选">
|
||||
<a-checkbox-group v-model="networksSelected">
|
||||
<a-checkbox value="tron">Tron</a-checkbox>
|
||||
<a-checkbox value="bsc">Bsc</a-checkbox>
|
||||
<a-checkbox value="polygon">Polygon</a-checkbox>
|
||||
<a-checkbox value="ethereum">Ethereum</a-checkbox>
|
||||
<a-checkbox value="aptos">Aptos</a-checkbox>
|
||||
<a-checkbox value="solana">Solana</a-checkbox>
|
||||
<a-checkbox value="xlayer">XLayer</a-checkbox>
|
||||
<a-checkbox value="plasma">Plasma</a-checkbox>
|
||||
<a-checkbox value="arbitrum">Arbitrum</a-checkbox>
|
||||
<a-checkbox value="base">Base</a-checkbox>
|
||||
</a-checkbox-group>
|
||||
</a-form-item>
|
||||
|
||||
<a-form-item>
|
||||
<a-button type="primary" html-type="submit">提交</a-button>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-card>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Message } from "@arco-design/web-vue";
|
||||
import { setsConfAPI } from "@/api/modules/conf/index";
|
||||
|
||||
const emit = defineEmits(["refresh"]);
|
||||
const data = defineModel() as any;
|
||||
const rules = {
|
||||
mqtt_topic_prefix: [
|
||||
{
|
||||
validator: (value: string, callback: (error?: string) => void) => {
|
||||
if (!value) return callback();
|
||||
if (!/^[a-zA-Z0-9_/]+$/.test(value)) {
|
||||
return callback("Topic 前缀只允许包含字母、数字、下划线和斜杠");
|
||||
}
|
||||
if (value.startsWith("/") || value.endsWith("/")) {
|
||||
return callback("Topic 前缀不能以斜杠开头或结尾");
|
||||
}
|
||||
if (value.includes("//")) {
|
||||
return callback("Topic 前缀不能包含连续斜杠");
|
||||
}
|
||||
callback();
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const form = ref({
|
||||
mqtt_host: "",
|
||||
mqtt_port: "",
|
||||
mqtt_user: "",
|
||||
mqtt_pass: "",
|
||||
mqtt_publish_qos: "0",
|
||||
mqtt_networks: "",
|
||||
mqtt_topic_prefix: "bepusdt"
|
||||
});
|
||||
|
||||
const networksSelected = computed({
|
||||
get() {
|
||||
return form.value.mqtt_networks ? form.value.mqtt_networks.split(",").filter(Boolean) : [];
|
||||
},
|
||||
set(val: string[]) {
|
||||
form.value.mqtt_networks = val.join(",");
|
||||
}
|
||||
});
|
||||
|
||||
const onSubmit = async ({ errors }: ArcoDesign.ArcoSubmit) => {
|
||||
if (errors) return;
|
||||
|
||||
await setsConfAPI([
|
||||
{ key: "mqtt_host", value: form.value.mqtt_host },
|
||||
{ key: "mqtt_port", value: form.value.mqtt_port },
|
||||
{ key: "mqtt_user", value: form.value.mqtt_user },
|
||||
{ key: "mqtt_pass", value: form.value.mqtt_pass },
|
||||
{ key: "mqtt_publish_qos", value: form.value.mqtt_publish_qos },
|
||||
{ key: "mqtt_networks", value: form.value.mqtt_networks },
|
||||
{ key: "mqtt_topic_prefix", value: form.value.mqtt_topic_prefix || "bepusdt" }
|
||||
]);
|
||||
|
||||
Message.success("保存成功");
|
||||
emit("refresh");
|
||||
};
|
||||
|
||||
watch(
|
||||
() => data.value,
|
||||
() => {
|
||||
form.value.mqtt_host = data.value.mqtt_host ?? "";
|
||||
form.value.mqtt_port = data.value.mqtt_port ?? "";
|
||||
form.value.mqtt_user = data.value.mqtt_user ?? "";
|
||||
form.value.mqtt_pass = data.value.mqtt_pass ?? "";
|
||||
form.value.mqtt_publish_qos = data.value.mqtt_publish_qos ?? "0";
|
||||
form.value.mqtt_networks = data.value.mqtt_networks ?? "";
|
||||
form.value.mqtt_topic_prefix = data.value.mqtt_topic_prefix ?? "bepusdt";
|
||||
}
|
||||
);
|
||||
</script>
|
||||
@@ -79,7 +79,7 @@
|
||||
<template #label>
|
||||
<div class="label-with-tip">
|
||||
<span>Tron Grid Api Key</span>
|
||||
<a-tooltip content="使用个人独立的Api Key,可以提高扫块成功率" position="top">
|
||||
<a-tooltip content="配置独立 Api Key 可提高扫块稳定性,多个可用半角符逗号隔开。" position="top">
|
||||
<icon-question-circle class="tip-icon" />
|
||||
</a-tooltip>
|
||||
<span class="optional-tag">(可选)</span>
|
||||
@@ -87,7 +87,7 @@
|
||||
</template>
|
||||
<a-input
|
||||
v-model="formData.rpc_endpoint_tron_grid_api_key"
|
||||
placeholder="请输入 Tron Grid Api Key (可选)"
|
||||
placeholder="请输入 Tron Grid Api Key (可选),多个可用半角符逗号隔开"
|
||||
allow-clear
|
||||
size="small"
|
||||
class="network-input tron-input"
|
||||
|
||||
Reference in New Issue
Block a user