Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1cd01f7c8 | ||
|
|
507f201bd6 | ||
|
|
a7c6618437 | ||
|
|
0b8adb2ab4 | ||
|
|
0ef12745ea | ||
|
|
2988a6f1f4 | ||
|
|
ecd3a3983c | ||
|
|
34c005a3ab | ||
|
|
bfcfcc2f3c | ||
|
|
9d65fceaa9 | ||
|
|
bf5ff0fc5c | ||
|
|
98eedf378d | ||
|
|
99c9557ab3 | ||
|
|
a2b072d4be | ||
|
|
866d4ce193 | ||
|
|
b2d97b09a1 | ||
|
|
0680a3829a | ||
|
|
9aed022d43 | ||
|
|
dc4ef18526 | ||
|
|
a45f51be6f | ||
|
|
b098246a6f | ||
|
|
2cd7216423 | ||
|
|
0dc523cdf8 | ||
|
|
1e36375182 | ||
|
|
7587e87994 | ||
|
|
62758f2468 | ||
|
|
525f0f4079 | ||
|
|
ffe1e4a0b7 | ||
|
|
2d7fc6a6ec | ||
|
|
60a53b0e3a | ||
|
|
6a82a8550e | ||
|
|
5c70030dda | ||
|
|
9eb3b0092c | ||
|
|
8b8bddc99e | ||
|
|
185e14c41d | ||
|
|
7535347b0e | ||
|
|
d65d5d5613 | ||
|
|
bea39407f4 | ||
|
|
36c10092ea | ||
|
|
05b9ab33a2 | ||
|
|
ad2d3d1a89 | ||
|
|
1378c503a9 | ||
|
|
b20bea9ce9 | ||
|
|
4b86f847f6 | ||
|
|
987249485d | ||
|
|
5e8db1c73a | ||
|
|
b076f054e9 | ||
|
|
6c01039b9c | ||
|
|
9cc0a2b9dc | ||
|
|
bfb207fb34 | ||
|
|
a4186435c4 | ||
|
|
ae5e3fe5fb | ||
|
|
aeeaa7ef95 | ||
|
|
0e0392e352 | ||
|
|
a91e9ba87c | ||
|
|
16d8df2cc5 | ||
|
|
665d2c3ddb | ||
|
|
ec0aa7b29d | ||
|
|
67aba0e1a9 | ||
|
|
9c260a9f3d | ||
|
|
741009d69f | ||
|
|
8a4ce15e26 | ||
|
|
63c162bd2a | ||
|
|
9c5d7191e8 | ||
|
|
d633bd56ab | ||
|
|
f7bb776e99 | ||
|
|
b1a06b8e17 | ||
|
|
c57e80b8c3 | ||
|
|
e631969719 | ||
|
|
2df4b3c4af | ||
|
|
2a539c1146 | ||
|
|
ac5b1c2abf | ||
|
|
76980b6841 | ||
|
|
33b67fc850 | ||
|
|
13f9139055 | ||
|
|
b693e3b45f | ||
|
|
cd2064aea6 | ||
|
|
44ddaef00a | ||
|
|
8082c8863d | ||
|
|
20f173edc6 | ||
|
|
070f0073c7 | ||
|
|
80f3752021 | ||
|
|
bab60542dd | ||
|
|
f86e654a3c | ||
|
|
c98aaed49e | ||
|
|
3a567363f3 | ||
|
|
bfc5decae8 | ||
|
|
084122ef3a | ||
|
|
7730a9b9e7 | ||
|
|
41314b1ce4 | ||
|
|
49a8f2e862 | ||
|
|
b8c9711645 | ||
|
|
6f02cfbb91 | ||
|
|
79d9501c85 | ||
|
|
bb7546e647 | ||
|
|
616de30e97 | ||
|
|
b941e10da9 | ||
|
|
0c30873f26 | ||
|
|
946e20f274 | ||
|
|
3f4b9ead90 | ||
|
|
81f2966fb9 | ||
|
|
474c0d5ea8 | ||
|
|
eac611798a | ||
|
|
a32ef21be6 | ||
|
|
28097247ba | ||
|
|
d56e84e64d | ||
|
|
64f9f57470 | ||
|
|
f3a13db852 | ||
|
|
bbc323a9a3 | ||
|
|
557c9cdf65 | ||
|
|
e77caba177 | ||
|
|
12f3ecf6fe |
@@ -1,37 +0,0 @@
|
||||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main -trimpath -ldflags \"-s -w -buildid=\" ./main"
|
||||
delay = 3000
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
full_bin = ""
|
||||
include_dir = []
|
||||
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
send_interrupt = false
|
||||
stop_on_error = true
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
@@ -0,0 +1,23 @@
|
||||
name: Close inactive issues
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "30 1 * * *"
|
||||
|
||||
jobs:
|
||||
close-issues:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
days-before-issue-stale: 30
|
||||
days-before-issue-close: 7
|
||||
stale-issue-label: "stale"
|
||||
stale-issue-message: "此议题由于30天内没有任何活动,现在标记为过时。"
|
||||
close-issue-message: "此议题被标记为过时并且在7天内没有活动,因此已被关闭。请随时重新打开此议题以继续讨论。"
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,8 +1,8 @@
|
||||
name: docker-beta
|
||||
name: docker-nightly
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
schedule:
|
||||
- cron: '0 16 * * *'
|
||||
workflow_dispatch:
|
||||
env:
|
||||
APP_NAME: bepusdt
|
||||
DOCKER_HUB_USER: v03413
|
||||
@@ -25,7 +25,9 @@ jobs:
|
||||
username: ${{ env.DOCKER_HUB_USER }}
|
||||
password: ${{ secrets.DOCKER_HUB_BETA_TOKEN }}
|
||||
- name: Generate App Version
|
||||
run: echo "APP_VERSION=$(git rev-parse HEAD | cut -c 1-6)" >> $GITHUB_ENV
|
||||
run: |
|
||||
echo "APP_VERSION=$(git rev-parse HEAD | cut -c 1-6)" >> $GITHUB_ENV
|
||||
echo "APP_DATE=$(date +'%Y%m%d')" >> $GITHUB_ENV
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
@@ -38,5 +40,5 @@ jobs:
|
||||
APP_NAME=${{ env.APP_NAME }}
|
||||
APP_VERSION=${{ env.APP_VERSION }}
|
||||
tags: |
|
||||
${{ env.DOCKER_HUB_REPO }}:beta
|
||||
${{ env.DOCKER_HUB_REPO }}:beta-${{ env.APP_VERSION }}
|
||||
${{ env.DOCKER_HUB_REPO }}:nightly
|
||||
${{ env.DOCKER_HUB_REPO }}:nightly-${{ env.APP_DATE }}-${{ env.APP_VERSION }}
|
||||
@@ -6,55 +6,25 @@ on:
|
||||
- main
|
||||
tags:
|
||||
- v*
|
||||
|
||||
env:
|
||||
APP_NAME: bepusdt
|
||||
BUILD_DIR: build_assets
|
||||
|
||||
jobs:
|
||||
build-release:
|
||||
strategy:
|
||||
matrix:
|
||||
goos: [ linux ]
|
||||
goarch: [ amd64 ]
|
||||
fail-fast: false
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GOOS: ${{ matrix.goos }}
|
||||
GOARCH: ${{ matrix.goarch }}
|
||||
|
||||
steps:
|
||||
- name: Checkout codebase
|
||||
uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Show workflow information
|
||||
id: get_filename
|
||||
run: |
|
||||
export _NAME=$GOOS-$GOARCH
|
||||
echo "GOOS: $GOOS, GOARCH: $GOARCH, RELEASE_NAME: $_NAME"
|
||||
echo "OS_ARCH=$_NAME" >> $GITHUB_ENV
|
||||
- name: Git Fetch Tags
|
||||
run: git fetch --force --tags
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.22
|
||||
- name: Get project dependencies
|
||||
run: go mod download
|
||||
- name: Build Bepusdt
|
||||
run: |
|
||||
export CGO_ENABLED=0
|
||||
mkdir -p ${{ env.BUILD_DIR }}
|
||||
go build -v -o ${{ env.BUILD_DIR }}/${{ env.APP_NAME }} -trimpath -ldflags "-s -w -buildid=" ./main
|
||||
- name: Prepare package
|
||||
run: |
|
||||
cp -v ./docs/${{ env.APP_NAME }}.service ./${{ env.BUILD_DIR }}
|
||||
cp -v ./docs/Environment.conf ./${{ env.BUILD_DIR }}
|
||||
mv -v ./${{ env.BUILD_DIR }} ./${{ env.APP_NAME }}
|
||||
- name: Create ZIP archive
|
||||
run: zip -9vr ./${{ env.APP_NAME }}-${{ env.OS_ARCH }}.zip ./${{ env.APP_NAME }}
|
||||
- name: Upload files to GitHub release
|
||||
uses: svenstaro/upload-release-action@v2
|
||||
go-version: '1.24.3'
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ./${{ env.APP_NAME }}-${{ env.OS_ARCH }}.zip
|
||||
tag: ${{ github.ref }}
|
||||
distribution: goreleaser
|
||||
version: latest
|
||||
args: release --clean --verbose
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,2 +1,7 @@
|
||||
tmp
|
||||
.idea
|
||||
.air.toml
|
||||
.DS_Store
|
||||
.idea
|
||||
conf.toml
|
||||
# Added by goreleaser init:
|
||||
dist/
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
version: 2
|
||||
project_name: BEpusdt
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
builds:
|
||||
- env:
|
||||
- CGO_ENABLED=0
|
||||
main: ./main
|
||||
binary: bepusdt
|
||||
ldflags:
|
||||
- s -w -buildid=
|
||||
goos:
|
||||
- windows
|
||||
- linux
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
archives:
|
||||
- formats: [ tar.gz ]
|
||||
name_template: "{{.Os}}-{{.Arch}}{{if .Arm}}v{{.Arm}}{{end}}-{{ .ProjectName }}"
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
formats: [ zip ]
|
||||
files:
|
||||
- conf.example.toml
|
||||
- conf.simple.toml
|
||||
- src: docs/bepusdt.service
|
||||
dst: .
|
||||
strip_parent: true
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- "^docs:"
|
||||
- "^test:"
|
||||
release:
|
||||
footer: >-
|
||||
|
||||
---
|
||||
|
||||
Released by [GoReleaser](https://github.com/goreleaser/goreleaser).
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.23.2-alpine3.20 AS builder
|
||||
FROM golang:1.24.3-alpine3.20 AS builder
|
||||
|
||||
ENV GO111MODULE=on
|
||||
WORKDIR /go/release
|
||||
@@ -13,10 +13,11 @@ ENV TZ=Asia/Shanghai
|
||||
# 安装所需的依赖
|
||||
RUN apk add --no-cache tzdata ca-certificates
|
||||
|
||||
COPY --from=builder /go/release/bepusdt /runtime/bepusdt
|
||||
COPY --from=builder /go/release/bepusdt /usr/local/bin/bepusdt
|
||||
|
||||
# 设置时区
|
||||
RUN ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["/runtime/bepusdt"]
|
||||
ENTRYPOINT ["bepusdt"]
|
||||
CMD ["-conf", "/usr/local/bepusdt/conf.toml"]
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
**❗️特别声明:本项目乃作者研究学习的开源项目,不提供任何形式的收费服务(谨防诈骗);使用过程中遇见问题请提`issue`
|
||||
或群里交流,对于信息完整的问题看心情回复,作者很~~忙~~(懒)也不靠它吃饭,请自重!**
|
||||
或群里交流,针对信息完整的问题优先回复,作者很~~忙~~(懒)开源项目,请自重!**
|
||||
|
||||
---
|
||||
|
||||
# Bepusdt (Better Easy Payment Usdt)
|
||||
# BEpusdt (Better Easy Payment Usdt)
|
||||
|
||||
<p align="center">
|
||||
<img src="./static/img/tether.svg" width="15%" alt="tether">
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.gnu.org/licenses/gpl-3.0.html"><img src="https://img.shields.io/badge/license-GPLV3-blue" alt="license GPLV3"></a>
|
||||
<a href="https://golang.org"><img src="https://img.shields.io/badge/Golang-1.22-red" alt="Go version 1.21"></a>
|
||||
<a href="https://golang.org"><img src="https://img.shields.io/badge/Golang-1.23-red" alt="Go version 1.23"></a>
|
||||
<a href="https://github.com/gin-gonic/gin"><img src="https://img.shields.io/badge/Gin-v1.9-blue" alt="Gin Web Framework v1.9"></a>
|
||||
<a href="https://github.com/go-telegram-bot-api/telegram-bot-api"><img src="https://img.shields.io/badge/Telegram Bot-v5-lightgrey" alt="Golang Telegram Bot Api-v5"></a>
|
||||
<a href="https://github.com/v03413/bepusdt"><img src="https://img.shields.io/badge/Release-v1.9.21-green" alt="Release v1.9.21"></a>
|
||||
<a href="https://github.com/go-telegram/bot"><img src="https://img.shields.io/badge/Go_Telegram_Bot-v1.15-blue" alt="Golang Telegram Bot"></a>
|
||||
<a href="https://github.com/v03413/bepusdt"><img src="https://img.shields.io/github/v/release/v03413/bepusdt" alt="Release v1.19.1"></a>
|
||||
</p>
|
||||
|
||||
## 🪧 介绍
|
||||
@@ -23,174 +23,49 @@
|
||||
|
||||
## 🎉 新特性
|
||||
|
||||
- ✅ 具备`Epusdt`的所有特性,插件兼容无缝替换
|
||||
- ✅ USDT汇率实时同步交易所,且支持在以此基础上波动
|
||||
- ✅ 不依赖`MySQL Redis`环境,支持`Docker`部署
|
||||
- ✅ 支持非订单交易监控通知,钱包余额变动及时通知
|
||||
- ✅ 机器人支持查询当前实时汇率,计算实际浮动汇率
|
||||
- ✅ 机器人支持任意地址查询 USDT、TRX余额等信息
|
||||
- ✅ 订单收款成功和余额变动通知 支持指定群组推送
|
||||
- ✅ 支持可自定义USDT支付数额的精度,递增颗粒度
|
||||
- ✅ 底层直接采用区块扫描,不依赖三方API,秒级响应
|
||||
- ✅ <u>支持【TRX】收款</u>, TRX余额变动监控通知
|
||||
- ✅ 支持钱包地址 <u>能量代理</u>和<u>能量回收</u> 监控通知
|
||||
- ✅️ <u>原生支持易支付对接</u>,无需第三方插件依赖
|
||||
- ✅ 支持创建订单时动态钱包地址,不再强制固定
|
||||
- ⭕️ 待实现:支持<u>等待支付</u>和<u>支付超时</u> 订单状态回调
|
||||
### 🌟 目前支持收款类型
|
||||
|
||||
## 🛠 参数配置
|
||||
🔥 主流网络:TRON(`trx` `usdt.trc20`) Ethereum(`usdt.erc20`) BSC(`usdt.bep20`)
|
||||
⚡ 其他网络:Polygon(`usdt.polygon`) X-Layer(`usdt.xlayer`) Solana(`usdt.solana`) Aptos(`usdt.aptos`)
|
||||
|
||||
Bepusdt 所有参数都是以传递环境变量的方式进行配置,大部分参数含默认值,少量配置即可直接使用!
|
||||
|
||||
### 参数列表
|
||||
|
||||
| 参数名称 | 默认值 | 用法说明 |
|
||||
|----------------------|----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| EXPIRE_TIME | `600` | 订单有效期,单位秒 |
|
||||
| USDT_RATE | `6.4` | USDT汇率,默认留空则获取Okx交易所的汇率(每分钟同步一次),支持多种写法,如:`7.4` 表示固定7.4、`~1.02`表示最新汇率上浮2%、`~0.97`表示最新汇率下浮3%、`+0.3`表示最新加0.3、`-0.2`表示最新减0.2,以此类推;如参数错误则使用固定值6.4 |
|
||||
| USDT_ATOM | `0.01` | `0.01`表示支付数额保留两位小数,相同金额时递增颗粒度为`0.01`,依次类推,如无特殊需求不建议修改。 |
|
||||
| TRX_RATE | `0.95` | **同 USDT_RATE** |
|
||||
| TRX_ATOM | `0.01` | **同 USDT_ATOM** |
|
||||
| AUTH_TOKEN | `123234` | 认证Token,对接会用到这个参数 |
|
||||
| LISTEN | `:8080` | 服务器HTTP监听地址 |
|
||||
| TRADE_IS_CONFIRMED | `0` | 是否需要网络确认,禁用可以提高回调速度,启用则可以防止交易失败 |
|
||||
| APP_URI | 空 | 应用访问地址,留空则系统自动获取,前端收银台会用到,建议设置,例如:https://token-pay.example.com |
|
||||
| WALLET_ADDRESS | 空 | 启动时需要添加的钱包地址,多个请用半角符逗号`,`分开;当然,同样也支持通过机器人添加。 |
|
||||
| TG_BOT_TOKEN | 空 | Telegram Bot Token,**必须设置**,否则无法使用 |
|
||||
| TG_BOT_ADMIN_ID | 空 | Telegram Bot 管理员ID,**必须设置**,否则无法使用 |
|
||||
| TG_BOT_GROUP_ID | 空 | Telegram 群组ID,设置之后机器人会将交易消息会推送到此群 |
|
||||
| PAYMENT_AMOUNT_RANGE | `0.01,99999` | 支付监控的允许数额范围(闭区间),设置合理数值可避免一些诱导式诈骗交易提醒 |
|
||||
| TRON_GRPC_NODE | `18.141.79.38:50051` | Tron区块网络的GRPC节点,可选列表:https://developers.tron.network/docs/networks#public-node |
|
||||
| STATIC_PATH | 空 | 静态资源路径,例如:`/root/bepusdt/static`;通过此参数可自定义模板,参考`static`目录,如非必要不建议修改。 |
|
||||
|
||||
**Ps:所以综上所述,必须设置的参数有`TG_BOT_TOKEN TG_BOT_ADMIN_ID`,否则无法使用!**
|
||||
- ✅ 完全兼容 `Epusdt`,插件可无缝替换
|
||||
- ✅ 实时同步 USDT 汇率,支持自定义浮动
|
||||
- ✅ 无`MySQL Redis`依赖,支持`Docker`部署
|
||||
- ✅ 支持非订单交易监控,钱包余额变动通知
|
||||
- ✅ 支持自定义 USDT 支付精度与递增颗粒度
|
||||
- ✅ 底层区块扫描,无第三方 API,秒级响应
|
||||
- ✅ 支持波场能量代理与能量回收监控通知
|
||||
- ✅ 原生支持易支付对接,无三方插件依赖
|
||||
- ✅ 支持创建订单时 自定义超时 钱包地址
|
||||
- ✅ 完整支持`等待支付 支付超时`回调
|
||||
- ✅ 支持事件`WebHook` 方便多方协同
|
||||
|
||||
## 🚀 安装部署
|
||||
|
||||
- [Docker 安装教程(强烈推荐🔥)](./docs/docker.md)
|
||||
- [异次元发卡对接教程 🌟](./docs/acg-faka.md)
|
||||
- [萌次元商城系统对接 🌟](./docs/mcy-shop.md)
|
||||
- [独角数卡对接教程 🌟](./docs/dujiaoka.md)
|
||||
- [https 配置教程](./docs/ssl.md)
|
||||
- [Linux 手动安装教程](./docs/systemd.md)
|
||||
- [Linux 时钟同步配置](./docs/systemd-timesyncd.md)
|
||||
- [彩虹易支付后台对接教程](./docs/epay.md)
|
||||
- 安装:[Docker](./docs/docker.md)・[Linux](./docs/systemd.md)・1Panel・宝塔
|
||||
- 对接:[独角数卡](./docs/dujiaoka.md)・[异次元](./docs/acg-faka.md)・[萌次元](./docs/mcy-shop.md)・[彩虹易支付](https://github.com/v03413/Epay-BEpusdt)
|
||||
- 开发:[API对接](./docs/api.md)・[订单回调](./docs/notify-epusdt.md)・[Webhook 事件](./docs/webhook.md)
|
||||
- 其它:[https 配置](./docs/ssl.md)・[Linux 时钟同步](./docs/systemd-timesyncd.md)
|
||||
|
||||
## 🖼 功能截图
|
||||
|
||||

|
||||
|
||||
## 🤔 常见问题
|
||||
|
||||
### 如何获取参数 TG_BOT_ADMIN_ID
|
||||
|
||||
Telegram 搜索`@userinfobot`机器人并启用,返回的ID就是`TG_BOT_ADMIN_ID`
|
||||
Telegram 搜索加入群`@BEpusdtChat`,随后发送命令`/info`,返回的`ID`就是`TG_BOT_ADMIN_ID`
|
||||
|
||||
## ⚠️ 特别注意
|
||||
|
||||
- 订单交易强依赖时间,请确保服务器时间准确性,否则可能导致订单异常!
|
||||
- 部分功能依赖网络,请确保服务器网络纯洁性,否则可能导致功能异常!
|
||||
|
||||
## 📚 接口文档
|
||||
|
||||
<details>
|
||||
<summary>创建订单</summary>
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/create-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 可根据实际情况传入收款地址,亦可留空
|
||||
"trade_type": "usdt.trc20", // usdt.trc20(默认) 或 tron.trx
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": 28.88, // 请求支付金额,CNY
|
||||
"signature":"123456abcd", // 签名
|
||||
"notify_url": "https://example.com/callback", // 回调地址
|
||||
"redirect_url": "https://example.com/callback" // 支付成功跳转地址
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415", // 本地交易ID
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": "28.88", // 请求支付金额,CNY
|
||||
"actual_amount": "10", // 实际支付数额 usdt or trx
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 收款地址
|
||||
"expiration_time": 1200, // 订单有效期,秒
|
||||
"payment_url": "https://example.com//pay/checkout-counter/b3d2477c-d945-41da-96b7-f925bbd1b415" // 收银台地址
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>取消订单</summary>
|
||||
|
||||
商户端系统可以通过此接口取消订单,取消后,系统将不再监控此订单,同时释放对应金额占用。
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/cancel-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ", // 交易ID
|
||||
"signature":"123456abcd" // 签名内容
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ"
|
||||
},
|
||||
"message": "success",
|
||||
"request_id": "",
|
||||
"status_code": 200
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>回调通知</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415",
|
||||
"order_id": "787240927112940881",
|
||||
"amount": 28.88,
|
||||
"actual_amount": 10,
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
"block_transaction_id": "12ef6267b42e43959795cf31808d0cc72b3d0a48953ed19c61d4b6665a341d10",
|
||||
"signature": "123456abcd",
|
||||
"status": 2 // 1:等待支付 2:支付成功 3:支付超时
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 🏝️ 交流反馈
|
||||
|
||||
- Telegram 频道:[https://t.me/bepusdt](https://t.me/bepusdt)
|
||||
- Telegram 群组:[https://t.me/bepusdt_group](https://t.me/bepusdt_group)
|
||||
- Telegram 群组:[https://t.me/BEpusdtChat](https://t.me/BEpusdtChat)
|
||||
- Telegram 频道:[https://t.me/BEpusdtChannel](https://t.me/BEpusdtChannel)
|
||||
|
||||
## 🙏 感谢
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"time"
|
||||
)
|
||||
|
||||
var api *bot.Bot
|
||||
var err error
|
||||
|
||||
func Init() error {
|
||||
var opts = []bot.Option{
|
||||
//bot.WithDebug(),
|
||||
bot.WithCheckInitTimeout(time.Minute),
|
||||
bot.WithMiddlewares([]bot.Middleware{updateFilter}...),
|
||||
bot.WithDefaultHandler(defaultHandle),
|
||||
}
|
||||
|
||||
api, err = bot.New(conf.BotToken(), opts...)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func Start() {
|
||||
var ctx, cancel = context.WithCancel(context.Background())
|
||||
|
||||
defer cancel()
|
||||
|
||||
var me, err2 = api.GetMe(ctx)
|
||||
if err2 != nil {
|
||||
panic(err2)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
{
|
||||
api.RegisterHandler(bot.HandlerTypeMessageText, cmdGetId, bot.MatchTypeCommand, cmdGetIdHandle)
|
||||
api.RegisterHandler(bot.HandlerTypeMessageText, cmdStart, bot.MatchTypeCommand, cmdStartHandle)
|
||||
api.RegisterHandler(bot.HandlerTypeMessageText, cmdState, bot.MatchTypeCommand, cmdStateHandle)
|
||||
api.RegisterHandler(bot.HandlerTypeMessageText, cmdOrder, bot.MatchTypeCommand, cmdOrderHandle)
|
||||
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbOrderDetail, bot.MatchTypePrefix, cbOrderDetailAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbWallet, bot.MatchTypePrefix, cbWalletAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddress, bot.MatchTypePrefix, cbAddressAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressAdd, bot.MatchTypePrefix, cbAddressAddAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressType, bot.MatchTypePrefix, cbAddressTypeAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressDelete, bot.MatchTypePrefix, cbAddressDelAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressBack, bot.MatchTypePrefix, cbAddressBackAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressEnable, bot.MatchTypePrefix, cbAddressEnableAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressDisable, bot.MatchTypePrefix, cbAddressDisableAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbAddressOtherNotify, bot.MatchTypePrefix, cbAddressOtherNotifyAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbMarkNotifySucc, bot.MatchTypePrefix, cbMarkNotifySuccAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbOrderNotifyRetry, bot.MatchTypePrefix, dbOrderNotifyRetryAction)
|
||||
api.RegisterHandler(bot.HandlerTypeCallbackQueryData, cbOrderList, bot.MatchTypePrefix, cbOrderListAction)
|
||||
}
|
||||
|
||||
_, err = api.SetMyCommands(ctx, &bot.SetMyCommandsParams{
|
||||
Commands: []models.BotCommand{
|
||||
{Command: cmdGetId, Description: "获取ID"},
|
||||
{Command: cmdStart, Description: "开始使用"},
|
||||
{Command: cmdState, Description: "收款状态"},
|
||||
{Command: cmdOrder, Description: "订单列表"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
panic("SetMyCommandsParams Error: " + err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
_, err = api.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true})
|
||||
if err != nil {
|
||||
panic("DeleteWebhook Error: " + err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
SendMessage(&bot.SendMessageParams{ChatID: conf.BotNotifyTarget(), Text: Welcome()})
|
||||
|
||||
fmt.Println(fmt.Sprintf("Bot UserName: %s %s%s", me.Username, me.FirstName, me.LastName))
|
||||
|
||||
api.Start(ctx)
|
||||
}
|
||||
|
||||
func SendMessage(p *bot.SendMessageParams) {
|
||||
if p.ChatID == nil {
|
||||
p.ChatID = conf.BotAdminID()
|
||||
}
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*5)
|
||||
defer cancel()
|
||||
|
||||
_, err := api.SendMessage(ctx, p)
|
||||
if err != nil {
|
||||
|
||||
log.Warn("Bot Send Message Error:", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func DeleteMessage(ctx context.Context, b *bot.Bot, p *bot.DeleteMessageParams) {
|
||||
_, err := b.DeleteMessage(ctx, p)
|
||||
if err != nil {
|
||||
|
||||
log.Warn("Bot Delete Message Error:", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func EditMessageText(ctx context.Context, b *bot.Bot, p *bot.EditMessageTextParams) {
|
||||
_, err := b.EditMessageText(ctx, p)
|
||||
if err != nil {
|
||||
|
||||
log.Warn("BotEditMessageText Error:", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func EditMessageReplyMarkup(ctx context.Context, b *bot.Bot, p *bot.EditMessageReplyMarkupParams) {
|
||||
_, err := b.EditMessageReplyMarkup(ctx, p)
|
||||
if err != nil {
|
||||
|
||||
log.Warn("BotEditMessageReplyMarkup Error:", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/go-cache"
|
||||
"gorm.io/gorm"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cbWallet = "wallet"
|
||||
const cbAddress = "address_act"
|
||||
const cbAddressAdd = "address_add"
|
||||
const cbAddressType = "address_type"
|
||||
const cbAddressEnable = "address_enable"
|
||||
const cbAddressDisable = "address_disable"
|
||||
const cbAddressDelete = "address_del"
|
||||
const cbAddressBack = "address_back"
|
||||
const cbAddressOtherNotify = "address_other_notify"
|
||||
const cbOrderDetail = "order_detail"
|
||||
const cbOrderList = "order_list"
|
||||
const cbMarkNotifySucc = "mark_notify_succ"
|
||||
const cbOrderNotifyRetry = "order_notify_retry"
|
||||
|
||||
func cbWalletAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var address = ctx.Value("args").([]string)[1]
|
||||
|
||||
var text = bot.EscapeMarkdownUnescaped("暂不支持...")
|
||||
if help.IsValidTronAddress(address) {
|
||||
text = getTronWalletInfo(address)
|
||||
}
|
||||
|
||||
var params = bot.SendMessageParams{ChatID: u.CallbackQuery.Message.Message.Chat.ID, ParseMode: models.ParseModeMarkdown}
|
||||
if text != "" {
|
||||
params.Text = text
|
||||
}
|
||||
|
||||
DeleteMessage(ctx, b, &bot.DeleteMessageParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
})
|
||||
SendMessage(¶ms)
|
||||
}
|
||||
|
||||
func cbAddressAddAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var tradeType = ctx.Value("args").([]string)[1]
|
||||
var k = fmt.Sprintf("%s_%d_trade_type", cbAddressAdd, u.CallbackQuery.Message.Message.Chat.ID)
|
||||
|
||||
cache.Set(k, tradeType, -1)
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
Text: replayAddressText,
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
ReplyMarkup: &models.ForceReply{
|
||||
ForceReply: true,
|
||||
Selective: true,
|
||||
InputFieldPlaceholder: fmt.Sprintf("钱包地址(%s)", tradeType),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func cbAddressTypeAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var btn [][]models.InlineKeyboardButton
|
||||
for _, v := range model.SupportTradeTypes {
|
||||
btn = append(btn, []models.InlineKeyboardButton{
|
||||
{
|
||||
Text: fmt.Sprintf("💎 %s", strings.ToUpper(v)),
|
||||
CallbackData: fmt.Sprintf("%s|%s", cbAddressAdd, v),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
Text: "*🏝️ 请选择添加的钱包地址类型:*",
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{InlineKeyboard: btn},
|
||||
})
|
||||
}
|
||||
|
||||
func cbAddressDelAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var id = ctx.Value("args").([]string)[1]
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
// 删除钱包地址
|
||||
wa.Delete()
|
||||
|
||||
// 删除历史消息
|
||||
DeleteMessage(ctx, b, &bot.DeleteMessageParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
})
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle(ctx, b, u)
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var id = ctx.Value("args").([]string)[1]
|
||||
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
var otherTextLabel = "🟢已启用 非订单交易监控通知"
|
||||
if wa.OtherNotify != 1 {
|
||||
otherTextLabel = "🔴已禁用 非订单交易监控通知"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf("> %s", wa.Address)
|
||||
if help.IsValidTronAddress(wa.Address) {
|
||||
text = getTronWalletInfo(wa.Address)
|
||||
}
|
||||
if help.IsValidEvmAddress(wa.Address) {
|
||||
text = getEvmWalletInfo(wa)
|
||||
}
|
||||
|
||||
EditMessageText(ctx, b, &bot.EditMessageTextParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "✅启用", CallbackData: cbAddressEnable + "|" + id},
|
||||
models.InlineKeyboardButton{Text: "❌禁用", CallbackData: cbAddressDisable + "|" + id},
|
||||
models.InlineKeyboardButton{Text: "⛔️删除", CallbackData: cbAddressDelete + "|" + id},
|
||||
models.InlineKeyboardButton{Text: "🔙返回", CallbackData: cbAddressBack + "|" + cast.ToString(u.CallbackQuery.Message.Message.ID)},
|
||||
},
|
||||
{
|
||||
models.InlineKeyboardButton{Text: otherTextLabel, CallbackData: cbAddressOtherNotify + "|" + id},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressBackAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
DeleteMessage(ctx, b, &bot.DeleteMessageParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: cast.ToInt(ctx.Value("args").([]string)[1]),
|
||||
})
|
||||
|
||||
cmdStartHandle(ctx, b, u)
|
||||
}
|
||||
|
||||
func cbAddressEnableAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var id = ctx.Value("args").([]string)[1]
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
// 修改地址状态
|
||||
wa.SetStatus(model.StatusEnable)
|
||||
|
||||
// 删除历史消息
|
||||
DeleteMessage(ctx, b, &bot.DeleteMessageParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
})
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle(ctx, b, u)
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressDisableAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var id = ctx.Value("args").([]string)[1]
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
// 修改地址状态
|
||||
wa.SetStatus(model.StatusDisable)
|
||||
|
||||
// 删除历史消息
|
||||
DeleteMessage(ctx, b, &bot.DeleteMessageParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
})
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle(ctx, b, u)
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressOtherNotifyAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var id = ctx.Value("args").([]string)[1]
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
if wa.OtherNotify == 1 {
|
||||
wa.SetOtherNotify(model.OtherNotifyDisable)
|
||||
} else {
|
||||
wa.SetOtherNotify(model.OtherNotifyEnable)
|
||||
}
|
||||
|
||||
DeleteMessage(ctx, b, &bot.DeleteMessageParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
})
|
||||
|
||||
cmdStartHandle(ctx, b, u)
|
||||
}
|
||||
}
|
||||
|
||||
func cbOrderDetailAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
args := ctx.Value("args").([]string)
|
||||
if len(args) < 2 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var order model.TradeOrders
|
||||
if err := model.DB.Where("trade_id = ?", args[1]).First(&order).Error; err != nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
urlInfo, err := url.Parse(order.NotifyUrl)
|
||||
if err != nil {
|
||||
log.Error("商户网站地址解析错误:" + err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 确定回调状态标签
|
||||
var notifyStateLabel string
|
||||
switch {
|
||||
case order.Status == model.OrderStatusWaiting:
|
||||
notifyStateLabel = order.GetStatusLabel()
|
||||
case order.Status == model.OrderStatusExpired:
|
||||
notifyStateLabel = "🈚️没有回调"
|
||||
case order.NotifyState == model.OrderNotifyStateSucc:
|
||||
notifyStateLabel = "✅回调成功"
|
||||
default:
|
||||
notifyStateLabel = "❌回调失败"
|
||||
}
|
||||
|
||||
site := &url.URL{Scheme: urlInfo.Scheme, Host: urlInfo.Host}
|
||||
markup := models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
{Text: "🌏商户网站", URL: site.String()},
|
||||
{Text: "📝交易明细", URL: order.GetDetailUrl()},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if order.Status == model.OrderStatusSuccess && order.NotifyState == model.OrderNotifyStateFail {
|
||||
markup.InlineKeyboard = append(markup.InlineKeyboard, []models.InlineKeyboardButton{
|
||||
{Text: "✅标记回调成功", CallbackData: cbMarkNotifySucc + "|" + order.TradeId},
|
||||
{Text: "⚡️立刻回调重试", CallbackData: cbOrderNotifyRetry + "|" + order.TradeId},
|
||||
})
|
||||
}
|
||||
|
||||
if len(args) == 3 {
|
||||
markup.InlineKeyboard = append(markup.InlineKeyboard, []models.InlineKeyboardButton{
|
||||
{Text: "📦返回订单列表", CallbackData: fmt.Sprintf("%s|%s", cbOrderList, args[2])},
|
||||
})
|
||||
}
|
||||
|
||||
text := fmt.Sprintf("```\n"+
|
||||
"⛵️系统订单:%s\n"+
|
||||
"📌商户订单:%s\n"+
|
||||
"📊交易汇率:%s(%s)\n"+
|
||||
"💲交易数额:%s\n"+
|
||||
"💰交易金额:%.2f CNY\n"+
|
||||
"💍交易类别:%s\n"+
|
||||
"🌏商户网站:%s\n"+
|
||||
"🔋收款状态:%s\n"+
|
||||
"🍀回调状态:%s\n"+
|
||||
"💎️收款地址:%s\n"+
|
||||
"🕒创建时间:%s\n"+
|
||||
"🕒失效时间:%s\n"+
|
||||
"⚖️️确认时间:%s\n"+
|
||||
"```",
|
||||
order.TradeId,
|
||||
order.OrderId,
|
||||
order.TradeRate, conf.GetUsdtRate(),
|
||||
order.Amount,
|
||||
order.Money,
|
||||
strings.ToUpper(order.TradeType),
|
||||
site.String(),
|
||||
order.GetStatusLabel(),
|
||||
notifyStateLabel,
|
||||
help.MaskAddress(order.Address),
|
||||
order.CreatedAt.Format(time.DateTime),
|
||||
order.ExpiredAt.Format(time.DateTime),
|
||||
order.ConfirmedAt.Format(time.DateTime))
|
||||
|
||||
EditMessageText(ctx, b, &bot.EditMessageTextParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: markup,
|
||||
})
|
||||
}
|
||||
|
||||
func cbOrderListAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
page := cast.ToInt(ctx.Value("args").([]string)[1])
|
||||
buttons := buildOrderListWithNavigation(page)
|
||||
|
||||
EditMessageText(ctx, b, &bot.EditMessageTextParams{
|
||||
ChatID: u.CallbackQuery.Message.Message.Chat.ID,
|
||||
MessageID: u.CallbackQuery.Message.Message.ID,
|
||||
Text: orderListText,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: buttons},
|
||||
})
|
||||
}
|
||||
|
||||
func cbMarkNotifySuccAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var tradeId = ctx.Value("args").([]string)[1]
|
||||
|
||||
model.DB.Model(&model.TradeOrders{}).Where("trade_id = ?", tradeId).Update("notify_state", model.OrderNotifyStateSucc)
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
Text: fmt.Sprintf("✅订单(`%s`)回调手动标记成功,后续将不会再次回调。", tradeId),
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
})
|
||||
}
|
||||
|
||||
func dbOrderNotifyRetryAction(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var tradeId = ctx.Value("args").([]string)[1]
|
||||
|
||||
model.DB.Model(&model.TradeOrders{}).Where("trade_id = ?", tradeId).UpdateColumn("notify_num", gorm.Expr("notify_num - ?", 1))
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
Text: fmt.Sprintf("🪧订单(`%s`)即将开始回调重试,稍后可再次查询。", tradeId),
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
})
|
||||
}
|
||||
|
||||
func getTronWalletInfo(address string) string {
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
resp, err := client.Get("https://apilist.tronscanapi.com/api/accountv2?address=" + address)
|
||||
if err != nil {
|
||||
log.Error("GetWalletInfoByAddress client.Get(url)", err)
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
log.Error("GetWalletInfoByAddress resp.StatusCode != 200", resp.StatusCode, err)
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Error("GetWalletInfoByAddress io.ReadAll(resp.Body)", err)
|
||||
|
||||
return ""
|
||||
}
|
||||
result := gjson.ParseBytes(all)
|
||||
|
||||
var dateCreated = time.UnixMilli(result.Get("date_created").Int())
|
||||
var latestOperationTime = time.UnixMilli(result.Get("latest_operation_time").Int())
|
||||
var netRemaining = result.Get("bandwidth.netRemaining").Int() + result.Get("bandwidth.freeNetRemaining").Int()
|
||||
var netLimit = result.Get("bandwidth.netLimit").Int() + result.Get("bandwidth.freeNetLimit").Int()
|
||||
var text = `
|
||||
>💰 TRX余额:0.00 TRX
|
||||
>💲 USDT余额:0.00 USDT
|
||||
>📬 交易数量:` + result.Get("totalTransactionCount").String() + `
|
||||
>📈 转账数量:↑ ` + result.Get("transactions_out").String() + ` ↓ ` + result.Get("transactions_in").String() + `
|
||||
>📡 宽带资源:` + fmt.Sprintf("%v", netRemaining) + ` / ` + fmt.Sprintf("%v", netLimit) + `
|
||||
>🔋 能量资源:` + result.Get("bandwidth.energyRemaining").String() + ` / ` + result.Get("bandwidth.energyLimit").String() + `
|
||||
>⏰ 创建时间:` + help.Ec(dateCreated.Format(time.DateTime)) + `
|
||||
>⏰ 最后活动:` + help.Ec(latestOperationTime.Format(time.DateTime)) + `
|
||||
>☘️ 查询地址:` + address
|
||||
|
||||
for _, v := range result.Get("withPriceTokens").Array() {
|
||||
if v.Get("tokenName").String() == "trx" {
|
||||
text = strings.Replace(text, "0.00 TRX", help.Ec(fmt.Sprintf("%.2f TRX", v.Get("balance").Float()/1000000)), 1)
|
||||
}
|
||||
if v.Get("tokenName").String() == "Tether USD" {
|
||||
text = strings.Replace(text, "0.00 USDT", help.Ec(fmt.Sprintf("%.2f USDT", v.Get("balance").Float()/1000000)), 1)
|
||||
}
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
func getEvmWalletInfo(wa model.WalletAddress) string {
|
||||
|
||||
return fmt.Sprintf(">💲余额:%s\\(%s\\)\n>☘️地址:`%s`", help.Ec(evmUSDTBalanceOf(wa)), help.Ec(wa.TradeType), wa.Address)
|
||||
}
|
||||
|
||||
func evmUSDTBalanceOf(wa model.WalletAddress) string {
|
||||
var jsonData = []byte(fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"method":"eth_call","params":[{"from":"0x0000000000000000000000000000000000000000","data":"0x70a08231000000000000000000000000%s","to":"%s"},"latest"]}`,
|
||||
time.Now().Unix(), strings.ToLower(strings.Trim(wa.Address, "0x")), strings.ToLower(wa.GetUsdtContract())))
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
resp, err := client.Post(wa.GetEvmRpcEndpoint(), "application/json", bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
log.Warn("Error Post response:", err)
|
||||
|
||||
return "0.00"
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("Error reading response body:", err)
|
||||
|
||||
return "0.00"
|
||||
}
|
||||
|
||||
var data = gjson.ParseBytes(body)
|
||||
var result = data.Get("result").String()
|
||||
|
||||
return decimal.NewFromBigInt(help.HexStr2Int(result), wa.GetUsdtDecimals()).String()
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/task/rate"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cmdGetId = "id"
|
||||
const cmdStart = "start"
|
||||
const cmdState = "state"
|
||||
const cmdOrder = "order"
|
||||
|
||||
const replayAddressText = "🚚 请发送需要添加的钱包地址"
|
||||
const orderListText = "*现有订单列表,点击可查看详细信息,不同颜色对应着不同支付状态!*\n>🟢收款成功 🔴交易过期 🟡等待支付 ⚪️订单取消\n>🌟按钮内容 订单创建时间 订单号末八位 交易金额"
|
||||
const orderPageSize = 8
|
||||
|
||||
func cmdGetIdHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: u.Message.Chat.ID,
|
||||
Text: "您的ID: " + fmt.Sprintf("`%v`(点击复制)", u.Message.Chat.ID),
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyParameters: &models.ReplyParameters{
|
||||
MessageID: u.Message.ID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func cmdStartHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var was []model.WalletAddress
|
||||
var btn [][]models.InlineKeyboardButton
|
||||
if model.DB.Find(&was).Error == nil {
|
||||
for _, wa := range was {
|
||||
var text = fmt.Sprintf("[✅已启用] %s %s", help.MaskAddress2(wa.Address), wa.TradeType)
|
||||
if wa.Status == model.StatusDisable {
|
||||
text = fmt.Sprintf("[❌已禁用] %s %s", help.MaskAddress2(wa.Address), wa.TradeType)
|
||||
}
|
||||
|
||||
btn = append(btn, []models.InlineKeyboardButton{
|
||||
{Text: text, CallbackData: fmt.Sprintf("%s|%v", cbAddress, wa.ID)},
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
var chatID any
|
||||
if u.Message != nil {
|
||||
chatID = u.Message.Chat.ID
|
||||
}
|
||||
if u.CallbackQuery != nil {
|
||||
chatID = u.CallbackQuery.Message.Message.Chat.ID
|
||||
}
|
||||
|
||||
btn = append(btn, []models.InlineKeyboardButton{{Text: "👛 收款地址添加", CallbackData: cbAddressType}})
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: chatID,
|
||||
Text: "🌟点击钱包 按提示进行操作",
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: btn},
|
||||
})
|
||||
}
|
||||
|
||||
func cmdStateHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
var rows []model.TradeOrders
|
||||
model.DB.Where("created_at > ?", time.Now().Format(time.DateOnly)).Find(&rows)
|
||||
var succ uint64
|
||||
var money, trx, uTrc20, uErc20, uBep20, uXlayer, uSolana, uPol, uAptos float64
|
||||
for _, o := range rows {
|
||||
if o.Status != model.OrderStatusSuccess {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
succ++
|
||||
money += o.Money
|
||||
|
||||
var amount = cast.ToFloat64(o.Amount)
|
||||
if o.TradeType == model.OrderTradeTypeTronTrx {
|
||||
trx += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtBep20 {
|
||||
uBep20 += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtTrc20 {
|
||||
uTrc20 += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtErc20 {
|
||||
uErc20 += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtPolygon {
|
||||
uPol += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtXlayer {
|
||||
uXlayer += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtSolana {
|
||||
uSolana += amount
|
||||
}
|
||||
if o.TradeType == model.OrderTradeTypeUsdtAptos {
|
||||
uAptos += amount
|
||||
}
|
||||
}
|
||||
|
||||
var base = "```" + `
|
||||
🎁今日成功订单:%d
|
||||
💎今日总数订单:%d
|
||||
💰今日收款汇总
|
||||
- %.2f CNY
|
||||
- %.2f TRX
|
||||
- %.2f USDT.Trc20
|
||||
- %.2f USDT.Erc20
|
||||
- %.2f USDT.Bep20
|
||||
- %.2f USDT.Aptos
|
||||
- %.2f USDT.Xlayer
|
||||
- %.2f USDT.Solana
|
||||
- %.2f USDT.Polygon
|
||||
🌟扫块成功数据
|
||||
- Bsc %s
|
||||
- Tron %s
|
||||
- Aptos %s
|
||||
- Xlayer %s
|
||||
- Solana %s
|
||||
- Polygon %s
|
||||
- Ethereum %s
|
||||
-----------------------
|
||||
🪧基准汇率(TRX):%v
|
||||
🪧基准汇率(USDT):%v
|
||||
✅订单汇率(TRX):%v
|
||||
✅订单汇率(USDT):%v
|
||||
-----------------------
|
||||
` + "```" + `
|
||||
>基准汇率:来源于交易所的原始数据。
|
||||
>订单汇率:订单创建过程中实际使用的汇率。
|
||||
>扫块成功数据:如果该值过低,说明您的服务器与区块链网络连接不稳定,请尝试更换区块节点。
|
||||
`
|
||||
|
||||
var text = fmt.Sprintf(base,
|
||||
succ,
|
||||
len(rows),
|
||||
money,
|
||||
trx,
|
||||
uTrc20,
|
||||
uErc20,
|
||||
uBep20,
|
||||
uAptos,
|
||||
uXlayer,
|
||||
uSolana,
|
||||
uPol,
|
||||
conf.GetBlockSuccRate(conf.Bsc),
|
||||
conf.GetBlockSuccRate(conf.Tron),
|
||||
conf.GetBlockSuccRate(conf.Aptos),
|
||||
conf.GetBlockSuccRate(conf.Xlayer),
|
||||
conf.GetBlockSuccRate(conf.Solana),
|
||||
conf.GetBlockSuccRate(conf.Polygon),
|
||||
conf.GetBlockSuccRate(conf.Ethereum),
|
||||
cast.ToString(rate.GetOkxTrxRawRate()),
|
||||
cast.ToString(rate.GetOkxUsdtRawRate()),
|
||||
cast.ToString(rate.GetTrxCalcRate()),
|
||||
cast.ToString(rate.GetUsdtCalcRate()),
|
||||
)
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: u.Message.Chat.ID,
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
})
|
||||
}
|
||||
|
||||
func cmdOrderHandle(ctx context.Context, b *bot.Bot, u *models.Update) {
|
||||
buttons := buildOrderListWithNavigation(1)
|
||||
if buttons == nil {
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: u.Message.Chat.ID,
|
||||
Text: "*订单列表暂时为空!*",
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
ChatID: u.Message.Chat.ID,
|
||||
Text: orderListText,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: buttons},
|
||||
})
|
||||
}
|
||||
|
||||
func buildOrderListWithNavigation(page int) [][]models.InlineKeyboardButton {
|
||||
buttons, total := buildOrderButtons(page, orderPageSize)
|
||||
if buttons == nil {
|
||||
return nil
|
||||
}
|
||||
return append(buttons, buildPageNavigation(page, total, orderPageSize)...)
|
||||
}
|
||||
|
||||
func buildOrderButtons(page, size int) ([][]models.InlineKeyboardButton, int) {
|
||||
var total int64
|
||||
model.DB.Model(&model.TradeOrders{}).Count(&total)
|
||||
if total == 0 {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
var orders []model.TradeOrders
|
||||
model.DB.Order("id desc").Offset((page - 1) * size).Limit(size).Find(&orders)
|
||||
|
||||
buttons := make([][]models.InlineKeyboardButton, 0, len(orders))
|
||||
for _, o := range orders {
|
||||
orderId := o.OrderId
|
||||
if len(orderId) > 8 {
|
||||
orderId = orderId[len(orderId)-8:]
|
||||
}
|
||||
buttons = append(buttons, []models.InlineKeyboardButton{{
|
||||
Text: fmt.Sprintf("%s〚%s〛%s 💰%.2f", o.GetStatusEmoji(), o.CreatedAt.Format("1/2 15:04"), orderId, o.Money),
|
||||
CallbackData: fmt.Sprintf("%s|%v|%d", cbOrderDetail, o.TradeId, page),
|
||||
}})
|
||||
}
|
||||
|
||||
return buttons, int(total)
|
||||
}
|
||||
|
||||
func buildPageNavigation(page, total, size int) [][]models.InlineKeyboardButton {
|
||||
totalPage := int(math.Ceil(float64(total) / float64(size)))
|
||||
|
||||
prevBtn := models.InlineKeyboardButton{Text: "🏠首页", CallbackData: "-"}
|
||||
if page > 1 {
|
||||
prevBtn = models.InlineKeyboardButton{Text: "⬅️上一页", CallbackData: fmt.Sprintf("%s|%d", cbOrderList, page-1)}
|
||||
}
|
||||
|
||||
nextBtn := models.InlineKeyboardButton{Text: "🔙末页", CallbackData: "-"}
|
||||
if page < totalPage {
|
||||
nextBtn = models.InlineKeyboardButton{Text: "➡️下一页", CallbackData: fmt.Sprintf("%s|%d", cbOrderList, page+1)}
|
||||
}
|
||||
|
||||
return [][]models.InlineKeyboardButton{{
|
||||
prevBtn,
|
||||
{Text: fmt.Sprintf("📄第[%d/%d]页", page, totalPage), CallbackData: "-"},
|
||||
nextBtn,
|
||||
}}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/go-cache"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func defaultHandle(ctx context.Context, bot *bot.Bot, u *models.Update) {
|
||||
if u.Message != nil && u.Message.ReplyToMessage != nil && u.Message.ReplyToMessage.Text == replayAddressText {
|
||||
addWalletAddress(u)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 私聊消息
|
||||
if u.Message != nil && u.Message.Chat.Type == models.ChatTypePrivate {
|
||||
var text = u.Message.Text
|
||||
if help.IsValidTronAddress(text) {
|
||||
go queryTronAddressInfo(u.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addWalletAddress(u *models.Update) {
|
||||
var address = strings.TrimSpace(u.Message.Text)
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidEvmAddress(address) && !help.IsValidSolanaAddress(address) && !help.IsValidAptosAddress(address) {
|
||||
SendMessage(&bot.SendMessageParams{Text: "钱包地址不合法"})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if help.IsValidEvmAddress(address) {
|
||||
|
||||
address = strings.ToLower(address)
|
||||
}
|
||||
|
||||
var tradeType, _ = cache.Get(fmt.Sprintf("%s_%d_trade_type", cbAddressAdd, u.Message.Chat.ID))
|
||||
|
||||
var wa = model.WalletAddress{TradeType: tradeType.(string), Address: address, Status: model.StatusEnable, OtherNotify: model.OtherNotifyDisable}
|
||||
var r = model.DB.Create(&wa)
|
||||
if r.Error != nil {
|
||||
SendMessage(&bot.SendMessageParams{Text: "❌地址添加失败," + r.Error.Error()})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
SendMessage(&bot.SendMessageParams{Text: "✅添加且成功启用"})
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle(context.Background(), api, u)
|
||||
}
|
||||
|
||||
func queryTronAddressInfo(m *models.Message) {
|
||||
var address = strings.TrimSpace(m.Text)
|
||||
var params = bot.SendMessageParams{
|
||||
ChatID: m.Chat.ID,
|
||||
Text: getTronWalletInfo(address),
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyParameters: &models.ReplyParameters{
|
||||
MessageID: m.ID,
|
||||
ChatID: m.Chat.ID,
|
||||
},
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看详细信息", URL: "https://tronscan.org/#/address/" + address},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
SendMessage(¶ms)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func SendTradeSuccMsg(order model.TradeOrders) {
|
||||
var tradeType = "USDT"
|
||||
if order.TradeType == model.OrderTradeTypeTronTrx {
|
||||
tradeType = "TRX"
|
||||
}
|
||||
|
||||
var text = `
|
||||
\#收款成功 \#订单交易 \#` + tradeType + `
|
||||
\-\-\-
|
||||
` + "```" + `
|
||||
🚦商户订单:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💲支付数额:%v ` + order.TradeType + `
|
||||
💎交易哈希:%s
|
||||
✅收款地址:%s
|
||||
⏱️创建时间:%s
|
||||
️🎯️支付时间:%s
|
||||
` + "```" + `
|
||||
`
|
||||
text = fmt.Sprintf(text,
|
||||
order.OrderId,
|
||||
order.Money,
|
||||
order.TradeRate,
|
||||
order.Amount,
|
||||
help.MaskHash(order.TradeHash),
|
||||
help.MaskAddress(order.Address),
|
||||
order.CreatedAt.Format(time.DateTime),
|
||||
order.UpdatedAt.Format(time.DateTime),
|
||||
)
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ChatID: conf.BotNotifyTarget(),
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看交易明细", URL: order.GetDetailUrl()},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func SendNotifyFailed(o model.TradeOrders, reason string) {
|
||||
var tradeType = "USDT"
|
||||
if o.TradeType == model.OrderTradeTypeTronTrx {
|
||||
tradeType = "TRX"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(`
|
||||
\#回调失败 \#订单交易 \#`+tradeType+`
|
||||
\-\-\-
|
||||
`+"```"+`
|
||||
🚦商户订单:%v
|
||||
💲支付数额:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💍交易类别:%s
|
||||
⚖️️确认时间:%s
|
||||
⏰下次回调:%s
|
||||
🗒️失败原因:%s
|
||||
`+"```"+`
|
||||
`,
|
||||
help.Ec(o.OrderId),
|
||||
o.Amount,
|
||||
o.Money, o.TradeRate,
|
||||
strings.ToUpper(o.TradeType),
|
||||
o.ConfirmedAt.Format(time.DateTime),
|
||||
help.CalcNextNotifyTime(o.ConfirmedAt, o.NotifyNum+1).Format(time.DateTime),
|
||||
reason,
|
||||
)
|
||||
|
||||
SendMessage(&bot.SendMessageParams{
|
||||
Text: text,
|
||||
ChatID: conf.BotNotifyTarget(),
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: &models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看收款详情", CallbackData: fmt.Sprintf("%s|%v", cbOrderDetail, o.TradeId)},
|
||||
models.InlineKeyboardButton{Text: "✅标记回调成功", CallbackData: fmt.Sprintf("%s|%v", cbMarkNotifySucc, o.TradeId)},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func Welcome() string {
|
||||
return `
|
||||
👋 欢迎使用 Bepusdt,一款更好用的个人USDT收款网关,如果您看到此消息,说明机器人已经启动成功!
|
||||
|
||||
📌当前版本:` + app.Version + `
|
||||
📝发送命令 /start 可以开始使用
|
||||
🎉开源地址 https://github.com/v03413/bepusdt
|
||||
---
|
||||
`
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func updateFilter(next bot.HandlerFunc) bot.HandlerFunc {
|
||||
return func(ctx context.Context, bot *bot.Bot, update *models.Update) {
|
||||
var allow bool
|
||||
var admin = conf.BotAdminID()
|
||||
|
||||
// 只处理管理员私聊消息
|
||||
if update.Message != nil && update.Message.Chat.Type == models.ChatTypePrivate && update.Message.Chat.ID == admin {
|
||||
|
||||
allow = true
|
||||
}
|
||||
|
||||
// 只处理管理员回调消息
|
||||
if update.CallbackQuery != nil && update.CallbackQuery.From.ID == admin {
|
||||
ctx = context.WithValue(ctx, "args", strings.Split(update.CallbackQuery.Data, "|"))
|
||||
|
||||
allow = true
|
||||
}
|
||||
|
||||
if !allow {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
next(ctx, bot, update)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package conf
|
||||
|
||||
type Conf struct {
|
||||
AppUri string `toml:"app_uri"`
|
||||
AuthToken string `toml:"auth_token"`
|
||||
Listen string `toml:"listen"`
|
||||
OutputLog string `toml:"output_log"`
|
||||
StaticPath string `toml:"static_path"`
|
||||
SqlitePath string `toml:"sqlite_path"`
|
||||
TronGrpcNode string `toml:"tron_grpc_node"`
|
||||
AptosRpcNode string `toml:"aptos_rpc_node"`
|
||||
WebhookUrl string `toml:"webhook_url"`
|
||||
Pay struct {
|
||||
TrxAtom float64 `toml:"trx_atom"`
|
||||
TrxRate string `toml:"trx_rate"`
|
||||
UsdtAtom float64 `toml:"usdt_atom"`
|
||||
UsdtRate string `toml:"usdt_rate"`
|
||||
ExpireTime int `toml:"expire_time"`
|
||||
WalletAddress []string `toml:"wallet_address"`
|
||||
TradeIsConfirmed bool `toml:"trade_is_confirmed"`
|
||||
PaymentAmountMin float64 `toml:"payment_amount_min"`
|
||||
PaymentAmountMax float64 `toml:"payment_amount_max"`
|
||||
} `toml:"pay"`
|
||||
EvmRpc struct {
|
||||
Bsc string `toml:"bsc"`
|
||||
Solana string `toml:"solana"`
|
||||
Xlayer string `toml:"xlayer"`
|
||||
Polygon string `toml:"polygon"`
|
||||
Ethereum string `toml:"ethereum"`
|
||||
} `toml:"evm_rpc"`
|
||||
Bot struct {
|
||||
Token string `toml:"token"`
|
||||
AdminID int64 `toml:"admin_id"`
|
||||
GroupID string `toml:"group_id"`
|
||||
} `toml:"bot"`
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
defaultExpireTime = 600 // 订单默认有效期 10分钟
|
||||
DefaultUsdtCnyRate = 6.4 // 默认USDT基准汇率
|
||||
DefaultTrxCnyRate = 0.95 // 默认TRX基准汇率
|
||||
defaultAuthToken = "123234" // 默认授权码
|
||||
defaultListen = ":8080" // 默认监听地址
|
||||
defaultPaymentMinAmount = 0.01
|
||||
defaultPaymentMaxAmount = 99999
|
||||
defaultUsdtAtomicity = 0.01 // 原子精度
|
||||
defaultTrxAtomicity = 0.01
|
||||
|
||||
defaultTronGrpcNode = "18.141.79.38:50051" // 默认GRPC节点
|
||||
defaultBscRpcEndpoint = "https://bsc-dataseed.bnbchain.org/" // 默认BSC RPC节点
|
||||
defaultSolanaRpcEndpoint = "https://solana-rpc.publicnode.com/" // 默认Solana RPC节点 官方是 https://api.mainnet-beta.solana.com/ 但存在速率限制
|
||||
defaultXlayerRpcEndpoint = "https://xlayerrpc.okx.com/" // 默认Xlayer RPC节点
|
||||
defaultPolygonRpcEndpoint = "https://polygon-rpc.com/" // 默认Polygon RPC节点
|
||||
defaultEthereumRpcEndpoint = "https://ethereum.publicnode.com/" // 默认Ethereum RPC节点
|
||||
defaultAptosRpcEndpoint = "https://aptos-rest.publicnode.com/" // 默认Aptos RPC节点
|
||||
defaultOutputLog = "/var/log/bepusdt.log" // 默认日志输出文件
|
||||
defaultSqlitePath = "/var/lib/bepusdt/sqlite.db" // 默认数据库文件
|
||||
)
|
||||
|
||||
const (
|
||||
UsdtErc20 = "0xdac17f958d2ee523a2206206994597c13d831ec7" // Eth USDT合约地址
|
||||
UsdtBep20 = "0x55d398326f99059ff775485246999027b3197955" // BSC USDT合约地址
|
||||
UsdtXlayer = "0x1e4a5963abfd975d8c9021ce480b42188849d41d" // Xlayer USDT合约地址
|
||||
UsdtPolygon = "0xc2132d05d31c914a87c6611c10748aeb04b58e8f" // Polygon USDT合约地址
|
||||
UsdtSolana = "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" // Solana USDT合约地址
|
||||
SolSplToken = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" // Solana SPL Token合约地址
|
||||
UsdtAptos = "0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2b" // Aptos USDT合约地址
|
||||
)
|
||||
|
||||
// UsdtDecimals USDT合约小数位数
|
||||
const (
|
||||
UsdtBscDecimals = -18 // USDT BEP20小数位数
|
||||
UsdtEthDecimals = -6 // USDT ERC20小数位数
|
||||
UsdtXlayerDecimals = -6 // USDT Xlayer小数位数
|
||||
UsdtPolygonDecimals = -6 // USDT Polygon小数位数
|
||||
UsdtAptosDecimals = -6 // USDT Aptos小数位数
|
||||
)
|
||||
|
||||
const (
|
||||
NotifyMaxRetry = 10 // 最大重试次数,订单回调失败、Webhook失败
|
||||
BlockHeightMaxDiff = 1000 // 区块高度最大差值,超过此值则以当前区块高度为准,重新开始扫描
|
||||
)
|
||||
@@ -0,0 +1,203 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
Bsc = "bsc" // Binance Smart Chain
|
||||
Tron = "tron"
|
||||
Aptos = "aptos"
|
||||
Solana = "solana"
|
||||
Xlayer = "xlayer"
|
||||
Polygon = "polygon"
|
||||
Ethereum = "ethereum"
|
||||
)
|
||||
|
||||
var (
|
||||
cfg Conf
|
||||
path string
|
||||
)
|
||||
|
||||
func Init() error {
|
||||
flag.StringVar(&path, "conf", "./conf.toml", "config file path")
|
||||
flag.Parse()
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("配置文件加载失败:%w", err)
|
||||
}
|
||||
|
||||
if err = toml.Unmarshal(data, &cfg); err != nil {
|
||||
|
||||
return fmt.Errorf("配置数据解析失败:%w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetUsdtRate() string {
|
||||
|
||||
return cfg.Pay.UsdtRate
|
||||
}
|
||||
|
||||
func GetTrxRate() string {
|
||||
|
||||
return cfg.Pay.TrxRate
|
||||
}
|
||||
|
||||
func GetUsdtAtomicity() (decimal.Decimal, int) {
|
||||
var val = defaultUsdtAtomicity
|
||||
if cfg.Pay.UsdtAtom != 0 {
|
||||
|
||||
val = cfg.Pay.UsdtAtom
|
||||
}
|
||||
|
||||
var atom = decimal.NewFromFloat(val)
|
||||
|
||||
return atom, cast.ToInt(math.Abs(float64(atom.Exponent())))
|
||||
}
|
||||
|
||||
func GetTrxAtomicity() (decimal.Decimal, int) {
|
||||
var val = defaultTrxAtomicity
|
||||
if cfg.Pay.TrxAtom != 0 {
|
||||
|
||||
val = cfg.Pay.TrxAtom
|
||||
}
|
||||
|
||||
var atom = decimal.NewFromFloat(val)
|
||||
|
||||
return atom, cast.ToInt(math.Abs(float64(atom.Exponent())))
|
||||
}
|
||||
|
||||
func GetExpireTime() time.Duration {
|
||||
if cfg.Pay.ExpireTime == 0 {
|
||||
|
||||
return time.Duration(defaultExpireTime)
|
||||
}
|
||||
|
||||
return time.Duration(cfg.Pay.ExpireTime)
|
||||
}
|
||||
|
||||
func GetAuthToken() string {
|
||||
if cfg.AuthToken == "" {
|
||||
|
||||
return defaultAuthToken
|
||||
}
|
||||
|
||||
return cfg.AuthToken
|
||||
}
|
||||
|
||||
func GetAppUri(host string) string {
|
||||
if cfg.AppUri != "" {
|
||||
|
||||
return cfg.AppUri
|
||||
}
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
func GetStaticPath() string {
|
||||
|
||||
return cfg.StaticPath
|
||||
}
|
||||
|
||||
func GetSqlitePath() string {
|
||||
if cfg.SqlitePath != "" {
|
||||
|
||||
return cfg.SqlitePath
|
||||
}
|
||||
|
||||
return defaultSqlitePath
|
||||
}
|
||||
|
||||
func GetOutputLog() string {
|
||||
if cfg.OutputLog != "" {
|
||||
|
||||
return cfg.OutputLog
|
||||
}
|
||||
|
||||
return defaultOutputLog
|
||||
}
|
||||
|
||||
func GetListen() string {
|
||||
if cfg.Listen != "" {
|
||||
|
||||
return cfg.Listen
|
||||
}
|
||||
|
||||
return defaultListen
|
||||
}
|
||||
|
||||
func BotToken() string {
|
||||
var token = strings.TrimSpace(os.Getenv("BOT_TOKEN"))
|
||||
if token != "" {
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
return cfg.Bot.Token
|
||||
}
|
||||
|
||||
func BotAdminID() int64 {
|
||||
var id = strings.TrimSpace(os.Getenv("BOT_ADMIN_ID"))
|
||||
if id != "" {
|
||||
|
||||
return cast.ToInt64(id)
|
||||
}
|
||||
|
||||
return cfg.Bot.AdminID
|
||||
}
|
||||
|
||||
func BotNotifyTarget() string {
|
||||
if cfg.Bot.GroupID != "" {
|
||||
|
||||
return cfg.Bot.GroupID
|
||||
}
|
||||
|
||||
return cast.ToString(cfg.Bot.AdminID)
|
||||
}
|
||||
|
||||
func GetWalletAddress() []string {
|
||||
|
||||
return cfg.Pay.WalletAddress
|
||||
}
|
||||
|
||||
func GetTradeIsConfirmed() bool {
|
||||
|
||||
return cfg.Pay.TradeIsConfirmed
|
||||
}
|
||||
|
||||
func GetPaymentAmountMin() decimal.Decimal {
|
||||
var val = defaultPaymentMinAmount
|
||||
if cfg.Pay.PaymentAmountMin != 0 {
|
||||
|
||||
val = cfg.Pay.PaymentAmountMin
|
||||
}
|
||||
|
||||
return decimal.NewFromFloat(val)
|
||||
}
|
||||
|
||||
func GetPaymentAmountMax() decimal.Decimal {
|
||||
var val float64 = defaultPaymentMaxAmount
|
||||
if cfg.Pay.PaymentAmountMax != 0 {
|
||||
|
||||
val = cfg.Pay.PaymentAmountMax
|
||||
}
|
||||
|
||||
return decimal.NewFromFloat(val)
|
||||
}
|
||||
|
||||
func GetWebhookUrl() string {
|
||||
|
||||
return cfg.WebhookUrl
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package conf
|
||||
|
||||
func GetTronGrpcNode() string {
|
||||
if cfg.TronGrpcNode != "" {
|
||||
|
||||
return cfg.TronGrpcNode
|
||||
}
|
||||
|
||||
return defaultTronGrpcNode
|
||||
}
|
||||
|
||||
func GetAptosRpcNode() string {
|
||||
if cfg.AptosRpcNode != "" {
|
||||
return cfg.AptosRpcNode
|
||||
}
|
||||
|
||||
return defaultAptosRpcEndpoint
|
||||
}
|
||||
|
||||
func GetSolanaRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Solana != "" {
|
||||
|
||||
return cfg.EvmRpc.Solana
|
||||
}
|
||||
|
||||
return defaultSolanaRpcEndpoint
|
||||
}
|
||||
|
||||
func GetXlayerRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Xlayer != "" {
|
||||
|
||||
return cfg.EvmRpc.Xlayer
|
||||
}
|
||||
|
||||
return defaultXlayerRpcEndpoint
|
||||
}
|
||||
|
||||
func GetBscRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Bsc != "" {
|
||||
|
||||
return cfg.EvmRpc.Bsc
|
||||
}
|
||||
|
||||
return defaultBscRpcEndpoint
|
||||
}
|
||||
|
||||
func GetPolygonRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Polygon != "" {
|
||||
|
||||
return cfg.EvmRpc.Polygon
|
||||
}
|
||||
|
||||
return defaultPolygonRpcEndpoint
|
||||
}
|
||||
|
||||
func GetEthereumRpcEndpoint() string {
|
||||
if cfg.EvmRpc.Ethereum != "" {
|
||||
|
||||
return cfg.EvmRpc.Ethereum
|
||||
}
|
||||
|
||||
return defaultEthereumRpcEndpoint
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type stat struct {
|
||||
total atomic.Int64
|
||||
fail atomic.Int64
|
||||
}
|
||||
|
||||
var (
|
||||
data sync.Map // map[string]*stat
|
||||
)
|
||||
|
||||
func getStat(net string) *stat {
|
||||
val, _ := data.LoadOrStore(net, &stat{})
|
||||
|
||||
return val.(*stat)
|
||||
}
|
||||
|
||||
func SetBlockTotal(net string) {
|
||||
getStat(net).total.Add(1)
|
||||
}
|
||||
|
||||
func SetBlockFail(net string) {
|
||||
getStat(net).fail.Add(1)
|
||||
}
|
||||
|
||||
func GetBlockSuccRate(net string) string {
|
||||
s := getStat(net)
|
||||
t := s.total.Load()
|
||||
if t == 0 {
|
||||
|
||||
return "100.00%"
|
||||
}
|
||||
|
||||
f := s.fail.Load()
|
||||
|
||||
return fmt.Sprintf("%.2f%%", float64(t-f)/float64(t)*100)
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const defaultExpireTime = 600 // 订单默认有效期 10分钟
|
||||
const DefaultUsdtCnyRate = 6.4 // 默认USDT汇率
|
||||
const DefaultTrxCnyRate = 0.95 // 默认TRX汇率
|
||||
const defaultAuthToken = "123234" // 默认授权码
|
||||
const defaultListen = ":8080" // 默认监听地址
|
||||
const defaultPaymentMinAmount = 0.01
|
||||
const defaultPaymentMaxAmount = 99999
|
||||
const defaultUsdtAtomicity = "0.01" // 原子精度
|
||||
const defaultTrxAtomicity = "0.01"
|
||||
const defaultTronGrpcNode = "18.141.79.38:50051" // 默认GRPC节点
|
||||
const defaultPolygonRpcEndpoint = "https://polygon-rpc.com/" // 默认Polygon RPC节点
|
||||
|
||||
var runPath string
|
||||
|
||||
var (
|
||||
BlockScanSucc uint64
|
||||
BlockScanTotal uint64
|
||||
)
|
||||
|
||||
func init() {
|
||||
execPath, err := os.Executable()
|
||||
if err != nil {
|
||||
|
||||
panic(err)
|
||||
}
|
||||
|
||||
runPath = filepath.Dir(execPath)
|
||||
}
|
||||
|
||||
func GetPolygonRpcEndpoint() string {
|
||||
if data := help.GetEnv("POLYGON_RPC_ENDPOINT"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return defaultPolygonRpcEndpoint
|
||||
}
|
||||
|
||||
func GetBlockScanSuccRate() string {
|
||||
if BlockScanTotal == 0 {
|
||||
|
||||
return "100.00%"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%.2f%%", cast.ToFloat64(BlockScanSucc/BlockScanTotal)*100)
|
||||
}
|
||||
|
||||
func GetTronGrpcNode() string {
|
||||
if data := help.GetEnv("TRON_GRPC_NODE"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return defaultTronGrpcNode
|
||||
}
|
||||
|
||||
func GetUsdtAtomicity() (decimal.Decimal, int) {
|
||||
var defaultAtom, _ = decimal.NewFromString(defaultUsdtAtomicity)
|
||||
var defaultExp = cast.ToInt(math.Abs(float64(defaultAtom.Exponent())))
|
||||
if data := help.GetEnv("USDT_ATOM"); data != "" {
|
||||
var atom, exp, err = parseAtomicity(data)
|
||||
if err == nil {
|
||||
|
||||
return atom, exp
|
||||
}
|
||||
}
|
||||
|
||||
return defaultAtom, defaultExp
|
||||
}
|
||||
|
||||
func GetTrxAtomicity() (decimal.Decimal, int) {
|
||||
var defaultAtom, _ = decimal.NewFromString(defaultTrxAtomicity)
|
||||
var defaultExp = cast.ToInt(math.Abs(float64(defaultAtom.Exponent())))
|
||||
if data := help.GetEnv("TRX_ATOM"); data != "" {
|
||||
var atom, exp, err = parseAtomicity(data)
|
||||
if err == nil {
|
||||
|
||||
return atom, exp
|
||||
}
|
||||
}
|
||||
|
||||
return defaultAtom, defaultExp
|
||||
}
|
||||
|
||||
func GetPaymentMinAmount() decimal.Decimal {
|
||||
var _default = decimal.NewFromFloat(defaultPaymentMinAmount)
|
||||
var _min, _ = getPaymentRangeAmount()
|
||||
if _min == "" {
|
||||
|
||||
return _default
|
||||
}
|
||||
|
||||
_result, err := decimal.NewFromString(_min)
|
||||
if err == nil {
|
||||
|
||||
return _result
|
||||
}
|
||||
|
||||
return _default
|
||||
}
|
||||
|
||||
func GetPaymentMaxAmount() decimal.Decimal {
|
||||
var _default = decimal.NewFromFloat(defaultPaymentMaxAmount)
|
||||
var _, _max = getPaymentRangeAmount()
|
||||
if _max == "" {
|
||||
|
||||
return _default
|
||||
}
|
||||
|
||||
_result, err := decimal.NewFromString(_max)
|
||||
if err == nil {
|
||||
|
||||
return _result
|
||||
}
|
||||
|
||||
return _default
|
||||
}
|
||||
|
||||
func getPaymentRangeAmount() (string, string) {
|
||||
var _rangeVar string
|
||||
if _rangeVar = strings.TrimSpace(help.GetEnv("PAYMENT_AMOUNT_RANGE")); _rangeVar == "" {
|
||||
|
||||
return "", ""
|
||||
}
|
||||
|
||||
var _payRange = strings.Split(_rangeVar, ",")
|
||||
if len(_payRange) < 2 {
|
||||
|
||||
return "", ""
|
||||
}
|
||||
|
||||
return _payRange[0], _payRange[1]
|
||||
}
|
||||
|
||||
func GetExpireTime() time.Duration {
|
||||
if ret := help.GetEnv("EXPIRE_TIME"); ret != "" {
|
||||
sec, err := strconv.Atoi(ret)
|
||||
if err == nil && sec > 0 {
|
||||
|
||||
return time.Duration(sec)
|
||||
}
|
||||
}
|
||||
|
||||
return defaultExpireTime
|
||||
}
|
||||
|
||||
func GetUsdtRate() string {
|
||||
if data := help.GetEnv("USDT_RATE"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTrxRate() string {
|
||||
if data := help.GetEnv("TRX_RATE"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetAuthToken() string {
|
||||
if data := help.GetEnv("AUTH_TOKEN"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return defaultAuthToken
|
||||
}
|
||||
|
||||
func GetListen() string {
|
||||
if data := help.GetEnv("LISTEN"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return defaultListen
|
||||
}
|
||||
|
||||
func GetTradeConfirmed() bool {
|
||||
if data := help.GetEnv("TRADE_IS_CONFIRMED"); data != "" {
|
||||
if data == "1" || data == "true" {
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func GetAppUri(host string) string {
|
||||
if data := help.GetEnv("APP_URI"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return host
|
||||
}
|
||||
|
||||
func GetTGBotToken() string {
|
||||
if data := help.GetEnv("TG_BOT_TOKEN"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTGBotAdminId() string {
|
||||
if data := help.GetEnv("TG_BOT_ADMIN_ID"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTgBotGroupId() string {
|
||||
if data := help.GetEnv("TG_BOT_GROUP_ID"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetTgBotNotifyTarget() string {
|
||||
var groupId = GetTgBotGroupId()
|
||||
if groupId != "" {
|
||||
|
||||
return groupId
|
||||
}
|
||||
|
||||
return GetTGBotAdminId()
|
||||
}
|
||||
|
||||
func GetOutputLog() string {
|
||||
|
||||
return runPath + "/bepusdt.log"
|
||||
}
|
||||
|
||||
func GetDbPath() string {
|
||||
|
||||
return runPath + "/bepusdt.db"
|
||||
}
|
||||
|
||||
func GetStaticPath() string {
|
||||
if data := help.GetEnv("STATIC_PATH"); data != "" {
|
||||
|
||||
return strings.TrimSpace(data)
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetInitWalletAddress() []string {
|
||||
if data := help.GetEnv("WALLET_ADDRESS"); data != "" {
|
||||
|
||||
return strings.Split(strings.TrimSpace(data), ",")
|
||||
}
|
||||
|
||||
return []string{}
|
||||
}
|
||||
|
||||
func parseAtomicity(data string) (decimal.Decimal, int, error) {
|
||||
var atom, err = decimal.NewFromString(data)
|
||||
if err != nil {
|
||||
|
||||
return decimal.Zero, 0, err
|
||||
}
|
||||
|
||||
// 如果大于0,且小数点后位数大于0
|
||||
if atom.GreaterThan(decimal.Zero) && atom.Exponent() < 0 {
|
||||
|
||||
return atom, cast.ToInt(math.Abs(float64(atom.Exponent()))), nil
|
||||
}
|
||||
|
||||
return decimal.Zero, 0, errors.New("原子精度参数不合法")
|
||||
}
|
||||
@@ -4,12 +4,13 @@ import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
"math"
|
||||
"math/big"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -99,7 +100,7 @@ func IsValidTronAddress(address string) bool {
|
||||
return match && err == nil
|
||||
}
|
||||
|
||||
func IsValidPolygonAddress(address string) bool {
|
||||
func IsValidEvmAddress(address string) bool {
|
||||
if len(address) != 42 || !strings.HasPrefix(address, "0x") {
|
||||
|
||||
return false
|
||||
@@ -114,6 +115,28 @@ func IsValidPolygonAddress(address string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func IsValidSolanaAddress(address string) bool {
|
||||
data := base58.Decode(address)
|
||||
|
||||
return len(data) == 32
|
||||
}
|
||||
|
||||
func IsValidAptosAddress(address string) bool {
|
||||
if strings.HasPrefix(address, "0x") || strings.HasPrefix(address, "0X") {
|
||||
|
||||
address = address[2:]
|
||||
}
|
||||
|
||||
if len(address) != 64 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
matched, _ := regexp.MatchString("^[0-9a-fA-F]{64}$", address)
|
||||
|
||||
return matched
|
||||
}
|
||||
|
||||
func MaskAddress(address string) string {
|
||||
if len(address) <= 20 {
|
||||
|
||||
@@ -123,13 +146,45 @@ func MaskAddress(address string) string {
|
||||
return address[:8] + " ***** " + address[len(address)-10:]
|
||||
}
|
||||
|
||||
func MaskAddress2(address string) string {
|
||||
if len(address) <= 20 {
|
||||
|
||||
return address
|
||||
}
|
||||
|
||||
return "*** " + address[len(address)-8:]
|
||||
}
|
||||
|
||||
func MaskHash(hash string) string {
|
||||
if len(hash) <= 20 {
|
||||
|
||||
return hash
|
||||
}
|
||||
|
||||
return hash[:6] + " ***** " + hash[len(hash)-8:]
|
||||
}
|
||||
|
||||
func CalcNextNotifyTime(base time.Time, num int) time.Time {
|
||||
|
||||
return base.Add(time.Minute * time.Duration(math.Pow(2, float64(num))))
|
||||
}
|
||||
|
||||
func HexStr2Int(hex string) int64 {
|
||||
v, _ := strconv.ParseInt(strings.TrimPrefix(hex, "0x"), 16, 64)
|
||||
func HexStr2Int(str string) *big.Int {
|
||||
var n = new(big.Int)
|
||||
var val = strings.TrimLeft(strings.TrimPrefix(str, "0x"), "0")
|
||||
|
||||
return v
|
||||
n.SetString(val, 16)
|
||||
|
||||
return n
|
||||
}
|
||||
|
||||
func InStrings(str string, list []string) bool {
|
||||
for _, item := range list {
|
||||
if item == str {
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -2,15 +2,14 @@ package log
|
||||
|
||||
import (
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
var logger *logrus.Logger
|
||||
|
||||
func init() {
|
||||
var level, logFile = logrus.InfoLevel, config.GetOutputLog()
|
||||
func Init() error {
|
||||
logger = logrus.New()
|
||||
logger.SetFormatter(&logrus.TextFormatter{
|
||||
ForceColors: true,
|
||||
@@ -19,15 +18,17 @@ func init() {
|
||||
FullTimestamp: true,
|
||||
})
|
||||
|
||||
logger.SetLevel(level)
|
||||
logger.SetLevel(logrus.InfoLevel)
|
||||
|
||||
output, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
output, err := os.OpenFile(conf.GetOutputLog(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
|
||||
panic(err)
|
||||
return err
|
||||
}
|
||||
|
||||
logger.SetOutput(output)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Debug(args ...interface{}) {
|
||||
|
||||
@@ -2,8 +2,9 @@ package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -12,55 +13,68 @@ const (
|
||||
StatusDisable uint8 = 0
|
||||
OtherNotifyEnable uint8 = 1
|
||||
OtherNotifyDisable uint8 = 0
|
||||
WaChainTron = "tron"
|
||||
WaChainPolygon = "polygon"
|
||||
)
|
||||
|
||||
var tradeChain = map[string]string{
|
||||
OrderTradeTypeTronTrx: WaChainTron,
|
||||
OrderTradeTypeUsdtTrc20: WaChainTron,
|
||||
OrderTradeTypeUsdtPolygon: WaChainPolygon,
|
||||
// SupportTradeTypes 目前支持的收款交易类型
|
||||
var SupportTradeTypes = []string{
|
||||
OrderTradeTypeTronTrx,
|
||||
OrderTradeTypeUsdtTrc20,
|
||||
OrderTradeTypeUsdtErc20,
|
||||
OrderTradeTypeUsdtBep20,
|
||||
OrderTradeTypeUsdtAptos,
|
||||
OrderTradeTypeUsdtXlayer,
|
||||
OrderTradeTypeUsdtSolana,
|
||||
OrderTradeTypeUsdtPolygon,
|
||||
}
|
||||
|
||||
type WalletAddress struct {
|
||||
ID int64 `gorm:"integer;primaryKey;not null;comment:id"`
|
||||
Status uint8 `gorm:"column:status;type:tinyint(1);not null;default:1;comment:地址状态 1启动 0禁止"`
|
||||
Chain string `gorm:"column:chain;type:varchar(16);not null;default:'tron';comment:链类型"`
|
||||
Address string `gorm:"column:address;type:varchar(64);not null;uniqueIndex;comment:钱包地址"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;type:tinyint(1);not null;default:0;comment:其它转账通知 1启动 0禁止"`
|
||||
Status uint8 `gorm:"column:status;type:tinyint(1);not null;default:1;comment:地址状态"`
|
||||
TradeType string `gorm:"column:trade_type;type:varchar(20);not null;comment:交易类型"`
|
||||
Address string `gorm:"column:address;type:varchar(64);not null;index;comment:钱包地址"`
|
||||
OtherNotify uint8 `gorm:"column:other_notify;type:tinyint(1);not null;default:0;comment:其它通知"`
|
||||
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime;type:timestamp;not null;comment:创建时间"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime;type:timestamp;not null;comment:更新时间"`
|
||||
}
|
||||
|
||||
// 启动时添加初始钱包地址
|
||||
func addStartWalletAddress() {
|
||||
for _, address := range config.GetInitWalletAddress() {
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidPolygonAddress(address) {
|
||||
for _, itm := range conf.GetWalletAddress() {
|
||||
var info = strings.Split(itm, ":")
|
||||
if len(info) != 2 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var address = info[1]
|
||||
var tradeType = info[0]
|
||||
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidEvmAddress(address) {
|
||||
fmt.Println("❌钱包地址不合法:", address)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var chain = WaChainTron
|
||||
if help.IsValidPolygonAddress(address) {
|
||||
chain = WaChainPolygon
|
||||
if help.IsValidEvmAddress(address) {
|
||||
|
||||
address = strings.ToLower(address)
|
||||
}
|
||||
|
||||
var wa WalletAddress
|
||||
DB.Where("address = ?", address).Limit(1).Find(&wa)
|
||||
DB.Where("address = ? and trade_type = ?", address, tradeType).Limit(1).Find(&wa)
|
||||
if wa.ID != 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var err = DB.Create(&WalletAddress{Chain: chain, Address: address, Status: StatusEnable}).Error
|
||||
var err = DB.Create(&WalletAddress{TradeType: tradeType, Address: address, Status: StatusEnable}).Error
|
||||
if err != nil {
|
||||
fmt.Println("❌钱包地址添加失败:", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Println("✅钱包地址添加成功:", chain, address)
|
||||
fmt.Println("✅钱包地址添加成功:", tradeType, address)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,18 +98,63 @@ func (wa *WalletAddress) Delete() {
|
||||
DB.Delete(wa)
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) GetUsdtContract() string {
|
||||
switch wa.TradeType {
|
||||
case OrderTradeTypeUsdtPolygon:
|
||||
return conf.UsdtPolygon
|
||||
case OrderTradeTypeUsdtErc20:
|
||||
return conf.UsdtErc20
|
||||
case OrderTradeTypeUsdtBep20:
|
||||
return conf.UsdtBep20
|
||||
case OrderTradeTypeUsdtXlayer:
|
||||
return conf.UsdtXlayer
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) GetUsdtDecimals() int32 {
|
||||
switch wa.TradeType {
|
||||
case OrderTradeTypeUsdtPolygon:
|
||||
return conf.UsdtPolygonDecimals
|
||||
case OrderTradeTypeUsdtErc20:
|
||||
return conf.UsdtEthDecimals
|
||||
case OrderTradeTypeUsdtBep20:
|
||||
return conf.UsdtBscDecimals
|
||||
case OrderTradeTypeUsdtXlayer:
|
||||
return conf.UsdtXlayerDecimals
|
||||
default:
|
||||
return -6
|
||||
}
|
||||
}
|
||||
|
||||
func (wa *WalletAddress) GetEvmRpcEndpoint() string {
|
||||
switch wa.TradeType {
|
||||
case OrderTradeTypeUsdtPolygon:
|
||||
return conf.GetPolygonRpcEndpoint()
|
||||
case OrderTradeTypeUsdtErc20:
|
||||
return conf.GetEthereumRpcEndpoint()
|
||||
case OrderTradeTypeUsdtBep20:
|
||||
return conf.GetBscRpcEndpoint()
|
||||
case OrderTradeTypeUsdtXlayer:
|
||||
return conf.GetXlayerRpcEndpoint()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func GetAvailableAddress(address, tradeType string) []WalletAddress {
|
||||
var rows []WalletAddress
|
||||
var chain = tradeChain[tradeType]
|
||||
if address == "" {
|
||||
DB.Where("chain = ? and status = ?", chain, StatusEnable).Find(&rows)
|
||||
var db = DB.Where("trade_type = ?", tradeType)
|
||||
if address != "" {
|
||||
|
||||
return rows
|
||||
db = db.Where("address = ?", address)
|
||||
}
|
||||
|
||||
DB.Where("address = ?", address).Find(&rows)
|
||||
if len(rows) == 0 {
|
||||
var wa = WalletAddress{Chain: chain, Address: address, Status: StatusEnable, OtherNotify: OtherNotifyDisable}
|
||||
db.Find(&rows)
|
||||
|
||||
if len(rows) == 0 && address != "" {
|
||||
var wa = WalletAddress{TradeType: tradeType, Address: address, Status: StatusEnable, OtherNotify: OtherNotifyDisable}
|
||||
|
||||
DB.Create(&wa)
|
||||
|
||||
@@ -104,14 +163,3 @@ func GetAvailableAddress(address, tradeType string) []WalletAddress {
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
func GetOtherNotify(address string) bool {
|
||||
var row WalletAddress
|
||||
var res = DB.Where("status = ? and address = ?", StatusEnable, address).First(&row)
|
||||
if res.Error != nil {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return row.OtherNotify == 1
|
||||
}
|
||||
|
||||
@@ -1,25 +1,33 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"gorm.io/gorm"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
var _err error
|
||||
var err error
|
||||
|
||||
func Init() error {
|
||||
DB, _err = gorm.Open(sqlite.Open(config.GetDbPath()), &gorm.Config{})
|
||||
if _err != nil {
|
||||
|
||||
return _err
|
||||
var path = conf.GetSqlitePath()
|
||||
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
|
||||
|
||||
return fmt.Errorf("创建数据库目录失败:%w", err)
|
||||
}
|
||||
|
||||
if _err = AutoMigrate(); _err != nil {
|
||||
DB, err = gorm.Open(sqlite.Open(path), &gorm.Config{})
|
||||
if err != nil {
|
||||
|
||||
return _err
|
||||
return fmt.Errorf("数据库初始化失败:%w", err)
|
||||
}
|
||||
|
||||
if err = AutoMigrate(); err != nil {
|
||||
|
||||
return fmt.Errorf("数据库结构迁移失败:%w", err)
|
||||
}
|
||||
|
||||
addStartWalletAddress()
|
||||
@@ -29,5 +37,5 @@ func Init() error {
|
||||
|
||||
func AutoMigrate() error {
|
||||
|
||||
return DB.AutoMigrate(&WalletAddress{}, &TradeOrders{}, &NotifyRecord{}, &Config{})
|
||||
return DB.AutoMigrate(&WalletAddress{}, &TradeOrders{}, &NotifyRecord{}, &Config{}, &Webhook{})
|
||||
}
|
||||
|
||||
@@ -1,29 +1,36 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
OrderNotifyStateSucc = 1 // 回调成功
|
||||
OrderNotifyStateFail = 0 // 回调失败
|
||||
|
||||
OrderStatusCanceled = 4 // 订单取消
|
||||
OrderStatusExpired = 3 // 订单过期
|
||||
OrderStatusSuccess = 2 // 订单成功
|
||||
OrderStatusWaiting = 1 // 等待支付
|
||||
)
|
||||
|
||||
const (
|
||||
OrderNotifyStateSucc = 1 // 回调成功
|
||||
OrderNotifyStateFail = 0 // 回调失败
|
||||
)
|
||||
OrderTradeTypeBscBnb = "bsc.bnb"
|
||||
OrderTradeTypeEthEth = "ethereum.eth"
|
||||
OrderTradeTypeXlayerOkb = "xlayer.okb"
|
||||
OrderTradeTypePolygonPol = "polygon.pol"
|
||||
|
||||
const (
|
||||
OrderTradeTypeTronTrx = "tron.trx"
|
||||
OrderTradeTypeUsdtTrc20 = "usdt.trc20"
|
||||
OrderTradeTypeUsdtPolygon = "usdt.polygon"
|
||||
OrderTradeTypeUsdtErc20 = "usdt.erc20"
|
||||
OrderTradeTypeUsdtBep20 = "usdt.bep20"
|
||||
OrderTradeTypeUsdtXlayer = "usdt.xlayer"
|
||||
OrderTradeTypeUsdtSolana = "usdt.solana"
|
||||
OrderTradeTypeUsdtAptos = "usdt.aptos"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -33,26 +40,31 @@ const (
|
||||
|
||||
var calcMutex sync.Mutex
|
||||
|
||||
type TradeType struct {
|
||||
Type string `json:"type"` // 交易类型
|
||||
Native bool `json:"native"` // 是否是原生代币
|
||||
}
|
||||
|
||||
type TradeOrders struct {
|
||||
Id int64 `gorm:"primary_key;AUTO_INCREMENT;comment:id"`
|
||||
OrderId string `gorm:"type:varchar(128);not null;unique;color:blue;comment:商户ID"`
|
||||
TradeId string `gorm:"type:varchar(128);not null;unique;color:blue;comment:本地ID"`
|
||||
TradeType string `gorm:"type:varchar(20);not null;comment:交易类型"`
|
||||
TradeHash string `gorm:"type:varchar(64);default:'';unique;comment:交易哈希"`
|
||||
TradeRate string `gorm:"type:varchar(10);not null;comment:交易汇率"`
|
||||
OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID"`
|
||||
TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID"`
|
||||
TradeType string `gorm:"column:trade_type;type:varchar(20);not null;comment:交易类型"`
|
||||
TradeHash string `gorm:"column:trade_hash;type:varchar(130);default:'';unique;comment:交易哈希"`
|
||||
TradeRate string `gorm:"column:trade_rate;type:varchar(10);not null;comment:交易汇率"`
|
||||
Amount string `gorm:"type:decimal(10,2);not null;default:0;comment:交易数额"`
|
||||
Money float64 `gorm:"type:decimal(10,2);not null;default:0;comment:订单交易金额"`
|
||||
Address string `gorm:"column:address;type:varchar(64);not null;comment:收款地址"`
|
||||
FromAddress string `gorm:"type:varchar(34);not null;default:'';comment:支付地址"`
|
||||
Status int `gorm:"type:tinyint(1);not null;default:0;comment:交易状态 1:等待支付 2:支付成功 3:订单过期"`
|
||||
Status int `gorm:"type:tinyint(1);not null;default:1;index;comment:交易状态"`
|
||||
Name string `gorm:"type:varchar(64);not null;default:'';comment:商品名称"`
|
||||
ApiType string `gorm:"type:varchar(20);not null;default:'epusdt';comment:API类型"`
|
||||
ReturnUrl string `gorm:"type:varchar(255);not null;default:'';comment:同步地址"`
|
||||
NotifyUrl string `gorm:"type:varchar(255);not null;default:'';comment:异步地址"`
|
||||
NotifyNum int `gorm:"type:int(11);not null;default:0;comment:回调次数"`
|
||||
NotifyNum int `gorm:"column:notify_num;type:int(11);not null;default:0;comment:回调次数"`
|
||||
NotifyState int `gorm:"column:notify_state;type:tinyint(1);not null;default:0;comment:回调状态 1:成功 0:失败"`
|
||||
RefBlockNum int64 `gorm:"type:bigint(20);not null;default:0;comment:交易所在区块"`
|
||||
ExpiredAt time.Time `gorm:"type:timestamp;not null;comment:订单失效时间"`
|
||||
ExpiredAt time.Time `gorm:"column:expired_at;type:timestamp;not null;comment:失效时间"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;type:timestamp;not null;comment:创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime;type:timestamp;not null;comment:更新时间"`
|
||||
ConfirmedAt time.Time `gorm:"type:timestamp;null;comment:交易确认时间"`
|
||||
@@ -70,22 +82,17 @@ func (o *TradeOrders) OrderSetExpired() {
|
||||
DB.Save(o)
|
||||
}
|
||||
|
||||
func (o *TradeOrders) OrderUpdateTxInfo(refBlockNum int64, fromAddress, tradeHash string, confirmedAt time.Time) {
|
||||
o.FromAddress = fromAddress
|
||||
o.ConfirmedAt = confirmedAt
|
||||
o.TradeHash = tradeHash
|
||||
o.RefBlockNum = refBlockNum
|
||||
func (o *TradeOrders) MarkSuccess(blockNum int64, from, hash string, at time.Time) {
|
||||
o.FromAddress = from
|
||||
o.ConfirmedAt = at
|
||||
o.TradeHash = hash
|
||||
o.RefBlockNum = blockNum
|
||||
o.Status = OrderStatusSuccess
|
||||
|
||||
DB.Save(o)
|
||||
}
|
||||
|
||||
func (o *TradeOrders) MarkSuccess() {
|
||||
o.Status = OrderStatusSuccess // 标记成功
|
||||
|
||||
DB.Save(o)
|
||||
}
|
||||
|
||||
func (o *TradeOrders) OrderSetNotifyState(state int) error {
|
||||
func (o *TradeOrders) SetNotifyState(state int) error {
|
||||
o.NotifyNum += 1
|
||||
o.NotifyState = state
|
||||
|
||||
@@ -93,44 +100,77 @@ func (o *TradeOrders) OrderSetNotifyState(state int) error {
|
||||
}
|
||||
|
||||
func (o *TradeOrders) GetStatusLabel() string {
|
||||
var label = "🟢 收款成功"
|
||||
var label = "🟢收款成功"
|
||||
if o.Status == OrderStatusExpired {
|
||||
|
||||
label = "🔴 交易过期"
|
||||
label = "🔴交易过期"
|
||||
}
|
||||
if o.Status == OrderStatusWaiting {
|
||||
|
||||
label = "🟡 等待支付"
|
||||
label = "🟡等待支付"
|
||||
}
|
||||
if o.Status == OrderStatusCanceled {
|
||||
|
||||
label = "⚪️ 订单取消"
|
||||
label = "⚪️订单取消"
|
||||
}
|
||||
|
||||
return label
|
||||
}
|
||||
|
||||
func GetTradeType(trade string) string {
|
||||
if trade == OrderTradeTypeTronTrx {
|
||||
func (o *TradeOrders) GetStatusEmoji() string {
|
||||
var label = "🟢"
|
||||
if o.Status == OrderStatusExpired {
|
||||
|
||||
return OrderTradeTypeTronTrx
|
||||
label = "🔴"
|
||||
}
|
||||
if trade == OrderTradeTypeUsdtPolygon {
|
||||
if o.Status == OrderStatusWaiting {
|
||||
|
||||
return OrderTradeTypeUsdtPolygon
|
||||
label = "🟡"
|
||||
}
|
||||
if o.Status == OrderStatusCanceled {
|
||||
|
||||
label = "⚪️"
|
||||
}
|
||||
|
||||
return OrderTradeTypeUsdtTrc20
|
||||
return label
|
||||
}
|
||||
|
||||
func (o *TradeOrders) GetDetailUrl() string {
|
||||
|
||||
return GetDetailUrl(o.TradeType, o.TradeHash)
|
||||
}
|
||||
|
||||
func GetDetailUrl(tradeType, hash string) string {
|
||||
if tradeType == OrderTradeTypeUsdtErc20 {
|
||||
return "https://etherscan.io/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtBep20 {
|
||||
return "https://bscscan.com/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtXlayer {
|
||||
return "https://web3.okx.com/zh-hans/explorer/x-layer/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtPolygon {
|
||||
return "https://polygonscan.com/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtSolana {
|
||||
return "https://solscan.io/tx/" + hash
|
||||
}
|
||||
if tradeType == OrderTradeTypeUsdtAptos {
|
||||
return fmt.Sprintf("https://explorer.aptoslabs.com/txn/%s?network=mainnet", hash)
|
||||
}
|
||||
|
||||
return "https://tronscan.org/#/transaction/" + hash
|
||||
}
|
||||
|
||||
func GetTradeOrder(tradeId string) (TradeOrders, bool) {
|
||||
var order TradeOrders
|
||||
var res = DB.Where("trade_id = ?", tradeId).First(&order)
|
||||
var res = DB.Where("trade_id = ?", tradeId).Take(&order)
|
||||
|
||||
return order, res.Error == nil
|
||||
}
|
||||
|
||||
func GetTradeOrderByStatus(Status int) []TradeOrders {
|
||||
func GetOrderByStatus(Status int) []TradeOrders {
|
||||
var orders = make([]TradeOrders, 0)
|
||||
|
||||
DB.Where("status = ?", Status).Find(&orders)
|
||||
@@ -140,7 +180,8 @@ func GetTradeOrderByStatus(Status int) []TradeOrders {
|
||||
|
||||
func GetNotifyFailedTradeOrders() ([]TradeOrders, error) {
|
||||
var orders []TradeOrders
|
||||
var res = DB.Where("status = ?", OrderStatusSuccess).Where("notify_num > ?", 0).
|
||||
var res = DB.Where("status = ?", OrderStatusSuccess).
|
||||
Where("notify_num <= ?", conf.NotifyMaxRetry).
|
||||
Where("notify_state = ?", OrderNotifyStateFail).Find(&orders)
|
||||
|
||||
return orders, res.Error
|
||||
@@ -159,10 +200,10 @@ func CalcTradeAmount(wa []WalletAddress, rate, money float64, tradeType string)
|
||||
lock[order.Address+order.Amount] = true
|
||||
}
|
||||
|
||||
var atom, prec = config.GetUsdtAtomicity()
|
||||
var atom, prec = conf.GetUsdtAtomicity()
|
||||
if tradeType == OrderTradeTypeTronTrx {
|
||||
|
||||
atom, prec = config.GetTrxAtomicity()
|
||||
atom, prec = conf.GetTrxAtomicity()
|
||||
}
|
||||
|
||||
var payAmount, _ = decimal.NewFromString(strconv.FormatFloat(money/rate, 'f', prec, 64))
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
WebhookStatusWait = 0
|
||||
WebhookStatusSucc = 1
|
||||
WebhookStatusFail = -1
|
||||
)
|
||||
|
||||
const (
|
||||
WebhookEventOrderCreate = "order.create" // 订单创建
|
||||
WebhookEventOrderPaid = "order.paid" // 订单支付
|
||||
WebhookEventOrderTimeout = "order.timeout" // 订单超时
|
||||
WebhookEventOrderCancel = "order.cancel" // 订单取消
|
||||
)
|
||||
|
||||
var WebhookHandleQueue = chanx.NewUnboundedChan[Webhook](context.Background(), 30)
|
||||
|
||||
type Webhook struct {
|
||||
ID int64 `gorm:"column:id;type:INTEGER PRIMARY KEY AUTOINCREMENT;" json:"id"`
|
||||
Status int8 `gorm:"column:status;type:tinyint;not null;default:0" json:"status"`
|
||||
Num int `gorm:"column:num;type:int(11);not null;default:0" json:"hook_num"`
|
||||
Url string `gorm:"column:url;type:varchar(255);not null;default:''" json:"url"`
|
||||
Event string `gorm:"column:event;type:varchar(64);not null;default:''" json:"event"`
|
||||
Data json.RawMessage `gorm:"column:data;type:json;not null" json:"data"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime;type:timestamp;not null;comment:创建时间"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime;type:timestamp;not null;comment:更新时间"`
|
||||
}
|
||||
|
||||
func (Webhook) TableName() string {
|
||||
|
||||
return "bep_webhook"
|
||||
}
|
||||
|
||||
func (w Webhook) PostData() string {
|
||||
var data = make(map[string]any)
|
||||
|
||||
data["event"] = w.Event
|
||||
data["data"] = w.Data
|
||||
|
||||
jsonData, _ := json.Marshal(data)
|
||||
|
||||
return string(jsonData)
|
||||
}
|
||||
|
||||
func (w Webhook) SetStatus(status int8) {
|
||||
if status == WebhookStatusSucc {
|
||||
DB.Model(&Webhook{}).Where("id = ?", w.ID).Update("status", status)
|
||||
|
||||
return
|
||||
}
|
||||
if status == WebhookStatusWait {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Num = w.Num + 1
|
||||
if w.Num > conf.NotifyMaxRetry {
|
||||
|
||||
w.Status = WebhookStatusFail
|
||||
}
|
||||
|
||||
DB.Save(&w)
|
||||
}
|
||||
|
||||
func PushWebhookEvent(event string, data any) {
|
||||
go func() {
|
||||
var url = conf.GetWebhookUrl()
|
||||
if url == "" {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
bytes, _ := json.Marshal(data)
|
||||
|
||||
var w = Webhook{Status: WebhookStatusWait, Url: url, Event: event, Data: bytes}
|
||||
if err = DB.Create(&w).Error; err == nil {
|
||||
|
||||
WebhookHandleQueue.In <- w
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func ListWaitWebhooks() {
|
||||
var webhooks = make([]Webhook, 0)
|
||||
DB.Where("status = ?", WebhookStatusWait).Find(&webhooks)
|
||||
|
||||
for _, w := range webhooks {
|
||||
var next = w.CreatedAt.Add(time.Minute * time.Duration(math.Pow(2, float64(w.Num))))
|
||||
if time.Now().Unix() >= next.Unix() {
|
||||
|
||||
WebhookHandleQueue.In <- w
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"time"
|
||||
)
|
||||
|
||||
type task struct {
|
||||
Tick time.Duration
|
||||
Callback func(tick time.Duration)
|
||||
}
|
||||
|
||||
var scheduleList []task
|
||||
|
||||
var _paymentMinAmount, _paymentMaxAmount decimal.Decimal
|
||||
|
||||
func init() {
|
||||
_paymentMinAmount = config.GetPaymentMinAmount()
|
||||
_paymentMaxAmount = config.GetPaymentMaxAmount()
|
||||
}
|
||||
|
||||
func Start() {
|
||||
for _, t := range scheduleList {
|
||||
go t.Callback(t.Tick)
|
||||
}
|
||||
}
|
||||
|
||||
func RegisterSchedule(tick time.Duration, callback func(tick time.Duration)) {
|
||||
scheduleList = append(scheduleList, task{
|
||||
Tick: tick,
|
||||
Callback: callback,
|
||||
})
|
||||
}
|
||||
|
||||
func inPaymentAmountRange(payAmount decimal.Decimal) bool {
|
||||
if payAmount.GreaterThan(_paymentMaxAmount) {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if payAmount.LessThan(_paymentMinAmount) {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notify"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterSchedule(time.Second*3, NotifyStart)
|
||||
}
|
||||
|
||||
func NotifyStart(duration time.Duration) {
|
||||
log.Info("回调监控启动.")
|
||||
for range time.Tick(duration) {
|
||||
tradeOrders, err := model.GetNotifyFailedTradeOrders()
|
||||
if err != nil {
|
||||
log.Error("待回调订单获取失败", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, order := range tradeOrders {
|
||||
var next = help.CalcNextNotifyTime(order.ConfirmedAt, order.NotifyNum)
|
||||
if time.Now().Unix() >= next.Unix() {
|
||||
|
||||
go notify.Handle(order)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notify"
|
||||
"github.com/v03413/bepusdt/app/telegram"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type polygonUsdtTransfer struct {
|
||||
From string
|
||||
To string
|
||||
Amount float64
|
||||
Hash string
|
||||
BlockNum int64
|
||||
Timestamp time.Time
|
||||
TradeType string
|
||||
}
|
||||
|
||||
var polygonLastBlockNumber int64
|
||||
var polygonBlockScanQueue = chanx.NewUnboundedChan[int64](context.Background(), 30)
|
||||
var polygonUsdtTransferQueue = chanx.NewUnboundedChan[[]polygonUsdtTransfer](context.Background(), 30)
|
||||
|
||||
const usdtPolygonContractAddress = "0xc2132d05d31c914a87c6611c10748aeb04b58e8f"
|
||||
const usdtPolygonTransferMethodID = "0xa9059cbb" // Function: transfer(address recipient, uint256 amount)
|
||||
const contentType = "application/json"
|
||||
|
||||
func init() {
|
||||
RegisterSchedule(time.Second*3, polygonBlockNumber)
|
||||
RegisterSchedule(time.Second, polygonBlockScan)
|
||||
RegisterSchedule(time.Second, polygonUsdtTransferHandle)
|
||||
}
|
||||
|
||||
func polygonUsdtTransferHandle(time.Duration) {
|
||||
for {
|
||||
select {
|
||||
case transfers := <-polygonUsdtTransferQueue.Out:
|
||||
var orders = getAllWaitingOrders()
|
||||
for _, t := range transfers {
|
||||
// 计算交易金额
|
||||
var amount, quant = parseTransAmount(t.Amount)
|
||||
|
||||
// 判断金额是否在允许范围内
|
||||
if !inPaymentAmountRange(amount) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断是否存在对应订单
|
||||
order, is := orders[fmt.Sprintf("%s%v%s", t.To, quant, t.TradeType)]
|
||||
if !is {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 有效期检测
|
||||
if !order.CreatedAt.Before(t.Timestamp) || !order.ExpiredAt.After(t.Timestamp) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 更新信息
|
||||
order.OrderUpdateTxInfo(t.BlockNum, t.From, t.Hash, t.Timestamp)
|
||||
|
||||
// 标记成功
|
||||
order.MarkSuccess()
|
||||
|
||||
go notify.Handle(order) // 通知订单支付成功
|
||||
go telegram.SendTradeSuccMsg(order) // TG发送订单信息
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func polygonProcessBlock(n any) {
|
||||
var num = n.(int64)
|
||||
var url = config.GetPolygonRpcEndpoint()
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
var post = []byte(fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x%x",true],"id":1}`, num))
|
||||
|
||||
resp, err := client.Post(url, contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
polygonBlockScanQueue.In <- num
|
||||
log.Warn("Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
polygonBlockScanQueue.In <- num
|
||||
log.Warn("Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
var data = gjson.ParseBytes(body)
|
||||
if data.Get("error").Exists() {
|
||||
polygonBlockScanQueue.In <- num
|
||||
log.Warn("Polygon getBlockByNumber response error ", data.Get("error").String())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var result = data.Get("result")
|
||||
var timestamp = help.HexStr2Int(result.Get("timestamp").String())
|
||||
var transfers = make([]polygonUsdtTransfer, 0)
|
||||
for _, v := range result.Get("transactions").Array() {
|
||||
if v.Get("to").String() != usdtPolygonContractAddress {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var input = v.Get("input").String()
|
||||
var methodID = input[:10]
|
||||
if methodID != usdtPolygonTransferMethodID {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount, ok := new(big.Int).SetString(input[74:], 16)
|
||||
if !ok {
|
||||
log.Warn("Error converting amount" + input[74:])
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, polygonUsdtTransfer{
|
||||
From: v.Get("from").String(),
|
||||
To: "0x" + input[34:74],
|
||||
Amount: float64(amount.Int64()),
|
||||
Hash: v.Get("hash").String(),
|
||||
BlockNum: num,
|
||||
Timestamp: time.Unix(timestamp, 0),
|
||||
TradeType: model.OrderTradeTypeUsdtPolygon,
|
||||
})
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", num, "POLYGON")
|
||||
|
||||
if len(transfers) == 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
polygonUsdtTransferQueue.In <- transfers
|
||||
}
|
||||
|
||||
func polygonBlockScan(time.Duration) {
|
||||
p, err := ants.NewPoolWithFunc(8, polygonProcessBlock)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range polygonBlockScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
polygonBlockScanQueue.In <- n
|
||||
|
||||
log.Warn("Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func polygonBlockNumber(d time.Duration) {
|
||||
var url = config.GetPolygonRpcEndpoint()
|
||||
var jsonData = []byte(`{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}`)
|
||||
var client = &http.Client{Timeout: time.Second * 5}
|
||||
|
||||
for range time.Tick(d) {
|
||||
resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
log.Warn("Error sending request:", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("Error reading response body:", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
_ = resp.Body.Close()
|
||||
|
||||
var res = gjson.ParseBytes(body)
|
||||
var number = help.HexStr2Int(res.Get("result").String())
|
||||
if number == 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if config.GetTradeConfirmed() { // 暂且认为30个区块之前的交易已经被全网确认
|
||||
|
||||
number = number - 30
|
||||
}
|
||||
|
||||
// 首次启动
|
||||
if polygonLastBlockNumber == 0 {
|
||||
|
||||
polygonLastBlockNumber = number - 1
|
||||
}
|
||||
|
||||
// 区块高度没有变化
|
||||
if number <= polygonLastBlockNumber {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for n := polygonLastBlockNumber + 1; n <= number; n++ {
|
||||
|
||||
polygonBlockScanQueue.In <- n
|
||||
}
|
||||
|
||||
polygonLastBlockNumber = number
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/telegram"
|
||||
"time"
|
||||
)
|
||||
|
||||
var err error
|
||||
|
||||
func init() {
|
||||
RegisterSchedule(0, BotStart)
|
||||
}
|
||||
|
||||
func BotStart(time.Duration) {
|
||||
var version = app.Version
|
||||
var botApi = telegram.GetBotApi()
|
||||
if botApi == nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
_, err = botApi.MakeRequest("deleteWebhook", tgbotapi.Params{})
|
||||
if err != nil {
|
||||
|
||||
log.Error("TG Bot deleteWebhook Error:", err)
|
||||
}
|
||||
|
||||
u := tgbotapi.NewUpdate(0)
|
||||
u.Timeout = 60
|
||||
updates := botApi.GetUpdatesChan(u)
|
||||
if err != nil {
|
||||
log.Error("TG Bot GetUpdatesChan Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
telegram.SendWelcome(version)
|
||||
|
||||
// 监听消息
|
||||
for _u := range updates {
|
||||
if _u.Message != nil {
|
||||
if !_u.FromChat().IsPrivate() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
telegram.HandleMessage(_u.Message)
|
||||
}
|
||||
if _u.CallbackQuery != nil {
|
||||
|
||||
telegram.HandleCallback(_u.CallbackQuery)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,525 +0,0 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/notify"
|
||||
"github.com/v03413/bepusdt/app/telegram"
|
||||
"github.com/v03413/tronprotocol/api"
|
||||
"github.com/v03413/tronprotocol/core"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/backoff"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 交易所在区块高度和当前区块高度差值超过20,说明此交易已经被网络确认
|
||||
const blockHeightNumConfirmedSub = 20
|
||||
|
||||
// usdt trc20 contract address 41a614f803b6fd780986a42c78ec9c7f77e6ded13c TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
|
||||
var usdtTrc20ContractAddress = []byte{0x41, 0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd, 0x78, 0x09, 0x86, 0xa4, 0x2c, 0x78, 0xec, 0x9c, 0x7f, 0x77, 0xe6, 0xde, 0xd1, 0x3c}
|
||||
|
||||
var currentBlockHeight int64
|
||||
|
||||
type resource struct {
|
||||
ID string
|
||||
Type core.Transaction_Contract_ContractType
|
||||
Balance int64
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
ResourceCode core.ResourceCode
|
||||
}
|
||||
|
||||
type transfer struct {
|
||||
ID string
|
||||
Amount float64
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType string
|
||||
}
|
||||
|
||||
type usdtTrc20TransferRaw struct {
|
||||
RecvAddress string
|
||||
Amount float64
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterSchedule(time.Second*3, BlockScanStart)
|
||||
}
|
||||
|
||||
// BlockScanStart 区块扫描
|
||||
func BlockScanStart(duration time.Duration) {
|
||||
var node = config.GetTronGrpcNode()
|
||||
log.Info("区块扫描启动:", node)
|
||||
|
||||
reParams := grpc.ConnectParams{
|
||||
Backoff: backoff.Config{BaseDelay: 1 * time.Second, MaxDelay: 30 * time.Second, Multiplier: 1.5},
|
||||
MinConnectTimeout: 1 * time.Minute,
|
||||
}
|
||||
|
||||
conn, err := grpc.NewClient(node, grpc.WithConnectParams(reParams), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
|
||||
log.Error("grpc.NewClient", err)
|
||||
}
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
var client = api.NewWalletClient(conn)
|
||||
|
||||
for range time.Tick(duration) { // 3秒产生一个区块
|
||||
atomic.AddUint64(&config.BlockScanTotal, 1)
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*3)
|
||||
nowBlock, err1 := client.GetNowBlock2(ctx, nil)
|
||||
cancel()
|
||||
if err1 != nil {
|
||||
log.Warn("GetNowBlock 超时:", err1)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
atomic.AddUint64(&config.BlockScanSucc, 1)
|
||||
|
||||
if currentBlockHeight == 0 { // 初始化当前区块高度
|
||||
|
||||
currentBlockHeight = nowBlock.BlockHeader.RawData.Number - 1
|
||||
}
|
||||
|
||||
// 连续区块
|
||||
var sub = nowBlock.BlockHeader.RawData.Number - currentBlockHeight
|
||||
if sub == 1 {
|
||||
parseBlockTrans(nowBlock, nowBlock.BlockHeader.RawData.Number)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 如果当前区块高度和上次扫描的区块高度差值超过1,说明存在区块丢失
|
||||
var startBlockHeight = currentBlockHeight + 1
|
||||
var endBlockHeight = nowBlock.BlockHeader.RawData.Number
|
||||
|
||||
// 扫描丢失的区块
|
||||
var ctx2, cancel2 = context.WithTimeout(context.Background(), time.Second*3)
|
||||
blocks, err2 := client.GetBlockByLimitNext2(ctx2, &api.BlockLimit{StartNum: startBlockHeight, EndNum: endBlockHeight})
|
||||
cancel2()
|
||||
if err2 != nil {
|
||||
log.Warn("GetBlockByLimitNext2 超时:", err2)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 扫描丢失区块
|
||||
for _, block := range blocks.GetBlock() {
|
||||
parseBlockTrans(block, block.BlockHeader.RawData.Number)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseBlockTrans 解析区块交易
|
||||
func parseBlockTrans(block *api.BlockExtention, nowHeight int64) {
|
||||
currentBlockHeight = nowHeight
|
||||
|
||||
var resources = make([]resource, 0)
|
||||
var transfers = make([]transfer, 0)
|
||||
var timestamp = time.UnixMilli(block.GetBlockHeader().GetRawData().GetTimestamp())
|
||||
for _, v := range block.GetTransactions() {
|
||||
if !v.Result.Result {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var itm = v.GetTransaction()
|
||||
var id = hex.EncodeToString(v.Txid)
|
||||
for _, contract := range itm.GetRawData().GetContract() {
|
||||
// 资源代理 DelegateResourceContract
|
||||
if contract.GetType() == core.Transaction_Contract_DelegateResourceContract {
|
||||
var foo = &core.DelegateResourceContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
resources = append(resources, resource{
|
||||
ID: id,
|
||||
Type: core.Transaction_Contract_DelegateResourceContract,
|
||||
Balance: foo.Balance,
|
||||
ResourceCode: foo.Resource,
|
||||
FromAddress: base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: base58CheckEncode(foo.ReceiverAddress),
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
// 资源回收 UnDelegateResourceContract
|
||||
if contract.GetType() == core.Transaction_Contract_UnDelegateResourceContract {
|
||||
var foo = &core.UnDelegateResourceContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
resources = append(resources, resource{
|
||||
ID: id,
|
||||
Type: core.Transaction_Contract_UnDelegateResourceContract,
|
||||
Balance: foo.Balance,
|
||||
ResourceCode: foo.Resource,
|
||||
FromAddress: base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: base58CheckEncode(foo.ReceiverAddress),
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
// TRX转账交易
|
||||
if contract.GetType() == core.Transaction_Contract_TransferContract {
|
||||
var foo = &core.TransferContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
ID: id,
|
||||
Amount: float64(foo.Amount),
|
||||
FromAddress: base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: base58CheckEncode(foo.ToAddress),
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeTronTrx,
|
||||
})
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 触发智能合约
|
||||
if contract.GetType() == core.Transaction_Contract_TriggerSmartContract {
|
||||
var foo = &core.TriggerSmartContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var transItem = transfer{Timestamp: timestamp, ID: id, FromAddress: base58CheckEncode(foo.OwnerAddress)}
|
||||
var reader = bytes.NewReader(foo.GetData())
|
||||
if !bytes.Equal(foo.GetContractAddress(), usdtTrc20ContractAddress) { // usdt trc20 contract
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析合约数据
|
||||
var trc20Contract = parseUsdtTrc20Contract(reader)
|
||||
if trc20Contract.Amount == 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transItem.TradeType = model.OrderTradeTypeUsdtTrc20
|
||||
transItem.Amount = trc20Contract.Amount
|
||||
transItem.RecvAddress = trc20Contract.RecvAddress
|
||||
|
||||
transfers = append(transfers, transItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(transfers) > 0 {
|
||||
handleOtherNotify(handleOrderTransaction(block.GetBlockHeader().GetRawData().GetNumber(), nowHeight, transfers))
|
||||
}
|
||||
|
||||
if len(resources) > 0 {
|
||||
handleResourceNotify(resources)
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", nowHeight, "TRON")
|
||||
}
|
||||
|
||||
// parseUsdtTrc20Contract 解析usdt trc20合约
|
||||
func parseUsdtTrc20Contract(reader *bytes.Reader) usdtTrc20TransferRaw {
|
||||
var funcName = make([]byte, 4)
|
||||
_, err = reader.Read(funcName)
|
||||
if err != nil {
|
||||
// 读取funcName失败
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
}
|
||||
if !bytes.Equal(funcName, []byte{0xa9, 0x05, 0x9c, 0xbb}) { // a9059cbb transfer(address,uint256)
|
||||
// funcName不匹配transfer
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
}
|
||||
|
||||
var addressBytes = make([]byte, 20)
|
||||
_, err = reader.ReadAt(addressBytes, 4+12)
|
||||
if err != nil {
|
||||
// 读取toAddress失败
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
}
|
||||
|
||||
var toAddress = base58CheckEncode(append([]byte{0x41}, addressBytes...))
|
||||
var value = make([]byte, 32)
|
||||
_, err = reader.ReadAt(value, 36)
|
||||
if err != nil {
|
||||
// 读取value失败
|
||||
|
||||
return usdtTrc20TransferRaw{}
|
||||
}
|
||||
|
||||
var amount, _ = strconv.ParseInt(hex.EncodeToString(value), 16, 64)
|
||||
|
||||
return usdtTrc20TransferRaw{RecvAddress: toAddress, Amount: float64(amount)}
|
||||
}
|
||||
|
||||
// handleOrderTransaction 处理支付交易
|
||||
func handleOrderTransaction(refBlockNum, nowHeight int64, transfers []transfer) []transfer {
|
||||
var orders = getAllWaitingOrders()
|
||||
var notOrderTransfers []transfer
|
||||
|
||||
for _, t := range transfers {
|
||||
// 计算交易金额
|
||||
var amount, quant = parseTransAmount(t.Amount)
|
||||
|
||||
// 判断金额是否在允许范围内
|
||||
if !inPaymentAmountRange(amount) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断是否存在对应订单
|
||||
order, isOrder := orders[fmt.Sprintf("%s%v%s", t.RecvAddress, quant, t.TradeType)]
|
||||
if !isOrder {
|
||||
notOrderTransfers = append(notOrderTransfers, t)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断时间是否在有效期内
|
||||
if t.Timestamp.Unix() < order.CreatedAt.Unix() || t.Timestamp.Unix() > order.ExpiredAt.Unix() {
|
||||
// 已失效
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 更新订单交易信息
|
||||
order.OrderUpdateTxInfo(refBlockNum, t.FromAddress, t.ID, t.Timestamp)
|
||||
}
|
||||
|
||||
for _, order := range orders {
|
||||
if order.RefBlockNum == 0 || order.TradeHash == "" {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断交易是否需要被确认
|
||||
var confirmedSub int64 = 0
|
||||
if config.GetTradeConfirmed() {
|
||||
|
||||
confirmedSub = blockHeightNumConfirmedSub
|
||||
}
|
||||
|
||||
if nowHeight-order.RefBlockNum <= confirmedSub {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
order.MarkSuccess()
|
||||
|
||||
go notify.Handle(order) // 通知订单支付成功
|
||||
go telegram.SendTradeSuccMsg(order) // TG发送订单信息
|
||||
}
|
||||
|
||||
return notOrderTransfers
|
||||
}
|
||||
|
||||
// handleOtherNotify 处理其他通知
|
||||
func handleOtherNotify(items []transfer) {
|
||||
var ads []model.WalletAddress
|
||||
var tx = model.DB.Where("status = ? and other_notify = ?", model.StatusEnable, model.OtherNotifyEnable).Find(&ads)
|
||||
if tx.RowsAffected <= 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for _, wa := range ads {
|
||||
for _, trans := range items {
|
||||
if trans.RecvAddress != wa.Address && trans.FromAddress != wa.Address {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var amount, quant = parseTransAmount(trans.Amount)
|
||||
var detailUrl = "https://tronscan.org/#/transaction/" + trans.ID
|
||||
if !inPaymentAmountRange(amount) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if !model.IsNeedNotifyByTxid(trans.ID) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var title = "收入"
|
||||
if trans.RecvAddress != wa.Address {
|
||||
title = "支出"
|
||||
}
|
||||
|
||||
var transferUnit = "USDT.TRC20"
|
||||
var transferType = "USDT"
|
||||
if trans.TradeType == model.OrderTradeTypeTronTrx {
|
||||
transferUnit = "TRX"
|
||||
transferType = "TRX"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(
|
||||
"#账户%s #非订单交易 #"+transferType+"\n---\n```\n💲交易数额:%v "+transferUnit+"\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n",
|
||||
title,
|
||||
quant,
|
||||
trans.Timestamp.Format(time.DateTime),
|
||||
help.MaskAddress(trans.RecvAddress),
|
||||
help.MaskAddress(trans.FromAddress),
|
||||
)
|
||||
|
||||
var chatId, err = strconv.ParseInt(config.GetTgBotNotifyTarget(), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var msg = tgbotapi.NewMessage(chatId, text)
|
||||
msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
msg.ReplyMarkup = tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonURL("📝查看交易明细", detailUrl),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var _record = model.NotifyRecord{Txid: trans.ID}
|
||||
model.DB.Create(&_record)
|
||||
|
||||
go telegram.SendMsg(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleResourceNotify 处理资源通知
|
||||
func handleResourceNotify(items []resource) {
|
||||
var ads []model.WalletAddress
|
||||
var tx = model.DB.Where("status = ? and other_notify = ?", model.StatusEnable, model.OtherNotifyEnable).Find(&ads)
|
||||
if tx.RowsAffected <= 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for _, wa := range ads {
|
||||
for _, trans := range items {
|
||||
if trans.RecvAddress != wa.Address && trans.FromAddress != wa.Address {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if trans.ResourceCode != core.ResourceCode_ENERGY {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var detailUrl = "https://tronscan.org/#/transaction/" + trans.ID
|
||||
if !model.IsNeedNotifyByTxid(trans.ID) {
|
||||
// 不需要额外通知
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var title = "代理"
|
||||
if trans.Type == core.Transaction_Contract_UnDelegateResourceContract {
|
||||
title = "回收"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(
|
||||
"#资源动态 #能量"+title+"\n---\n```\n🔋质押数量:"+cast.ToString(trans.Balance/1000000)+"\n⏱️交易时间:%v\n✅操作地址:%v\n🅾️资源来源:%v```\n",
|
||||
trans.Timestamp.Format(time.DateTime),
|
||||
help.MaskAddress(trans.RecvAddress),
|
||||
help.MaskAddress(trans.FromAddress),
|
||||
)
|
||||
|
||||
var chatId, err = strconv.ParseInt(config.GetTgBotNotifyTarget(), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var msg = tgbotapi.NewMessage(chatId, text)
|
||||
msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
msg.ReplyMarkup = tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonURL("📝查看交易明细", detailUrl),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var _record = model.NotifyRecord{Txid: trans.ID}
|
||||
model.DB.Create(&_record)
|
||||
|
||||
go telegram.SendMsg(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func base58CheckEncode(input []byte) string {
|
||||
checksum := chainhash.DoubleHashB(input)
|
||||
checksum = checksum[:4]
|
||||
|
||||
input = append(input, checksum...)
|
||||
|
||||
return base58.Encode(input)
|
||||
}
|
||||
|
||||
// 列出所有待支付交易订单
|
||||
func getAllWaitingOrders() map[string]model.TradeOrders {
|
||||
var tradeOrders = model.GetTradeOrderByStatus(model.OrderStatusWaiting)
|
||||
var data = make(map[string]model.TradeOrders) // 当前所有正在等待支付的订单 Lock Key
|
||||
for _, order := range tradeOrders {
|
||||
if time.Now().Unix() >= order.ExpiredAt.Unix() { // 订单过期
|
||||
order.OrderSetExpired()
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if order.TradeType == model.OrderTradeTypeUsdtPolygon {
|
||||
|
||||
order.Address = strings.ToLower(order.Address)
|
||||
}
|
||||
|
||||
data[order.Address+order.Amount+order.TradeType] = order
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// 解析交易金额
|
||||
func parseTransAmount(amount float64) (decimal.Decimal, string) {
|
||||
var result = decimal.NewFromFloat(amount).Div(decimal.NewFromFloat(1000000))
|
||||
|
||||
return result, result.String()
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
e "github.com/v03413/bepusdt/app/epay"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/telegram"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Handle(order model.TradeOrders) {
|
||||
if order.ApiType == model.OrderApiTypeEpay {
|
||||
epay(order)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
epusdt(order)
|
||||
}
|
||||
|
||||
func epay(order model.TradeOrders) {
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var notifyUrl = fmt.Sprintf("%s?%s", order.NotifyUrl, e.BuildNotifyParams(order))
|
||||
|
||||
postReq, err2 := http.NewRequest("GET", notifyUrl, nil)
|
||||
if err2 != nil {
|
||||
log.Error("Notify NewRequest Error:", err2)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
log.Error("Notify Handle Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
markNotifyFail(order, fmt.Sprintf("resp.StatusCode != 200"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
markNotifyFail(order, fmt.Sprintf("io.ReadAll(resp.Body) Error: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 判断是否包含 success
|
||||
if !strings.Contains(strings.ToLower(string(all)), "success") {
|
||||
markNotifyFail(order, fmt.Sprintf("body not contains success (%s)", string(all)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = order.OrderSetNotifyState(model.OrderNotifyStateSucc)
|
||||
if err != nil {
|
||||
log.Error("订单标记通知成功错误:", err, order.OrderId)
|
||||
} else {
|
||||
log.Info("订单通知成功:", order.OrderId)
|
||||
}
|
||||
}
|
||||
|
||||
func epusdt(order model.TradeOrders) {
|
||||
var data = make(map[string]interface{})
|
||||
var body = struct {
|
||||
TradeId string `json:"trade_id"` // 本地订单号
|
||||
OrderId string `json:"order_id"` // 客户交易id
|
||||
Amount float64 `json:"amount"` // 订单金额 CNY
|
||||
ActualAmount string `json:"actual_amount"` // USDT 交易数额
|
||||
Token string `json:"token"` // 收款钱包地址
|
||||
BlockTransactionId string `json:"block_transaction_id"` // 区块id
|
||||
Signature string `json:"signature"` // 签名
|
||||
Status int `json:"status"` // 1:等待支付,2:支付成功,3:订单超时
|
||||
}{
|
||||
TradeId: order.TradeId,
|
||||
OrderId: order.OrderId,
|
||||
Amount: order.Money,
|
||||
ActualAmount: order.Amount,
|
||||
Token: order.Address,
|
||||
BlockTransactionId: order.TradeHash,
|
||||
Status: order.Status,
|
||||
}
|
||||
var jsonBody, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
log.Error("Notify Json Marshal Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
log.Error("Notify JSON Unmarshal Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 签名
|
||||
body.Signature = help.EpusdtSign(data, config.GetAuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, err = json.Marshal(body)
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var postReq, err2 = http.NewRequest("POST", order.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err2 != nil {
|
||||
log.Error("Notify NewRequest Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
postReq.Header.Set("Content-Type", "application/json")
|
||||
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
log.Error("Notify Handle Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
markNotifyFail(order, fmt.Sprintf("resp.StatusCode != 200"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
markNotifyFail(order, fmt.Sprintf("io.ReadAll(resp.Body) Error: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if string(all) != "ok" {
|
||||
markNotifyFail(order, fmt.Sprintf("body != ok (%s)", string(all)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = order.OrderSetNotifyState(model.OrderNotifyStateSucc)
|
||||
if err != nil {
|
||||
log.Error("订单标记通知成功错误:", err, order.OrderId)
|
||||
} else {
|
||||
log.Info("订单通知成功:", order.OrderId)
|
||||
}
|
||||
}
|
||||
|
||||
func markNotifyFail(order model.TradeOrders, reason string) {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):%s %v", order.TradeId, reason, order.OrderSetNotifyState(model.OrderNotifyStateFail)))
|
||||
go func() {
|
||||
telegram.SendNotifyFailed(order, reason)
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
aptosPayloadType = "entry_function_payload"
|
||||
)
|
||||
|
||||
type aptos struct {
|
||||
versionChunkSize int64
|
||||
versionConfirmedOffset int64
|
||||
versionInitStartOffset int64
|
||||
lastVersion int64
|
||||
versionQueue *chanx.UnboundedChan[version]
|
||||
}
|
||||
|
||||
type version struct {
|
||||
Start int64
|
||||
Limit int64
|
||||
}
|
||||
|
||||
var apt aptos
|
||||
|
||||
func init() {
|
||||
apt = newAptos()
|
||||
register(task{callback: apt.versionDispatch})
|
||||
register(task{callback: apt.versionRoll, duration: time.Second * 3})
|
||||
}
|
||||
|
||||
func newAptos() aptos {
|
||||
return aptos{
|
||||
versionChunkSize: 100, // 目前好像最大就只能100
|
||||
versionConfirmedOffset: 1000,
|
||||
versionInitStartOffset: -100 * 500,
|
||||
lastVersion: 0,
|
||||
versionQueue: chanx.NewUnboundedChan[version](context.Background(), 30),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) versionRoll(context.Context) {
|
||||
if rollBreak(conf.Aptos) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := client.Get(conf.GetAptosRpcNode() + "/v1")
|
||||
if err != nil {
|
||||
log.Warn("aptos versionRoll Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Warn("aptos versionRoll Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("aptos versionRoll Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "ledger_version").Int()
|
||||
if now <= 0 {
|
||||
log.Warn("versionRoll Error: invalid ledger_version:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - a.versionConfirmedOffset
|
||||
}
|
||||
|
||||
if now-a.lastVersion > 10000 {
|
||||
a.versionInitOffset(now)
|
||||
a.lastVersion = now - a.versionChunkSize
|
||||
}
|
||||
|
||||
var sub = now - a.lastVersion
|
||||
if now == 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if sub <= a.versionChunkSize {
|
||||
a.versionQueue.In <- version{Start: a.lastVersion, Limit: sub}
|
||||
} else {
|
||||
chunks := (sub + a.versionChunkSize - 1) / a.versionChunkSize
|
||||
for i := int64(0); i < chunks; i++ {
|
||||
limit := a.versionChunkSize
|
||||
start := a.lastVersion + a.versionChunkSize*i
|
||||
if i == chunks-1 {
|
||||
limit = sub % a.versionChunkSize
|
||||
if limit == 0 {
|
||||
limit = a.versionChunkSize
|
||||
}
|
||||
}
|
||||
|
||||
a.versionQueue.In <- version{Start: start, Limit: limit}
|
||||
}
|
||||
}
|
||||
|
||||
a.lastVersion = now
|
||||
}
|
||||
|
||||
func (a *aptos) versionDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, a.versionParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case n := <-a.versionQueue.Out:
|
||||
if err := p.Invoke(n); err != nil {
|
||||
a.versionQueue.In <- n
|
||||
log.Warn("versionDispatch Error invoking process slot:", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Warn("versionDispatch context done:", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) versionInitOffset(now int64) {
|
||||
if now == 0 || a.lastVersion != 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
var end = now + a.versionInitStartOffset
|
||||
for s := now - a.versionChunkSize; s >= end; s = s - a.versionChunkSize {
|
||||
if rollBreak(conf.Aptos) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
a.versionQueue.In <- version{Start: s, Limit: a.versionChunkSize}
|
||||
|
||||
<-ticker.C
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *aptos) versionParse(n any) {
|
||||
p := n.(version)
|
||||
|
||||
var network = conf.Aptos
|
||||
var url = fmt.Sprintf("%sv1/transactions?start=%d&limit=%d", conf.GetAptosRpcNode(), p.Start, p.Limit)
|
||||
|
||||
conf.SetBlockTotal(network)
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("versionParse Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("versionParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
a.versionQueue.In <- p
|
||||
log.Warn("versionParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !gjson.ValidBytes(body) {
|
||||
conf.SetBlockFail(network)
|
||||
a.versionQueue.In <- p
|
||||
log.Warn("versionParse Error: invalid JSON response body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for _, trans := range gjson.ParseBytes(body).Array() {
|
||||
tsNano := trans.Get("timestamp").Int() * 1000
|
||||
timestamp := time.Unix(tsNano/1e9, tsNano%1e9)
|
||||
function := trans.Get("payload.function").String()
|
||||
typeName := trans.Get("payload.type").String()
|
||||
if typeName != aptosPayloadType {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
hash := trans.Get("hash").String()
|
||||
sender := trans.Get("sender").String()
|
||||
ver := trans.Get("version").Int()
|
||||
args := trans.Get("payload.arguments").Array()
|
||||
|
||||
switch function {
|
||||
case "0x1::primary_fungible_store::transfer":
|
||||
a.parsePrimaryFungibleStoreTransfer(network, hash, sender, ver, timestamp, args)
|
||||
case "0x1::aptos_account::batch_transfer_fungible_assets":
|
||||
a.parseAptosAccountBatchTransferFungibleAssets(network, hash, sender, ver, timestamp, args)
|
||||
case "0x1::aptos_account::transfer_fungible_assets":
|
||||
a.parseAptosAccountTransferFungibleAssets(network, hash, sender, ver, timestamp, args)
|
||||
case "0x1::fungible_asset::transfer":
|
||||
// 待定
|
||||
case "0x1::coin::transfer":
|
||||
// 待定
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", fmt.Sprintf("%d.%d", p.Start, p.Limit), conf.GetBlockSuccRate(network), network)
|
||||
}
|
||||
|
||||
func (a *aptos) parsePrimaryFungibleStoreTransfer(net, hash, sender string, ver int64, t time.Time, args []gjson.Result) {
|
||||
if args[0].Get("inner").String() != conf.UsdtAptos {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rawAmount := new(big.Int)
|
||||
rawAmount.SetString(args[2].String(), 10)
|
||||
|
||||
transferQueue.In <- []transfer{{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(rawAmount, conf.UsdtAptosDecimals),
|
||||
FromAddress: sender,
|
||||
RecvAddress: args[1].String(),
|
||||
Timestamp: t,
|
||||
TradeType: model.OrderTradeTypeUsdtAptos,
|
||||
BlockNum: ver,
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *aptos) parseAptosAccountBatchTransferFungibleAssets(net, hash, sender string, ver int64, t time.Time, args []gjson.Result) {
|
||||
if args[0].Get("inner").String() != conf.UsdtAptos {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var result = make([]transfer, 0)
|
||||
for i, recv := range args[1].Array() {
|
||||
rawAmount := new(big.Int)
|
||||
rawAmount.SetString(args[2].Get(fmt.Sprintf("%d", i)).String(), 10)
|
||||
if rawAmount == nil || rawAmount.Sign() <= 0 {
|
||||
log.Warn("parseAptosAccountBatchTransferFungibleAssets Error: invalid amount for receiver", recv.String(), "in transaction", hash)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
result = append(result, transfer{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(rawAmount, conf.UsdtAptosDecimals),
|
||||
FromAddress: sender,
|
||||
RecvAddress: recv.String(),
|
||||
Timestamp: t,
|
||||
TradeType: model.OrderTradeTypeUsdtAptos,
|
||||
BlockNum: ver,
|
||||
})
|
||||
}
|
||||
|
||||
if len(result) > 0 {
|
||||
transferQueue.In <- result
|
||||
}
|
||||
}
|
||||
|
||||
func (a *aptos) parseAptosAccountTransferFungibleAssets(net, hash, sender string, ver int64, t time.Time, args []gjson.Result) {
|
||||
if args[0].Get("inner").String() != conf.UsdtAptos {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rawAmount := new(big.Int)
|
||||
rawAmount.SetString(args[2].String(), 10)
|
||||
|
||||
transferQueue.In <- []transfer{
|
||||
{
|
||||
Network: net,
|
||||
TxHash: hash,
|
||||
Amount: decimal.NewFromBigInt(rawAmount, conf.UsdtAptosDecimals),
|
||||
FromAddress: sender,
|
||||
RecvAddress: args[1].String(),
|
||||
Timestamp: t,
|
||||
TradeType: model.OrderTradeTypeUsdtAptos,
|
||||
BlockNum: ver,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/v03413/bepusdt/app/bot"
|
||||
)
|
||||
|
||||
var err error
|
||||
|
||||
func init() {
|
||||
register(task{callback: BotStart})
|
||||
}
|
||||
|
||||
func BotStart(context.Context) {
|
||||
|
||||
bot.Start()
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"time"
|
||||
)
|
||||
|
||||
func bscInit() {
|
||||
register(task{
|
||||
ctx: context.WithValue(context.Background(), "cfg", evmCfg{
|
||||
Endpoint: conf.GetBscRpcEndpoint(),
|
||||
Type: conf.Bsc,
|
||||
Decimals: decimals{
|
||||
Usdt: conf.UsdtBscDecimals,
|
||||
Native: -18, // bsc.bnb 小数位数
|
||||
},
|
||||
Block: block{
|
||||
InitStartOffset: -400,
|
||||
ConfirmedOffset: 15,
|
||||
},
|
||||
}),
|
||||
duration: time.Second * 3,
|
||||
callback: evmBlockRoll,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ethInit() {
|
||||
register(task{
|
||||
ctx: context.WithValue(context.Background(), "cfg", evmCfg{
|
||||
Endpoint: conf.GetEthereumRpcEndpoint(),
|
||||
Type: conf.Ethereum,
|
||||
Decimals: decimals{
|
||||
Usdt: conf.UsdtEthDecimals,
|
||||
Native: -18, // ethereum.eth 小数位数
|
||||
},
|
||||
Block: block{
|
||||
InitStartOffset: -100,
|
||||
ConfirmedOffset: 12,
|
||||
},
|
||||
}),
|
||||
duration: time.Second * 12,
|
||||
callback: evmBlockRoll,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
blockParseMaxNum = 10 // 每次解析区块的最大数量
|
||||
|
||||
usdtTransfer = "0xa9059cbb" // Tether transfer function ID
|
||||
contentType = "application/json"
|
||||
|
||||
inputAddressTotal = 138 // USDT转账 input 正确总长度
|
||||
inputAddressStart = 34 // USDT转账 接收地址在input中的起始位置
|
||||
inputAddressEnd = 74 // USDT转账 接收地址在input中的结束位置 amount在input中的起始位置
|
||||
)
|
||||
|
||||
var chainBlockNum sync.Map
|
||||
var nativeToken = map[string]string{
|
||||
conf.Bsc: model.OrderTradeTypeBscBnb,
|
||||
conf.Xlayer: model.OrderTradeTypeXlayerOkb,
|
||||
conf.Polygon: model.OrderTradeTypePolygonPol,
|
||||
conf.Ethereum: model.OrderTradeTypeEthEth,
|
||||
}
|
||||
var contractMap = map[string]string{
|
||||
conf.UsdtXlayer: model.OrderTradeTypeUsdtXlayer,
|
||||
conf.UsdtBep20: model.OrderTradeTypeUsdtBep20,
|
||||
conf.UsdtPolygon: model.OrderTradeTypeUsdtPolygon,
|
||||
conf.UsdtErc20: model.OrderTradeTypeUsdtErc20,
|
||||
}
|
||||
var chainUsdtMap = map[string]string{
|
||||
conf.Bsc: model.OrderTradeTypeUsdtBep20,
|
||||
conf.Xlayer: model.OrderTradeTypeUsdtXlayer,
|
||||
conf.Polygon: model.OrderTradeTypeUsdtPolygon,
|
||||
conf.Ethereum: model.OrderTradeTypeUsdtErc20,
|
||||
conf.Solana: model.OrderTradeTypeUsdtSolana,
|
||||
conf.Aptos: model.OrderTradeTypeUsdtAptos,
|
||||
}
|
||||
|
||||
var client = &http.Client{Timeout: time.Second * 30}
|
||||
var chainScanQueue = chanx.NewUnboundedChan[[]evmBlock](context.Background(), 30)
|
||||
|
||||
type decimals struct {
|
||||
Usdt int32 // USDT小数位数
|
||||
Native int32 // 原生代币小数位数
|
||||
}
|
||||
|
||||
type block struct {
|
||||
InitStartOffset int64 // 首次偏移量,第一次启动时,区块高度需要叠加此值,设置为负值可解决部分已创建但未超时(未扫描)的订单问题
|
||||
RollDelayOffset int64 // 延迟偏移量,某些RPC节点如果不延迟,会报错 block is out of range,目前发现 https://rpc.xlayer.tech/ 存在此问题
|
||||
ConfirmedOffset int64 // 确认偏移量,开启交易确认后,区块高度需要减去此值认为交易已确认
|
||||
}
|
||||
|
||||
type evmCfg struct {
|
||||
Type string
|
||||
Endpoint string
|
||||
Decimals decimals
|
||||
Block block
|
||||
}
|
||||
|
||||
type evmBlock struct {
|
||||
Network evmCfg
|
||||
Num int64
|
||||
}
|
||||
|
||||
func init() {
|
||||
register(task{callback: evmBlockDispatch})
|
||||
}
|
||||
|
||||
func evmBlockRoll(ctx context.Context) {
|
||||
val := ctx.Value("cfg")
|
||||
if val == nil {
|
||||
log.Warn("evmBlockRoll: context value 'cfg' is nil")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
cfg, ok := val.(evmCfg)
|
||||
if !ok {
|
||||
log.Warn("evmBlockRoll: context value 'cfg' is not of type evmCfg")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if rollBreak(cfg.Type) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
post := []byte(`{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}`)
|
||||
resp, err := client.Post(cfg.Endpoint, contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
log.Warn("Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var res = gjson.ParseBytes(body)
|
||||
var now = help.HexStr2Int(res.Get("result").String()).Int64() - cfg.Block.RollDelayOffset
|
||||
if now <= 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - cfg.Block.ConfirmedOffset
|
||||
}
|
||||
|
||||
var lastBlockNumber int64
|
||||
if v, ok := chainBlockNum.Load(cfg.Type); ok {
|
||||
|
||||
lastBlockNumber = v.(int64)
|
||||
}
|
||||
|
||||
if now-lastBlockNumber > conf.BlockHeightMaxDiff {
|
||||
|
||||
lastBlockNumber = evmBlockInitOffset(now, cfg.Block.InitStartOffset, cfg) - 1
|
||||
}
|
||||
|
||||
chainBlockNum.Store(cfg.Type, now)
|
||||
if now <= lastBlockNumber { // 区块高度没有变化
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
blocks := make([]evmBlock, 0)
|
||||
for n := lastBlockNumber + 1; n <= now; n++ {
|
||||
blocks = append(blocks, evmBlock{Num: n, Network: cfg})
|
||||
if len(blocks) >= blockParseMaxNum {
|
||||
chainScanQueue.In <- blocks
|
||||
blocks = make([]evmBlock, 0)
|
||||
}
|
||||
}
|
||||
|
||||
if len(blocks) > 0 {
|
||||
chainScanQueue.In <- blocks
|
||||
}
|
||||
}
|
||||
|
||||
func evmBlockInitOffset(now, offset int64, cfg evmCfg) int64 {
|
||||
go func() {
|
||||
var blocks []evmBlock
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for b := now; b >= now+offset; b-- {
|
||||
if rollBreak(cfg.Type) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
blocks = append(blocks, evmBlock{Num: b, Network: cfg})
|
||||
if len(blocks) >= blockParseMaxNum {
|
||||
chainScanQueue.In <- blocks
|
||||
blocks = blocks[:0]
|
||||
}
|
||||
|
||||
<-ticker.C
|
||||
}
|
||||
if len(blocks) > 0 {
|
||||
chainScanQueue.In <- blocks
|
||||
}
|
||||
}()
|
||||
|
||||
return now
|
||||
}
|
||||
|
||||
func evmBlockDispatch(context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(8, evmBlockParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range chainScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
chainScanQueue.In <- n
|
||||
|
||||
log.Warn("evmBlockDispatch Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func evmBlockParse(b any) {
|
||||
var blocks, ok = b.([]evmBlock)
|
||||
if !ok {
|
||||
log.Warn("evmBlockParse: received non-evmBlock type")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
first := blocks[0]
|
||||
items := make([]string, 0)
|
||||
for _, v := range blocks {
|
||||
conf.SetBlockTotal(v.Network.Type)
|
||||
items = append(items, fmt.Sprintf(`{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x%x",true],"id":%d}`, v.Num, v.Num))
|
||||
}
|
||||
|
||||
post := []byte(fmt.Sprintf(`[%s]`, strings.Join(items, ",")))
|
||||
resp, err := client.Post(first.Network.Endpoint, contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
conf.SetBlockFail(first.Network.Type)
|
||||
chainScanQueue.In <- blocks
|
||||
log.Warn("Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(first.Network.Type)
|
||||
chainScanQueue.In <- blocks
|
||||
log.Warn("Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var list = gjson.ParseBytes(body).Array()
|
||||
for _, data := range list {
|
||||
if !data.Get("result").Exists() {
|
||||
conf.SetBlockFail(first.Network.Type)
|
||||
chainScanQueue.In <- []evmBlock{{Network: first.Network, Num: data.Get("id").Int()}}
|
||||
log.Warn(fmt.Sprintf("%s getBlockByNumber response error %s", first.Network.Type, data.String()))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
num := data.Get("id").Int()
|
||||
result := data.Get("result")
|
||||
timestamp := time.Unix(help.HexStr2Int(result.Get("timestamp").String()).Int64(), 0)
|
||||
transfers := make([]transfer, 0)
|
||||
for _, v := range result.Get("transactions").Array() {
|
||||
recv := v.Get("to").String()
|
||||
input := v.Get("input").String()
|
||||
rawValue := v.Get("value").String()
|
||||
rawAmount, ok := new(big.Int).SetString(rawValue, 0)
|
||||
if !ok {
|
||||
log.Warn("Error converting value to integer:" + " " + rawValue)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount := decimal.NewFromBigInt(rawAmount, first.Network.Decimals.Native)
|
||||
tradeType := evmParseTradeType(first.Network.Type, recv, input, rawAmount)
|
||||
if tradeType == nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if !tradeType.Native && len(input) == inputAddressTotal { // usdt transfer
|
||||
rawAmount, ok = new(big.Int).SetString(input[inputAddressEnd:], 16)
|
||||
if !ok {
|
||||
log.Warn("Error converting amount(value):" + input[inputAddressEnd:])
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
amount = decimal.NewFromBigInt(rawAmount, first.Network.Decimals.Usdt)
|
||||
recv = "0x" + input[inputAddressStart:inputAddressEnd] // USDT转账接收地址
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: first.Network.Type,
|
||||
FromAddress: v.Get("from").String(),
|
||||
RecvAddress: recv,
|
||||
Amount: amount,
|
||||
TxHash: v.Get("hash").String(),
|
||||
BlockNum: num,
|
||||
Timestamp: timestamp,
|
||||
TradeType: tradeType.Type,
|
||||
})
|
||||
}
|
||||
|
||||
if len(transfers) > 0 {
|
||||
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", num, conf.GetBlockSuccRate(first.Network.Type), first.Network.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func evmParseTradeType(net, to, input string, value *big.Int) *model.TradeType {
|
||||
var tradeType, ok = nativeToken[net]
|
||||
if ok && input == "0x" && value.Sign() == 1 { // 原生代币
|
||||
|
||||
return &model.TradeType{Type: tradeType, Native: true}
|
||||
}
|
||||
|
||||
// 触发合约
|
||||
tradeType, ok = contractMap[to]
|
||||
if ok && strings.HasPrefix(input, usdtTransfer) { // USDT转账
|
||||
|
||||
return &model.TradeType{Type: tradeType, Native: false}
|
||||
}
|
||||
|
||||
// 其他合约数据
|
||||
return nil
|
||||
}
|
||||
|
||||
func rollBreak(network string) bool {
|
||||
usdt, ok := chainUsdtMap[network]
|
||||
if !ok {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var count int64 = 0
|
||||
model.DB.Model(&model.TradeOrders{}).Where("status = ? and trade_type = ?", model.OrderStatusWaiting, usdt).Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
model.DB.Model(&model.WalletAddress{}).Where("other_notify = ? and trade_type = ?", model.OtherNotifyEnable, usdt).Count(&count)
|
||||
if count > 0 {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/web/notify"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register(task{duration: time.Second * 3, callback: notifyRetry})
|
||||
register(task{duration: time.Second * 30, callback: notifyRoll})
|
||||
}
|
||||
|
||||
// notifyRetry 回调失败重试
|
||||
func notifyRetry(context.Context) {
|
||||
tradeOrders, err := model.GetNotifyFailedTradeOrders()
|
||||
if err != nil {
|
||||
log.Error("待回调订单获取失败", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for _, order := range tradeOrders {
|
||||
var next = help.CalcNextNotifyTime(order.ConfirmedAt, order.NotifyNum)
|
||||
if time.Now().Unix() >= next.Unix() {
|
||||
|
||||
go notify.Handle(order)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func notifyRoll(context.Context) {
|
||||
for _, o := range model.GetOrderByStatus(model.OrderStatusWaiting) {
|
||||
notify.Bepusdt(o)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
package monitor
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/rate"
|
||||
"github.com/v03413/bepusdt/app/task/rate"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -14,38 +15,32 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterSchedule(0, OkxUsdtRateStart)
|
||||
RegisterSchedule(0, OkxTrxUsdtRateStart)
|
||||
register(task{duration: time.Minute, callback: OkxUsdtRateStart})
|
||||
register(task{duration: time.Minute, callback: OkxTrxUsdtRateStart})
|
||||
}
|
||||
|
||||
// OkxUsdtRateStart Okx USDT_CNY 汇率监控
|
||||
func OkxUsdtRateStart(time.Duration) {
|
||||
for {
|
||||
var rawRate, err = getOkxUsdtCnySellPrice()
|
||||
if err != nil {
|
||||
log.Error("Okx USDT_CNY 汇率获取失败", err)
|
||||
} else {
|
||||
rate.SetOkxUsdtCnyRate(config.GetUsdtRate(), rawRate)
|
||||
}
|
||||
|
||||
log.Info("当前 USDT_CNY 计算汇率:", rate.GetUsdtCalcRate(config.DefaultUsdtCnyRate))
|
||||
time.Sleep(time.Minute)
|
||||
func OkxUsdtRateStart(context.Context) {
|
||||
var rawRate, err = getOkxUsdtCnySellPrice()
|
||||
if err != nil {
|
||||
log.Error("Okx USDT_CNY 汇率获取失败", err)
|
||||
} else {
|
||||
rate.SetOkxUsdtCnyRate(conf.GetUsdtRate(), rawRate)
|
||||
}
|
||||
|
||||
log.Info("当前 USDT_CNY 计算汇率:", rate.GetUsdtCalcRate())
|
||||
}
|
||||
|
||||
// OkxTrxUsdtRateStart Okx TRX_CNY 汇率监控
|
||||
func OkxTrxUsdtRateStart(time.Duration) {
|
||||
for {
|
||||
var price, err = getOkxTrxCnyMarketPrice()
|
||||
if err != nil {
|
||||
log.Error("Okx TRX_USDT 汇率获取失败", err)
|
||||
} else {
|
||||
rate.SetOkxTrxCnyRate(config.GetTrxRate(), price)
|
||||
}
|
||||
|
||||
log.Info("当前 TRX_CNY 计算汇率:", rate.GetTrxCalcRate(config.DefaultTrxCnyRate))
|
||||
time.Sleep(time.Minute)
|
||||
func OkxTrxUsdtRateStart(context.Context) {
|
||||
var price, err = getOkxTrxCnyMarketPrice()
|
||||
if err != nil {
|
||||
log.Error("Okx TRX_USDT 汇率获取失败", err)
|
||||
} else {
|
||||
rate.SetOkxTrxCnyRate(conf.GetTrxRate(), price)
|
||||
}
|
||||
|
||||
log.Info("当前 TRX_CNY 计算汇率:", rate.GetTrxCalcRate())
|
||||
}
|
||||
|
||||
// getOkxUsdtCnySellPrice Okx C2C快捷交易 USDT出售 实时汇率
|
||||
@@ -0,0 +1,26 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"time"
|
||||
)
|
||||
|
||||
func polygonInit() {
|
||||
register(task{
|
||||
ctx: context.WithValue(context.Background(), "cfg", evmCfg{
|
||||
Endpoint: conf.GetPolygonRpcEndpoint(),
|
||||
Type: conf.Polygon,
|
||||
Decimals: decimals{
|
||||
Usdt: conf.UsdtPolygonDecimals,
|
||||
Native: -18, // polygon.pol 小数位数
|
||||
},
|
||||
Block: block{
|
||||
InitStartOffset: -600,
|
||||
ConfirmedOffset: 40,
|
||||
},
|
||||
}),
|
||||
duration: time.Second * 3,
|
||||
callback: evmBlockRoll,
|
||||
})
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package rate
|
||||
import (
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"math"
|
||||
@@ -12,26 +12,18 @@ import (
|
||||
|
||||
var okxTrxCnyCalcRate = 0.0
|
||||
var okxUsdtCnyCalcRate = 0.0
|
||||
var okxUsdtCnyRawRate = config.DefaultUsdtCnyRate // okx 交易所 usdt 兑 cny原始汇率
|
||||
var okxTrxCnyRawRate = config.DefaultTrxCnyRate // okx 交易所 trx/cny 市场价
|
||||
var okxRatePrecision = 2 // 汇率保留位数,强迫症,另一方面两位小数足以覆盖大部分CNY使用场景
|
||||
var okxUsdtCnyRawRate = conf.DefaultUsdtCnyRate // okx 交易所 usdt/cny 原始汇率;6.4是初始默认值值,后续但凡有新的汇率数据更新都会覆盖这个值
|
||||
var okxTrxCnyRawRate = conf.DefaultTrxCnyRate // okx 交易所 trx/cny 原始汇率
|
||||
var okxRatePrecision = 2 // 汇率保留位数,强迫症,另一方面两位小数足以覆盖大部分CNY使用场景
|
||||
|
||||
func GetTrxCalcRate(defaultRate float64) float64 {
|
||||
if okxTrxCnyCalcRate > 0 {
|
||||
func GetTrxCalcRate() float64 {
|
||||
|
||||
return okxTrxCnyCalcRate
|
||||
}
|
||||
|
||||
return defaultRate
|
||||
return okxTrxCnyCalcRate
|
||||
}
|
||||
|
||||
func GetUsdtCalcRate(defaultRate float64) float64 {
|
||||
if okxUsdtCnyCalcRate > 0 {
|
||||
func GetUsdtCalcRate() float64 {
|
||||
|
||||
return okxUsdtCnyCalcRate
|
||||
}
|
||||
|
||||
return defaultRate
|
||||
return okxUsdtCnyCalcRate
|
||||
}
|
||||
|
||||
func GetOkxUsdtRawRate() float64 {
|
||||
@@ -47,16 +39,16 @@ func GetOkxTrxRawRate() float64 {
|
||||
func SetOkxTrxCnyRate(syntax string, rawRate float64) {
|
||||
rawRate = round(rawRate, okxRatePrecision)
|
||||
okxTrxCnyRawRate = rawRate
|
||||
okxTrxCnyCalcRate = parseFloatRate(syntax, rawRate)
|
||||
okxTrxCnyCalcRate = ParseFloatRate(syntax, rawRate)
|
||||
}
|
||||
|
||||
func SetOkxUsdtCnyRate(syntax string, rawRate float64) {
|
||||
rawRate = round(rawRate, okxRatePrecision)
|
||||
okxUsdtCnyRawRate = rawRate
|
||||
okxUsdtCnyCalcRate = parseFloatRate(syntax, rawRate)
|
||||
okxUsdtCnyCalcRate = ParseFloatRate(syntax, rawRate)
|
||||
}
|
||||
|
||||
func parseFloatRate(syntax string, rawVal float64) float64 {
|
||||
func ParseFloatRate(syntax string, rawVal float64) float64 {
|
||||
if syntax == "" {
|
||||
|
||||
return rawVal
|
||||
@@ -0,0 +1,336 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"math/big"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 参考文档
|
||||
// - https://solana.com/zh/docs/rpc
|
||||
// - https://github.com/solana-program/token/blob/main/program/src/instruction.rs
|
||||
|
||||
type solana struct {
|
||||
slotConfirmedOffset int64
|
||||
slotInitStartOffset int64
|
||||
lastSlotNum int64
|
||||
slotQueue *chanx.UnboundedChan[int64]
|
||||
}
|
||||
|
||||
var sol solana
|
||||
|
||||
func init() {
|
||||
sol = newSolana()
|
||||
register(task{callback: sol.slotDispatch})
|
||||
register(task{callback: sol.slotRoll, duration: time.Second * 5})
|
||||
}
|
||||
|
||||
func newSolana() solana {
|
||||
return solana{
|
||||
slotConfirmedOffset: 60,
|
||||
slotInitStartOffset: -600,
|
||||
lastSlotNum: 0,
|
||||
slotQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *solana) slotRoll(context.Context) {
|
||||
if rollBreak(conf.Solana) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
post := []byte(`{"jsonrpc":"2.0","id":1,"method":"getSlot"}`)
|
||||
|
||||
resp, err := client.Post(conf.GetSolanaRpcEndpoint(), contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
log.Warn("slotRoll Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Warn("slotRoll Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warn("slotRoll Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
now := gjson.GetBytes(body, "result").Int()
|
||||
if now <= 0 {
|
||||
log.Warn("slotRoll Error: invalid slot number:", now)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - s.slotConfirmedOffset
|
||||
}
|
||||
|
||||
if now-s.lastSlotNum > conf.BlockHeightMaxDiff { // 区块高度变化过大,强制丢块重扫
|
||||
s.lastSlotNum = now
|
||||
s.slotInitOffset(now)
|
||||
}
|
||||
|
||||
if now == s.lastSlotNum { // 区块高度没有变化
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for n := s.lastSlotNum + 1; n <= now; n++ {
|
||||
// 待扫描区块入列
|
||||
|
||||
s.slotQueue.In <- n
|
||||
}
|
||||
|
||||
s.lastSlotNum = now
|
||||
}
|
||||
|
||||
func (s *solana) slotDispatch(ctx context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(3, s.slotParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for {
|
||||
select {
|
||||
case slot := <-s.slotQueue.Out:
|
||||
if err := p.Invoke(slot); err != nil {
|
||||
s.slotQueue.In <- slot
|
||||
log.Warn("slotDispatch Error invoking process slot:", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
log.Warn("slotDispatch context done:", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// slotInitOffset 初始化区块高度偏移,往回扫一定数量的区块
|
||||
func (s *solana) slotInitOffset(now int64) {
|
||||
if now == 0 || s.lastSlotNum != 0 {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Millisecond * 300)
|
||||
defer ticker.Stop()
|
||||
|
||||
for num := now; num >= now+s.slotInitStartOffset; num-- {
|
||||
if rollBreak(conf.Solana) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
s.slotQueue.In <- num
|
||||
|
||||
<-ticker.C
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *solana) slotParse(n any) {
|
||||
slot := n.(int64)
|
||||
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
|
||||
|
||||
conf.SetBlockTotal(network)
|
||||
resp, err := client.Post(conf.GetSolanaRpcEndpoint(), contentType, bytes.NewBuffer(post))
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("slotParse Error sending request:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
conf.SetBlockFail(network)
|
||||
log.Warn("slotParse Error response status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
conf.SetBlockFail(network)
|
||||
s.slotQueue.In <- slot
|
||||
log.Warn("slotParse Error reading response body:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
timestamp := time.Unix(gjson.GetBytes(body, "result.blockTime").Int(), 0)
|
||||
|
||||
for _, trans := range gjson.GetBytes(body, "result.transactions").Array() {
|
||||
hash := trans.Get("transaction.signatures.0").String()
|
||||
|
||||
// 解析账号索引
|
||||
accountKeys := make([]string, 0)
|
||||
for _, key := range trans.Get("transaction.message.accountKeys").Array() {
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
for _, v := range []string{"readonly", "writable"} {
|
||||
for _, key := range trans.Get("meta.loadedAddresses." + v).Array() {
|
||||
|
||||
accountKeys = append(accountKeys, key.String())
|
||||
}
|
||||
}
|
||||
|
||||
// 查找SPL Token索引
|
||||
splTokenIndex := int64(-1)
|
||||
for i, v := range accountKeys {
|
||||
if v == conf.SolSplToken {
|
||||
splTokenIndex = int64(i)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// SPL Token的Mint地址,即不包含USDT交易信息
|
||||
if splTokenIndex == -1 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析 USDT Token 账户 【Token Address => Owner Address】
|
||||
usdtTokenAccountMap := make(map[string]string)
|
||||
for _, v := range []string{"postTokenBalances", "preTokenBalances"} {
|
||||
for _, itm := range trans.Get("meta." + v).Array() {
|
||||
if itm.Get("mint").String() != conf.UsdtSolana || itm.Get("programId").String() != conf.SolSplToken {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
usdtTokenAccountMap[accountKeys[itm.Get("accountIndex").Int()]] = itm.Get("owner").String()
|
||||
}
|
||||
}
|
||||
|
||||
transArr := make([]transfer, 0)
|
||||
|
||||
// 解析外部指令
|
||||
for _, instr := range trans.Get("transaction.message.instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, usdtTokenAccountMap))
|
||||
}
|
||||
|
||||
// 解析内部指令
|
||||
innerInstructions := trans.Get("meta.innerInstructions").Array()
|
||||
if len(innerInstructions) == 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, itm := range innerInstructions {
|
||||
for _, instr := range itm.Get("instructions").Array() {
|
||||
if instr.Get("programIdIndex").Int() != splTokenIndex {
|
||||
// 不是SPL Token的指令,即不会包含合约代表 transfer 的指令
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transArr = append(transArr, s.parseTransfer(instr, accountKeys, usdtTokenAccountMap))
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤无关交易
|
||||
result := make([]transfer, 0)
|
||||
for _, t := range transArr {
|
||||
if t.FromAddress == "" || t.RecvAddress == "" || t.Amount.IsZero() {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
t.TxHash = hash
|
||||
t.Network = conf.Solana
|
||||
t.BlockNum = slot
|
||||
t.Timestamp = timestamp
|
||||
t.TradeType = model.OrderTradeTypeUsdtSolana
|
||||
|
||||
result = append(result, t)
|
||||
}
|
||||
|
||||
if len(result) > 0 {
|
||||
transferQueue.In <- result
|
||||
}
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", slot, conf.GetBlockSuccRate(network), network)
|
||||
}
|
||||
|
||||
func (s *solana) parseTransfer(instr gjson.Result, accountKeys []string, usdtTokenAccountMap map[string]string) transfer {
|
||||
accounts := instr.Get("accounts").Array()
|
||||
trans := transfer{}
|
||||
if len(accounts) < 3 { // from to singer,至少存在3个账户索引,如果是多签则 > 3
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
data := base58.Decode(instr.Get("data").String())
|
||||
dLen := len(data)
|
||||
isTransfer := data[0] == 3 && dLen == 9
|
||||
isTransferChecked := data[0] == 12 && dLen == 10
|
||||
if !isTransfer && !isTransferChecked {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
var exp int32 = -6
|
||||
if isTransferChecked {
|
||||
exp = int32(data[9]) * -1
|
||||
}
|
||||
|
||||
from, ok := usdtTokenAccountMap[accountKeys[accounts[0].Int()]]
|
||||
if !ok {
|
||||
|
||||
return trans
|
||||
}
|
||||
|
||||
trans.FromAddress = from
|
||||
trans.RecvAddress = usdtTokenAccountMap[accountKeys[accounts[1].Int()]]
|
||||
if isTransferChecked {
|
||||
trans.RecvAddress = usdtTokenAccountMap[accountKeys[accounts[2].Int()]]
|
||||
}
|
||||
|
||||
buf := make([]byte, 8)
|
||||
copy(buf[:], data[1:9])
|
||||
number := binary.LittleEndian.Uint64(buf)
|
||||
b := new(big.Int)
|
||||
b.SetUint64(number)
|
||||
trans.Amount = decimal.NewFromBigInt(b, exp) // USDT的精度是6位小数
|
||||
|
||||
return trans
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
type task struct {
|
||||
ctx context.Context
|
||||
duration time.Duration
|
||||
callback func(ctx context.Context)
|
||||
}
|
||||
|
||||
var (
|
||||
tasks []task
|
||||
mu sync.Mutex
|
||||
)
|
||||
|
||||
func Init() error {
|
||||
bscInit()
|
||||
ethInit()
|
||||
polygonInit()
|
||||
xlayerInit()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func register(t task) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if t.ctx == nil {
|
||||
|
||||
t.ctx = context.Background()
|
||||
}
|
||||
|
||||
if t.callback == nil {
|
||||
|
||||
panic("task callback cannot be nil")
|
||||
}
|
||||
|
||||
tasks = append(tasks, t)
|
||||
}
|
||||
|
||||
func inAmountRange(payAmount decimal.Decimal) bool {
|
||||
if payAmount.GreaterThan(conf.GetPaymentAmountMax()) {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if payAmount.LessThan(conf.GetPaymentAmountMin()) {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func Start() {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
for _, t := range tasks {
|
||||
go func(t task) {
|
||||
if t.duration <= 0 {
|
||||
t.callback(t.ctx)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
t.callback(t.ctx)
|
||||
|
||||
ticker := time.NewTicker(t.duration)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-t.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
t.callback(t.ctx)
|
||||
}
|
||||
}
|
||||
}(t)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
bot2 "github.com/v03413/bepusdt/app/bot"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/web/notify"
|
||||
"github.com/v03413/tronprotocol/core"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type transfer struct {
|
||||
Network string
|
||||
TxHash string
|
||||
Amount decimal.Decimal
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
TradeType string
|
||||
BlockNum int64
|
||||
}
|
||||
|
||||
type resource struct {
|
||||
ID string
|
||||
Type core.Transaction_Contract_ContractType
|
||||
Balance int64
|
||||
FromAddress string
|
||||
RecvAddress string
|
||||
Timestamp time.Time
|
||||
ResourceCode core.ResourceCode
|
||||
}
|
||||
|
||||
var resourceQueue = chanx.NewUnboundedChan[[]resource](context.Background(), 30) // 资源队列
|
||||
var notOrderQueue = chanx.NewUnboundedChan[[]transfer](context.Background(), 30) // 非订单队列
|
||||
var transferQueue = chanx.NewUnboundedChan[[]transfer](context.Background(), 30) // 交易转账队列
|
||||
|
||||
func init() {
|
||||
register(task{callback: orderTransferHandle})
|
||||
register(task{callback: notOrderTransferHandle})
|
||||
register(task{callback: tronResourceHandle})
|
||||
}
|
||||
|
||||
func orderTransferHandle(context.Context) {
|
||||
for transfers := range transferQueue.Out {
|
||||
var other = make([]transfer, 0)
|
||||
var orders = getAllWaitingOrders()
|
||||
for _, t := range transfers {
|
||||
// debug
|
||||
//if t.Network == conf.Aptos {
|
||||
// fmt.Println(t.Network, t.TradeType, t.TxHash, t.Amount.String(), t.RecvAddress)
|
||||
//}
|
||||
|
||||
// 判断金额是否在允许范围内
|
||||
if !inAmountRange(t.Amount) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 判断是否存在对应订单
|
||||
o, ok := orders[fmt.Sprintf("%s%v%s", t.RecvAddress, t.Amount.String(), t.TradeType)]
|
||||
if !ok {
|
||||
other = append(other, t)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 有效期检测
|
||||
if !o.CreatedAt.Before(t.Timestamp) || !o.ExpiredAt.After(t.Timestamp) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 标记成功
|
||||
o.MarkSuccess(t.BlockNum, t.FromAddress, t.TxHash, t.Timestamp)
|
||||
|
||||
model.PushWebhookEvent(model.WebhookEventOrderPaid, o)
|
||||
|
||||
go notify.Handle(o) // 通知订单支付成功
|
||||
go bot2.SendTradeSuccMsg(o) // TG发送订单信息
|
||||
}
|
||||
|
||||
if len(other) > 0 {
|
||||
notOrderQueue.In <- other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func notOrderTransferHandle(context.Context) {
|
||||
for transfers := range notOrderQueue.Out {
|
||||
var was []model.WalletAddress
|
||||
|
||||
model.DB.Where("other_notify = ?", model.OtherNotifyEnable).Find(&was)
|
||||
|
||||
for _, wa := range was {
|
||||
for _, t := range transfers {
|
||||
if t.RecvAddress != wa.Address && t.FromAddress != wa.Address {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if !inAmountRange(t.Amount) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if !model.IsNeedNotifyByTxid(t.TxHash) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var title = "收入"
|
||||
if t.RecvAddress != wa.Address {
|
||||
title = "支出"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(
|
||||
"\\#账户%s \\#非订单交易\n\\-\\-\\-\n```\n💲交易数额:%v \n💍交易类别:"+strings.ToUpper(t.TradeType)+"\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n",
|
||||
title,
|
||||
t.Amount.String(),
|
||||
t.Timestamp.Format(time.DateTime),
|
||||
help.MaskAddress(t.RecvAddress),
|
||||
help.MaskAddress(t.FromAddress),
|
||||
)
|
||||
|
||||
var record = model.NotifyRecord{Txid: t.TxHash}
|
||||
model.DB.Create(&record)
|
||||
|
||||
go bot2.SendMessage(&bot.SendMessageParams{
|
||||
ChatID: conf.BotNotifyTarget(),
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看交易明细", URL: model.GetDetailUrl(t.TradeType, t.TxHash)},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tronResourceHandle(context.Context) {
|
||||
for resources := range resourceQueue.Out {
|
||||
var was []model.WalletAddress
|
||||
var types = []string{model.OrderTradeTypeTronTrx, model.OrderTradeTypeUsdtTrc20}
|
||||
|
||||
model.DB.Where("status = ? and other_notify = ? and trade_type in (?)", model.StatusEnable, model.OtherNotifyEnable, types).Find(&was)
|
||||
|
||||
for _, wa := range was {
|
||||
for _, t := range resources {
|
||||
if t.RecvAddress != wa.Address && t.FromAddress != wa.Address {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if t.ResourceCode != core.ResourceCode_ENERGY {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var url = "https://tronscan.org/#/transaction/" + t.ID
|
||||
if !model.IsNeedNotifyByTxid(t.ID) {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var title = "代理"
|
||||
if t.Type == core.Transaction_Contract_UnDelegateResourceContract {
|
||||
title = "回收"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(
|
||||
"\\#资源动态 \\#能量"+title+"\n\\-\\-\\-\n```\n🔋质押数量:"+cast.ToString(t.Balance/1000000)+"\n⏱️交易时间:%v\n✅操作地址:%v\n🅾️资源来源:%v```\n",
|
||||
t.Timestamp.Format(time.DateTime),
|
||||
help.MaskAddress(t.RecvAddress),
|
||||
help.MaskAddress(t.FromAddress),
|
||||
)
|
||||
|
||||
var record = model.NotifyRecord{Txid: t.ID}
|
||||
model.DB.Create(&record)
|
||||
|
||||
go bot2.SendMessage(&bot.SendMessageParams{
|
||||
ChatID: conf.BotNotifyTarget(),
|
||||
Text: text,
|
||||
ParseMode: models.ParseModeMarkdown,
|
||||
ReplyMarkup: models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
models.InlineKeyboardButton{Text: "📝查看交易明细", URL: url},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getAllWaitingOrders() map[string]model.TradeOrders {
|
||||
var tradeOrders = model.GetOrderByStatus(model.OrderStatusWaiting)
|
||||
var data = make(map[string]model.TradeOrders) // 当前所有正在等待支付的订单 Lock Key
|
||||
for _, order := range tradeOrders {
|
||||
if time.Now().Unix() >= order.ExpiredAt.Unix() { // 订单过期
|
||||
order.OrderSetExpired()
|
||||
notify.Bepusdt(order)
|
||||
model.PushWebhookEvent(model.WebhookEventOrderTimeout, order)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if order.TradeType == model.OrderTradeTypeUsdtPolygon {
|
||||
|
||||
order.Address = strings.ToLower(order.Address)
|
||||
}
|
||||
|
||||
data[order.Address+order.Amount+order.TradeType] = order
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"github.com/btcsuite/btcd/btcutil/base58"
|
||||
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/tronprotocol/api"
|
||||
"github.com/v03413/tronprotocol/core"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/backoff"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"math/big"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var gasFreeUsdtTokenAddress = []byte{0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd, 0x78, 0x09, 0x86, 0xa4, 0x2c, 0x78, 0xec, 0x9c, 0x7f, 0x77, 0xe6, 0xde, 0xd1, 0x3c}
|
||||
var gasFreeOwnerAddress = []byte{0x41, 0x3b, 0x41, 0x50, 0x50, 0xb1, 0xe7, 0x9e, 0x38, 0x50, 0x7c, 0xb6, 0xe4, 0x8d, 0xac, 0xc2, 0x27, 0xaf, 0xfd, 0xd5, 0x0c}
|
||||
var gasFreeContractAddress = []byte{0x41, 0x39, 0xdd, 0x12, 0xa5, 0x4e, 0x2b, 0xab, 0x7c, 0x82, 0xaa, 0x14, 0xa1, 0xe1, 0x58, 0xb3, 0x42, 0x63, 0xd2, 0xd5, 0x10}
|
||||
var usdtTrc20ContractAddress = []byte{0x41, 0xa6, 0x14, 0xf8, 0x03, 0xb6, 0xfd, 0x78, 0x09, 0x86, 0xa4, 0x2c, 0x78, 0xec, 0x9c, 0x7f, 0x77, 0xe6, 0xde, 0xd1, 0x3c}
|
||||
var grpcParams = grpc.ConnectParams{
|
||||
Backoff: backoff.Config{BaseDelay: 1 * time.Second, MaxDelay: 30 * time.Second, Multiplier: 1.5},
|
||||
MinConnectTimeout: 1 * time.Minute,
|
||||
}
|
||||
|
||||
type tron struct {
|
||||
blockConfirmedOffset int64
|
||||
blockInitStartOffset int64
|
||||
lastBlockNum int64
|
||||
blockScanQueue *chanx.UnboundedChan[int64]
|
||||
}
|
||||
|
||||
var tr tron
|
||||
|
||||
func init() {
|
||||
tr = newTron()
|
||||
register(task{duration: time.Second * 3, callback: tr.blockRoll}) // 大概3秒产生一个区块
|
||||
register(task{duration: time.Second, callback: tr.blockDispatch})
|
||||
}
|
||||
|
||||
func newTron() tron {
|
||||
return tron{
|
||||
blockConfirmedOffset: 30, // 区块确认偏移量
|
||||
blockInitStartOffset: -400, // 大概为过去20分钟的区块高度
|
||||
lastBlockNum: 0,
|
||||
blockScanQueue: chanx.NewUnboundedChan[int64](context.Background(), 30),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tron) blockDispatch(context.Context) {
|
||||
p, err := ants.NewPoolWithFunc(8, t.blockParse)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer p.Release()
|
||||
|
||||
for n := range t.blockScanQueue.Out {
|
||||
if err := p.Invoke(n); err != nil {
|
||||
t.blockScanQueue.In <- n
|
||||
|
||||
log.Warn("Tron Error invoking process block:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tron) blockRoll(context.Context) {
|
||||
var node = conf.GetTronGrpcNode()
|
||||
|
||||
conn, err := grpc.NewClient(node, grpc.WithConnectParams(grpcParams), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
|
||||
log.Error("grpc.NewClient", err)
|
||||
}
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
var client = api.NewWalletClient(conn)
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*3)
|
||||
block, err1 := client.GetNowBlock2(ctx, nil)
|
||||
defer cancel()
|
||||
|
||||
if err1 != nil {
|
||||
log.Warn("GetNowBlock2 超时:", err1)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var now = block.BlockHeader.RawData.Number
|
||||
if conf.GetTradeIsConfirmed() {
|
||||
|
||||
now = now - t.blockConfirmedOffset
|
||||
}
|
||||
|
||||
// 首次启动
|
||||
if t.lastBlockNum == 0 {
|
||||
|
||||
t.lastBlockNum = now + t.blockInitStartOffset
|
||||
}
|
||||
|
||||
// 区块高度没有变化
|
||||
if now <= t.lastBlockNum {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 待扫描区块入列
|
||||
for n := t.lastBlockNum + 1; n <= now; n++ {
|
||||
|
||||
t.blockScanQueue.In <- n
|
||||
}
|
||||
|
||||
t.lastBlockNum = now
|
||||
}
|
||||
|
||||
func (t *tron) blockParse(n any) {
|
||||
var num = n.(int64)
|
||||
var node = conf.GetTronGrpcNode()
|
||||
var conn *grpc.ClientConn
|
||||
var err error
|
||||
if conn, err = grpc.NewClient(node, grpc.WithConnectParams(grpcParams), grpc.WithTransportCredentials(insecure.NewCredentials())); err != nil {
|
||||
|
||||
log.Error("grpc.NewClient", err)
|
||||
}
|
||||
|
||||
defer conn.Close()
|
||||
var client = api.NewWalletClient(conn)
|
||||
|
||||
conf.SetBlockTotal(conf.Tron)
|
||||
|
||||
var ctx, cancel = context.WithTimeout(context.Background(), time.Second*3)
|
||||
bok, err2 := client.GetBlockByNum2(ctx, &api.NumberMessage{Num: num})
|
||||
cancel()
|
||||
if err2 != nil {
|
||||
conf.SetBlockFail(conf.Tron)
|
||||
t.blockScanQueue.In <- num
|
||||
log.Warn("GetBlockByNum2 Error", err2)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var resources = make([]resource, 0)
|
||||
var transfers = make([]transfer, 0)
|
||||
var timestamp = time.UnixMilli(bok.GetBlockHeader().GetRawData().GetTimestamp())
|
||||
for _, trans := range bok.GetTransactions() {
|
||||
if !trans.Result.Result {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var itm = trans.GetTransaction()
|
||||
var id = hex.EncodeToString(trans.Txid)
|
||||
for _, contract := range itm.GetRawData().GetContract() {
|
||||
// 资源代理 DelegateResourceContract
|
||||
if contract.GetType() == core.Transaction_Contract_DelegateResourceContract {
|
||||
var foo = &core.DelegateResourceContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
resources = append(resources, resource{
|
||||
ID: id,
|
||||
Type: core.Transaction_Contract_DelegateResourceContract,
|
||||
Balance: foo.Balance,
|
||||
ResourceCode: foo.Resource,
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: t.base58CheckEncode(foo.ReceiverAddress),
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
// 资源回收 UnDelegateResourceContract
|
||||
if contract.GetType() == core.Transaction_Contract_UnDelegateResourceContract {
|
||||
var foo = &core.UnDelegateResourceContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
resources = append(resources, resource{
|
||||
ID: id,
|
||||
Type: core.Transaction_Contract_UnDelegateResourceContract,
|
||||
Balance: foo.Balance,
|
||||
ResourceCode: foo.Resource,
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: t.base58CheckEncode(foo.ReceiverAddress),
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
// TRX转账交易
|
||||
if contract.GetType() == core.Transaction_Contract_TransferContract {
|
||||
var foo = &core.TransferContract{}
|
||||
err := contract.GetParameter().UnmarshalTo(foo)
|
||||
if err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: conf.Tron,
|
||||
TxHash: id,
|
||||
Amount: decimal.NewFromBigInt(new(big.Int).SetInt64(foo.Amount), -6),
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: t.base58CheckEncode(foo.ToAddress),
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeTronTrx,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
})
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 触发智能合约
|
||||
if contract.GetType() == core.Transaction_Contract_TriggerSmartContract {
|
||||
var foo = &core.TriggerSmartContract{}
|
||||
if err := contract.GetParameter().UnmarshalTo(foo); err != nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// Gas Free 钱包 合约授权转账
|
||||
if bytes.Equal(foo.OwnerAddress, gasFreeOwnerAddress) && bytes.Equal(foo.ContractAddress, gasFreeContractAddress) {
|
||||
from, receiver, amount := t.gasFreePermitTransfer(foo.GetData())
|
||||
if from == "" || receiver == "" || amount == nil {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: conf.Tron,
|
||||
TxHash: id,
|
||||
Amount: decimal.NewFromBigInt(new(big.Int).SetInt64(amount.Int64()), -6),
|
||||
FromAddress: from,
|
||||
RecvAddress: receiver,
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeUsdtTrc20,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
})
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
{
|
||||
var reader = bytes.NewReader(foo.GetData())
|
||||
if !bytes.Equal(foo.GetContractAddress(), usdtTrc20ContractAddress) { // usdt trc20 contract
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// 解析合约数据
|
||||
var recvAddress, amount = t.parseUsdtTrc20Contract(reader)
|
||||
if amount == 0 {
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
transfers = append(transfers, transfer{
|
||||
Network: conf.Tron,
|
||||
TxHash: id,
|
||||
Amount: decimal.NewFromBigInt(new(big.Int).SetInt64(amount), -6),
|
||||
FromAddress: t.base58CheckEncode(foo.OwnerAddress),
|
||||
RecvAddress: recvAddress,
|
||||
Timestamp: timestamp,
|
||||
TradeType: model.OrderTradeTypeUsdtTrc20,
|
||||
BlockNum: cast.ToInt64(num),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(transfers) > 0 {
|
||||
transferQueue.In <- transfers
|
||||
}
|
||||
|
||||
if len(resources) > 0 {
|
||||
resourceQueue.In <- resources
|
||||
}
|
||||
|
||||
log.Info("区块扫描完成", num, conf.GetBlockSuccRate(conf.Tron), conf.Tron)
|
||||
}
|
||||
|
||||
func (t *tron) parseUsdtTrc20Contract(reader *bytes.Reader) (string, int64) {
|
||||
var funcName = make([]byte, 4)
|
||||
_, err = reader.Read(funcName)
|
||||
if err != nil {
|
||||
// 读取funcName失败
|
||||
|
||||
return "", 0
|
||||
}
|
||||
if !bytes.Equal(funcName, []byte{0xa9, 0x05, 0x9c, 0xbb}) { // a9059cbb transfer(address,uint256)
|
||||
// funcName不匹配transfer
|
||||
|
||||
return "", 0
|
||||
}
|
||||
|
||||
var addressBytes = make([]byte, 20)
|
||||
_, err = reader.ReadAt(addressBytes, 4+12)
|
||||
if err != nil {
|
||||
// 读取toAddress失败
|
||||
|
||||
return "", 0
|
||||
}
|
||||
|
||||
var toAddress = t.base58CheckEncode(append([]byte{0x41}, addressBytes...))
|
||||
var value = make([]byte, 32)
|
||||
_, err = reader.ReadAt(value, 36)
|
||||
if err != nil {
|
||||
// 读取value失败
|
||||
|
||||
return "", 0
|
||||
}
|
||||
|
||||
var amount, _ = strconv.ParseInt(hex.EncodeToString(value), 16, 64)
|
||||
|
||||
return toAddress, amount
|
||||
}
|
||||
|
||||
func (t *tron) gasFreePermitTransfer(data []byte) (string, string, *big.Int) {
|
||||
// https://tronscan.org/#/contract/TFFAMQLZybALaLb4uxHA9RBE7pxhUAjF3U/code?func=Tab-proxywrite-F3proxyNonePayable
|
||||
if len(data) != 420 {
|
||||
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[:4], []byte{0x6f, 0x21, 0xb8, 0x98}) {
|
||||
// not permitTransfer (6f21b898) function
|
||||
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
if !bytes.Equal(data[16:36], gasFreeUsdtTokenAddress) {
|
||||
// not gas free usdt token address
|
||||
|
||||
return "", "", nil
|
||||
}
|
||||
|
||||
user := t.base58CheckEncode(append([]byte{0x41}, data[48:68]...))
|
||||
receiver := t.base58CheckEncode(append([]byte{0x41}, data[80:100]...))
|
||||
amount := big.NewInt(0).SetBytes(data[100:132])
|
||||
|
||||
return user, receiver, amount
|
||||
}
|
||||
|
||||
func (t *tron) base58CheckEncode(input []byte) string {
|
||||
checksum := chainhash.DoubleHashB(input)
|
||||
checksum = checksum[:4]
|
||||
|
||||
input = append(input, checksum...)
|
||||
|
||||
return base58.Encode(input)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/smallnest/chanx"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var webhookQueueKey = contextKey{}
|
||||
|
||||
func init() {
|
||||
register(task{
|
||||
callback: webhookRoll,
|
||||
ctx: context.WithValue(context.Background(), webhookQueueKey, model.WebhookHandleQueue)},
|
||||
)
|
||||
}
|
||||
|
||||
func webhookRoll(ctx context.Context) {
|
||||
var w model.Webhook
|
||||
var queue = ctx.Value(webhookQueueKey).(*chanx.UnboundedChan[model.Webhook])
|
||||
var ticker = time.NewTicker(time.Minute)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
model.ListWaitWebhooks()
|
||||
case w = <-queue.Out:
|
||||
go webhookHandle(w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func webhookHandle(w model.Webhook) {
|
||||
var req, err = http.NewRequest("POST", w.Url, strings.NewReader(w.PostData()))
|
||||
if err != nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
|
||||
req.Header.Set("User-Agent", "BEpusdt/"+app.Version)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Warn("Webhook request failed:", err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
w.SetStatus(model.WebhookStatusFail)
|
||||
log.Warn("Webhook request failed with status code:", resp.StatusCode)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.SetStatus(model.WebhookStatusSucc)
|
||||
|
||||
log.Info("Webhook request success:", w.Event, "to", w.Url)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"time"
|
||||
)
|
||||
|
||||
func xlayerInit() {
|
||||
register(task{
|
||||
ctx: context.WithValue(context.Background(), "cfg", evmCfg{
|
||||
Endpoint: conf.GetXlayerRpcEndpoint(),
|
||||
Type: conf.Xlayer,
|
||||
Decimals: decimals{
|
||||
Usdt: conf.UsdtXlayerDecimals,
|
||||
Native: -18, // xlayer.okb 小数位数
|
||||
},
|
||||
Block: block{
|
||||
InitStartOffset: -600,
|
||||
RollDelayOffset: 3,
|
||||
ConfirmedOffset: 12,
|
||||
},
|
||||
}),
|
||||
duration: time.Second * 3,
|
||||
callback: evmBlockRoll,
|
||||
})
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cbWallet = "wallet"
|
||||
const cbAddress = "address"
|
||||
const cbAddressAdd = "address_add"
|
||||
const cbAddressEnable = "address_enable"
|
||||
const cbAddressDisable = "address_disable"
|
||||
const cbAddressDelete = "address_del"
|
||||
const cbAddressOtherNotify = "address_other_notify"
|
||||
const cbOrderDetail = "order_detail"
|
||||
const cbMarkNotifySucc = "mark_notify_succ"
|
||||
|
||||
func cbWalletAction(query *tgbotapi.CallbackQuery, address string) {
|
||||
var info = "暂时只支持 Tron 钱包查询..."
|
||||
if strings.HasPrefix(address, "T") {
|
||||
info = getTronWalletInfo(address)
|
||||
}
|
||||
|
||||
var msg = tgbotapi.NewMessage(query.Message.Chat.ID, "❌查询失败")
|
||||
if info != "" {
|
||||
msg.Text = info
|
||||
msg.ReplyMarkup = tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonURL("📝查看详细信息", "https://tronscan.org/#/address/"+address),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
DeleteMsg(query.Message.MessageID)
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
|
||||
func cbAddressAddHandle(query *tgbotapi.CallbackQuery) {
|
||||
var msg = tgbotapi.NewMessage(query.Message.Chat.ID, replayAddressText)
|
||||
msg.ReplyMarkup = tgbotapi.ForceReply{ForceReply: true, Selective: true, InputFieldPlaceholder: "输入钱包地址"}
|
||||
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
|
||||
func cbAddressAction(query *tgbotapi.CallbackQuery, id string) {
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
var otherTextLabel = "✅已启用 非订单交易监控通知"
|
||||
if wa.OtherNotify != 1 {
|
||||
otherTextLabel = "❌已禁用 非订单交易监控通知"
|
||||
}
|
||||
|
||||
EditAndSendMsg(query.Message.MessageID, wa.Address, tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonData("✅启用", cbAddressEnable+"|"+id),
|
||||
tgbotapi.NewInlineKeyboardButtonData("❌禁用", cbAddressDisable+"|"+id),
|
||||
tgbotapi.NewInlineKeyboardButtonData("⛔️删除", cbAddressDelete+"|"+id),
|
||||
},
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonData(otherTextLabel, cbAddressOtherNotify+"|"+id),
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressEnableAction(query *tgbotapi.CallbackQuery, id string) {
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
// 修改地址状态
|
||||
wa.SetStatus(model.StatusEnable)
|
||||
|
||||
// 删除历史消息
|
||||
DeleteMsg(query.Message.MessageID)
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle()
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressDisableAction(query *tgbotapi.CallbackQuery, id string) {
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
// 修改地址状态
|
||||
wa.SetStatus(model.StatusDisable)
|
||||
|
||||
// 删除历史消息
|
||||
DeleteMsg(query.Message.MessageID)
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle()
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressDeleteAction(query *tgbotapi.CallbackQuery, id string) {
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
// 删除钱包地址
|
||||
wa.Delete()
|
||||
|
||||
// 删除历史消息
|
||||
DeleteMsg(query.Message.MessageID)
|
||||
|
||||
// 推送最新状态
|
||||
cmdStartHandle()
|
||||
}
|
||||
}
|
||||
|
||||
func cbAddressOtherNotifyAction(query *tgbotapi.CallbackQuery, id string) {
|
||||
var wa model.WalletAddress
|
||||
if model.DB.Where("id = ?", id).First(&wa).Error == nil {
|
||||
if wa.OtherNotify == 1 {
|
||||
wa.SetOtherNotify(model.OtherNotifyDisable)
|
||||
} else {
|
||||
wa.SetOtherNotify(model.OtherNotifyEnable)
|
||||
}
|
||||
|
||||
DeleteMsg(query.Message.MessageID)
|
||||
|
||||
cmdStartHandle()
|
||||
}
|
||||
}
|
||||
|
||||
func cbOrderDetailAction(tradeId string) {
|
||||
var o model.TradeOrders
|
||||
|
||||
if model.DB.Where("trade_id = ?", tradeId).First(&o).Error == nil {
|
||||
var urlInfo, er2 = url.Parse(o.NotifyUrl)
|
||||
if er2 != nil {
|
||||
log.Error("商户网站地址解析错误:" + er2.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var _notifyStateLabel = "✅ 回调成功"
|
||||
if o.NotifyState != model.OrderNotifyStateSucc {
|
||||
_notifyStateLabel = "❌ 回调失败"
|
||||
}
|
||||
if model.OrderStatusWaiting == o.Status {
|
||||
_notifyStateLabel = o.GetStatusLabel()
|
||||
}
|
||||
if model.OrderStatusExpired == o.Status {
|
||||
_notifyStateLabel = "🈚️ 没有回调"
|
||||
}
|
||||
|
||||
var tradeUnit = "USDT.TRC20"
|
||||
if o.TradeType == model.OrderTradeTypeTronTrx {
|
||||
tradeUnit = "TRX"
|
||||
}
|
||||
|
||||
var _site = &url.URL{Scheme: urlInfo.Scheme, Host: urlInfo.Host}
|
||||
var _msg = tgbotapi.NewMessage(0, "```"+`
|
||||
📌 订单ID:`+o.OrderId+`
|
||||
📊 交易汇率:`+o.TradeRate+`(`+config.GetUsdtRate()+`)
|
||||
💰 交易金额:`+fmt.Sprintf("%.2f", o.Money)+` CNY
|
||||
💲 交易数额:`+o.Amount+` `+tradeUnit+`
|
||||
🌏 商户网站:`+_site.String()+`
|
||||
🔋 收款状态:`+o.GetStatusLabel()+`
|
||||
🍀 回调状态:`+_notifyStateLabel+`
|
||||
💎️ 收款地址:`+help.MaskAddress(o.Address)+`
|
||||
🕒 创建时间:`+o.CreatedAt.Format(time.DateTime)+`
|
||||
🕒 失效时间:`+o.ExpiredAt.Format(time.DateTime)+`
|
||||
⚖️️ 确认时间:`+o.ConfirmedAt.Format(time.DateTime)+`
|
||||
`+"\n```")
|
||||
_msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
_msg.ReplyMarkup = tgbotapi.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]tgbotapi.InlineKeyboardButton{
|
||||
{
|
||||
tgbotapi.NewInlineKeyboardButtonURL("🌏商户网站", _site.String()),
|
||||
tgbotapi.NewInlineKeyboardButtonURL("📝交易明细", "https://tronscan.org/#/transaction/"+o.TradeHash),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
SendMsg(_msg)
|
||||
}
|
||||
}
|
||||
|
||||
func cbMarkNotifySuccAction(tradeId string) {
|
||||
|
||||
model.DB.Model(&model.TradeOrders{}).Where("trade_id = ?", tradeId).Update("notify_state", model.OrderNotifyStateSucc)
|
||||
|
||||
var msg = tgbotapi.NewMessage(0, fmt.Sprintf("✅订单(`%s`)回调状态手动标记成功,后续将不会再次回调。", tradeId))
|
||||
|
||||
msg.ParseMode = tgbotapi.ModeMarkdownV2
|
||||
|
||||
SendMsg(msg)
|
||||
}
|
||||
|
||||
func getTronWalletInfo(address string) string {
|
||||
var url = "https://apilist.tronscanapi.com/api/accountv2?address=" + address
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
log.Error("GetWalletInfoByAddress client.Get(url)", err)
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
log.Error("GetWalletInfoByAddress resp.StatusCode != 200", resp.StatusCode, err)
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Error("GetWalletInfoByAddress io.ReadAll(resp.Body)", err)
|
||||
|
||||
return ""
|
||||
}
|
||||
result := gjson.ParseBytes(all)
|
||||
|
||||
var dateCreated = time.UnixMilli(result.Get("date_created").Int())
|
||||
var latestOperationTime = time.UnixMilli(result.Get("latest_operation_time").Int())
|
||||
var netRemaining = result.Get("bandwidth.netRemaining").Int() + result.Get("bandwidth.freeNetRemaining").Int()
|
||||
var netLimit = result.Get("bandwidth.netLimit").Int() + result.Get("bandwidth.freeNetLimit").Int()
|
||||
var text = `
|
||||
☘️ 查询地址:` + address + `
|
||||
💰 TRX余额:0.00 TRX
|
||||
💲 USDT余额:0.00 USDT
|
||||
📬 交易数量:` + result.Get("totalTransactionCount").String() + `
|
||||
📈 转账数量:↑ ` + result.Get("transactions_out").String() + ` ↓ ` + result.Get("transactions_in").String() + `
|
||||
📡 宽带资源:` + fmt.Sprintf("%v", netRemaining) + ` / ` + fmt.Sprintf("%v", netLimit) + `
|
||||
🔋 能量资源:` + result.Get("bandwidth.energyRemaining").String() + ` / ` + result.Get("bandwidth.energyLimit").String() + `
|
||||
⏰ 创建时间:` + dateCreated.Format(time.DateTime) + `
|
||||
⏰ 最后活动:` + latestOperationTime.Format(time.DateTime) + `
|
||||
`
|
||||
|
||||
for _, v := range result.Get("withPriceTokens").Array() {
|
||||
if v.Get("tokenName").String() == "trx" {
|
||||
text = strings.Replace(text, "0.00 TRX", fmt.Sprintf("%.2f TRX", v.Get("balance").Float()/1000000), 1)
|
||||
}
|
||||
if v.Get("tokenName").String() == "Tether USD" {
|
||||
|
||||
text = strings.Replace(text, "0.00 USDT", fmt.Sprintf("%.2f USDT", v.Get("balance").Float()/1000000), 1)
|
||||
}
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
func getPolygonWallerInfo(address string) string {
|
||||
// TODO: 开发中...
|
||||
|
||||
return "开发中..."
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/rate"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cmdGetId = "id"
|
||||
const cmdStart = "start"
|
||||
const cmdState = "state"
|
||||
const cmdWallet = "wallet"
|
||||
const cmdOrder = "order"
|
||||
|
||||
const replayAddressText = "🚚 请发送一个合法的钱包地址"
|
||||
|
||||
func cmdGetIdHandle(_msg *tgbotapi.Message) {
|
||||
msg := tgbotapi.NewMessage(_msg.Chat.ID, "您的ID: "+fmt.Sprintf("`%v`(点击复制)", _msg.Chat.ID))
|
||||
msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
msg.ReplyToMessageID = _msg.MessageID
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
|
||||
func cmdStartHandle() {
|
||||
var msg = tgbotapi.NewMessage(0, "请点击钱包地址按照提示进行操作")
|
||||
var was []model.WalletAddress
|
||||
var inlineBtn [][]tgbotapi.InlineKeyboardButton
|
||||
if model.DB.Find(&was).Error == nil {
|
||||
for _, wa := range was {
|
||||
var _address = fmt.Sprintf("[✅已启用] %s", wa.Address)
|
||||
if wa.Status == model.StatusDisable {
|
||||
_address = fmt.Sprintf("[❌已禁用] %s", wa.Address)
|
||||
}
|
||||
|
||||
inlineBtn = append(inlineBtn, tgbotapi.NewInlineKeyboardRow(tgbotapi.NewInlineKeyboardButtonData(_address, fmt.Sprintf("%s|%v", cbAddress, wa.ID))))
|
||||
}
|
||||
}
|
||||
|
||||
inlineBtn = append(inlineBtn, tgbotapi.NewInlineKeyboardRow(tgbotapi.NewInlineKeyboardButtonData("👛 添加新的钱包地址", cbAddressAdd)))
|
||||
msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(inlineBtn...)
|
||||
|
||||
SendMsg(msg)
|
||||
}
|
||||
|
||||
func cmdStateHandle() {
|
||||
var rows []model.TradeOrders
|
||||
model.DB.Where("created_at > ?", time.Now().Format(time.DateOnly)).Find(&rows)
|
||||
var succ uint64
|
||||
var money float64
|
||||
for _, o := range rows {
|
||||
if o.Status == model.OrderStatusSuccess {
|
||||
succ++
|
||||
money += o.Money
|
||||
}
|
||||
}
|
||||
|
||||
var text = "```" + `
|
||||
🎁今日成功数量:%d
|
||||
💎今日订单总数:%d
|
||||
💰今日成功收款:%.2f
|
||||
🌟扫块成功数据:%s
|
||||
-----------------------
|
||||
🪧基准汇率(TRX):%v
|
||||
🪧基准汇率(USDT):%v
|
||||
✅订单汇率(TRX):%v
|
||||
✅订单汇率(USDT):%v
|
||||
-----------------------
|
||||
` + "```" + `
|
||||
>基准汇率:来源于交易所的原始数据。
|
||||
>订单汇率:订单创建过程中实际使用的汇率。
|
||||
>扫块成功数据:如果该值过低,说明您的服务器与区块链网络连接不稳定,请尝试更换区块节点。
|
||||
`
|
||||
var msg = tgbotapi.NewMessage(0, fmt.Sprintf(text,
|
||||
succ,
|
||||
len(rows),
|
||||
money,
|
||||
config.GetBlockScanSuccRate(),
|
||||
cast.ToString(rate.GetOkxTrxRawRate()),
|
||||
cast.ToString(rate.GetOkxUsdtRawRate()),
|
||||
cast.ToString(rate.GetTrxCalcRate(config.DefaultTrxCnyRate)),
|
||||
cast.ToString(rate.GetUsdtCalcRate(config.DefaultUsdtCnyRate)),
|
||||
))
|
||||
msg.ParseMode = tgbotapi.ModeMarkdownV2
|
||||
|
||||
SendMsg(msg)
|
||||
}
|
||||
|
||||
func cmdWalletHandle() {
|
||||
var msg = tgbotapi.NewMessage(0, "请选择需要查询的钱包地址")
|
||||
var was []model.WalletAddress
|
||||
var inlineBtn [][]tgbotapi.InlineKeyboardButton
|
||||
if model.DB.Find(&was).Error == nil {
|
||||
for _, wa := range was {
|
||||
var _address = fmt.Sprintf("[✅已启用] %s", wa.Address)
|
||||
if wa.Status == model.StatusDisable {
|
||||
_address = fmt.Sprintf("[❌已禁用] %s", wa.Address)
|
||||
}
|
||||
|
||||
inlineBtn = append(inlineBtn, tgbotapi.NewInlineKeyboardRow(tgbotapi.NewInlineKeyboardButtonData(_address, fmt.Sprintf("%s|%v", cbWallet, wa.Address))))
|
||||
}
|
||||
}
|
||||
|
||||
msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(inlineBtn...)
|
||||
|
||||
SendMsg(msg)
|
||||
}
|
||||
|
||||
func cmdOrderHandle() {
|
||||
var msg = tgbotapi.NewMessage(0, "*下面是最近的8个订单,点击可查看详细信息*\n```\n🟢 收款成功 🔴 交易过期 🟡 等待支付\n```")
|
||||
msg.ParseMode = tgbotapi.ModeMarkdown
|
||||
|
||||
var orders []model.TradeOrders
|
||||
var inlineBtn [][]tgbotapi.InlineKeyboardButton
|
||||
if model.DB.Order("id desc").Limit(8).Find(&orders).Error == nil {
|
||||
for _, order := range orders {
|
||||
var _state = "🟢"
|
||||
if order.Status == model.OrderStatusExpired {
|
||||
_state = "🔴"
|
||||
}
|
||||
if order.Status == model.OrderStatusWaiting {
|
||||
_state = "🟡"
|
||||
}
|
||||
|
||||
inlineBtn = append(inlineBtn, tgbotapi.NewInlineKeyboardRow(tgbotapi.NewInlineKeyboardButtonData(
|
||||
fmt.Sprintf("%s %s 💰%.2f", _state, order.OrderId, order.Money),
|
||||
fmt.Sprintf("%s|%v", cbOrderDetail, order.TradeId),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
msg.ReplyMarkup = tgbotapi.NewInlineKeyboardMarkup(inlineBtn...)
|
||||
|
||||
SendMsg(msg)
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
api "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func HandleMessage(msg *api.Message) {
|
||||
if msg.IsCommand() {
|
||||
botCommandHandle(msg)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if msg.ReplyToMessage != nil && msg.ReplyToMessage.Text == replayAddressText {
|
||||
|
||||
addWalletAddress(msg)
|
||||
}
|
||||
|
||||
if msg.Text != "" && help.IsValidTronAddress(msg.Text) {
|
||||
go queryTronAddressInfo(msg, msg.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func HandleCallback(query *api.CallbackQuery) {
|
||||
if fmt.Sprintf("%v", query.From.ID) != config.GetTGBotAdminId() {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var args []string
|
||||
var act = query.Data
|
||||
if strings.Contains(query.Data, "|") {
|
||||
args = strings.Split(query.Data, "|")
|
||||
act = args[0]
|
||||
}
|
||||
|
||||
switch act {
|
||||
case cbWallet:
|
||||
go cbWalletAction(query, args[1])
|
||||
case cbAddressAdd:
|
||||
go cbAddressAddHandle(query)
|
||||
case cbAddress:
|
||||
go cbAddressAction(query, args[1])
|
||||
case cbAddressEnable:
|
||||
go cbAddressEnableAction(query, args[1])
|
||||
case cbAddressDisable:
|
||||
go cbAddressDisableAction(query, args[1])
|
||||
case cbAddressDelete:
|
||||
go cbAddressDeleteAction(query, args[1])
|
||||
case cbAddressOtherNotify:
|
||||
go cbAddressOtherNotifyAction(query, args[1])
|
||||
case cbOrderDetail:
|
||||
go cbOrderDetailAction(args[1])
|
||||
case cbMarkNotifySucc:
|
||||
go cbMarkNotifySuccAction(args[1])
|
||||
}
|
||||
}
|
||||
|
||||
func addWalletAddress(msg *api.Message) {
|
||||
var address = strings.TrimSpace(msg.Text)
|
||||
// 简单检测地址是否合法
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidPolygonAddress(address) {
|
||||
SendMsg(api.NewMessage(msg.Chat.ID, "钱包地址不合法"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var chain = model.WaChainTron
|
||||
if help.IsValidPolygonAddress(address) {
|
||||
|
||||
chain = model.WaChainPolygon
|
||||
}
|
||||
|
||||
var wa = model.WalletAddress{Chain: chain, Address: address, Status: model.StatusEnable, OtherNotify: model.OtherNotifyEnable}
|
||||
var r = model.DB.Create(&wa)
|
||||
if r.Error != nil {
|
||||
if r.Error.Error() == "UNIQUE constraint failed: wallet_address.address" {
|
||||
SendMsg(api.NewMessage(msg.Chat.ID, "❌地址添加失败,地址重复!"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
SendMsg(api.NewMessage(msg.Chat.ID, "❌地址添加失败,错误信息:"+r.Error.Error()))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
SendMsg(api.NewMessage(msg.Chat.ID, "✅添加且成功启用"))
|
||||
cmdStartHandle()
|
||||
}
|
||||
|
||||
func botCommandHandle(msg *api.Message) {
|
||||
if msg.Command() == cmdGetId {
|
||||
|
||||
go cmdGetIdHandle(msg)
|
||||
}
|
||||
|
||||
if fmt.Sprintf("%v", msg.Chat.ID) != config.GetTGBotAdminId() {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
switch msg.Command() {
|
||||
case cmdStart:
|
||||
go cmdStartHandle()
|
||||
case cmdState:
|
||||
go cmdStateHandle()
|
||||
case cmdWallet:
|
||||
go cmdWalletHandle()
|
||||
case cmdOrder:
|
||||
go cmdOrderHandle()
|
||||
}
|
||||
}
|
||||
|
||||
func queryTronAddressInfo(msg *api.Message, address string) {
|
||||
var info = getTronWalletInfo(address)
|
||||
var reply = api.NewMessage(msg.Chat.ID, "❌查询失败")
|
||||
if info != "" {
|
||||
reply.ReplyToMessageID = msg.MessageID
|
||||
reply.Text = info
|
||||
reply.ReplyMarkup = api.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]api.InlineKeyboardButton{
|
||||
{
|
||||
api.NewInlineKeyboardButtonURL("📝查看详细信息", "https://tronscan.org/#/address/"+address),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
_, _ = botApi.Send(reply)
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
api "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func SendTradeSuccMsg(order model.TradeOrders) {
|
||||
var chatId, err = strconv.ParseInt(config.GetTgBotNotifyTarget(), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var url = fmt.Sprintf("https://tronscan.org/#/transaction/%s", order.TradeHash)
|
||||
|
||||
var tradeType = "USDT"
|
||||
var tradeUnit = `USDT.TRC20`
|
||||
if order.TradeType == model.OrderTradeTypeTronTrx {
|
||||
tradeType = "TRX"
|
||||
tradeUnit = "TRX"
|
||||
}
|
||||
if order.TradeType == model.OrderTradeTypeUsdtPolygon {
|
||||
tradeType = "USDT"
|
||||
tradeUnit = "USDT.Polygon"
|
||||
url = fmt.Sprintf("https://polygonscan.com/tx/%s", order.TradeHash)
|
||||
}
|
||||
|
||||
var text = `
|
||||
#收款成功 #订单交易 #` + tradeType + `
|
||||
---
|
||||
` + "```" + `
|
||||
🚦商户订单:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💲支付数额:%v ` + tradeUnit + `
|
||||
✅收款地址:%s
|
||||
⏱️创建时间:%s
|
||||
️🎯️支付时间:%s
|
||||
` + "```" + `
|
||||
`
|
||||
text = fmt.Sprintf(text,
|
||||
order.OrderId,
|
||||
order.Money,
|
||||
order.TradeRate,
|
||||
order.Amount,
|
||||
help.MaskAddress(order.Address),
|
||||
order.CreatedAt.Format(time.DateTime),
|
||||
order.UpdatedAt.Format(time.DateTime),
|
||||
)
|
||||
|
||||
var msg = api.NewMessage(chatId, text)
|
||||
msg.ParseMode = api.ModeMarkdown
|
||||
msg.ReplyMarkup = api.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]api.InlineKeyboardButton{
|
||||
{
|
||||
api.NewInlineKeyboardButtonURL("📝查看交易明细", url),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
|
||||
func SendNotifyFailed(o model.TradeOrders, reason string) {
|
||||
var chatId = cast.ToInt64(config.GetTgBotNotifyTarget())
|
||||
if err != nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var tradeType = "USDT"
|
||||
var tradeUnit = `USDT.TRC20`
|
||||
if o.TradeType == model.OrderTradeTypeTronTrx {
|
||||
tradeType = "TRX"
|
||||
tradeUnit = "TRX"
|
||||
}
|
||||
|
||||
var text = fmt.Sprintf(`
|
||||
#回调失败 #订单交易 #`+tradeType+`
|
||||
---
|
||||
`+"```"+`
|
||||
🚦商户订单:%v
|
||||
💰请求金额:%v CNY(%v)
|
||||
💲支付数额:%v %s
|
||||
⚖️️确认时间:%s
|
||||
⏰下次回调:%s
|
||||
🗒️失败原因:%s
|
||||
`+"```"+`
|
||||
`,
|
||||
help.Ec(o.OrderId),
|
||||
o.Money, o.TradeRate,
|
||||
o.Amount, tradeUnit,
|
||||
o.ConfirmedAt.Format(time.DateTime),
|
||||
help.CalcNextNotifyTime(o.ConfirmedAt, o.NotifyNum+1).Format(time.DateTime),
|
||||
reason,
|
||||
)
|
||||
|
||||
var msg = api.NewMessage(chatId, text)
|
||||
msg.ParseMode = api.ModeMarkdown
|
||||
msg.ReplyMarkup = api.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]api.InlineKeyboardButton{
|
||||
{
|
||||
api.NewInlineKeyboardButtonData("📝查看收款详情", fmt.Sprintf("%s|%v", cbOrderDetail, o.TradeId)),
|
||||
},
|
||||
{
|
||||
api.NewInlineKeyboardButtonData("✅标记回调成功", fmt.Sprintf("%s|%v", cbMarkNotifySucc, o.TradeId)),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
|
||||
func SendOtherNotify(text string) {
|
||||
var chatId, err = strconv.ParseInt(config.GetTgBotNotifyTarget(), 10, 64)
|
||||
if err != nil {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var msg = api.NewMessage(chatId, text)
|
||||
msg.ParseMode = api.ModeMarkdown
|
||||
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
|
||||
func SendWelcome(version string) {
|
||||
var text = `
|
||||
👋 欢迎使用 Bepusdt,一款更好用的个人USDT收款网关,如果您看到此消息,说明机器人已经启动成功!
|
||||
|
||||
📌当前版本:` + version + `
|
||||
📝发送命令 /start 可以开始使用
|
||||
🎉开源地址 https://github.com/v03413/bepusdt
|
||||
---
|
||||
`
|
||||
|
||||
SendMsg(api.NewMessage(0, text))
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var botApi *tgbotapi.BotAPI
|
||||
var err error
|
||||
|
||||
func init() {
|
||||
var token = config.GetTGBotToken()
|
||||
if token == "" {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
botApi, err = tgbotapi.NewBotAPI(token)
|
||||
if err != nil {
|
||||
panic("TG Bot NewBotAPI Error:" + err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 注册命令
|
||||
_, err = botApi.Request(tgbotapi.NewSetMyCommands([]tgbotapi.BotCommand{
|
||||
{Command: "/" + cmdGetId, Description: "获取ID"},
|
||||
{Command: "/" + cmdStart, Description: "开始使用"},
|
||||
{Command: "/" + cmdState, Description: "收款状态"},
|
||||
{Command: "/" + cmdWallet, Description: "钱包信息"},
|
||||
{Command: "/" + cmdOrder, Description: "最近订单"},
|
||||
}...))
|
||||
if err != nil {
|
||||
panic("TG Bot Request Error:" + err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("Bot UserName: ", botApi.Self.UserName)
|
||||
}
|
||||
|
||||
func GetBotApi() *tgbotapi.BotAPI {
|
||||
|
||||
return botApi
|
||||
}
|
||||
|
||||
func SendMsg(msg tgbotapi.MessageConfig) {
|
||||
if msg.ChatID != 0 {
|
||||
_, _ = botApi.Send(msg)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var chatId, err = strconv.ParseInt(config.GetTGBotAdminId(), 10, 64)
|
||||
if err == nil {
|
||||
msg.ChatID = chatId
|
||||
_, _ = botApi.Send(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func DeleteMsg(msgId int) {
|
||||
var chatId, err = strconv.ParseInt(config.GetTGBotAdminId(), 10, 64)
|
||||
if err == nil {
|
||||
_, _ = botApi.Send(tgbotapi.NewDeleteMessage(chatId, msgId))
|
||||
}
|
||||
}
|
||||
|
||||
func EditAndSendMsg(msgId int, text string, replyMarkup tgbotapi.InlineKeyboardMarkup) {
|
||||
var chatId, err = strconv.ParseInt(config.GetTGBotAdminId(), 10, 64)
|
||||
if err == nil {
|
||||
_, _ = botApi.Send(tgbotapi.NewEditMessageTextAndMarkup(chatId, msgId, text, replyMarkup))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package app
|
||||
|
||||
// Version 版本号说明 1.0.0 代表主版本号.功能版本号.修订号
|
||||
const Version = "1.17.1"
|
||||
const Version = "1.21.1"
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/epay"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/web/epay"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@@ -40,19 +40,30 @@ func epaySubmit(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if epay.Sign(data, config.GetAuthToken()) != data["sign"] {
|
||||
if epay.Sign(data, conf.GetAuthToken()) != data["sign"] {
|
||||
ctx.String(200, "签名错误")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var tradeType = model.OrderTradeTypeUsdtTrc20
|
||||
if data["type"] != tradeType {
|
||||
if v, ok := data["type"]; ok {
|
||||
|
||||
tradeType = model.OrderTradeTypeTronTrx
|
||||
tradeType = cast.ToString(v)
|
||||
}
|
||||
|
||||
var order, err = buildOrder(cast.ToFloat64(data["money"]), model.OrderApiTypeEpay, "", data["out_trade_no"], tradeType, data["return_url"], data["notify_url"], data["name"])
|
||||
var params = orderParams{
|
||||
Money: cast.ToFloat64(data["money"]),
|
||||
ApiType: model.OrderApiTypeEpay,
|
||||
PayAddress: "",
|
||||
OrderId: data["out_trade_no"],
|
||||
TradeType: tradeType,
|
||||
RedirectUrl: data["return_url"],
|
||||
NotifyUrl: data["notify_url"],
|
||||
Name: data["name"],
|
||||
}
|
||||
|
||||
var order, err = buildOrder(params)
|
||||
if err != nil {
|
||||
ctx.String(200, fmt.Sprintf("订单创建失败:%v", err))
|
||||
|
||||
@@ -65,5 +76,5 @@ func epaySubmit(ctx *gin.Context) {
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
ctx.Redirect(http.StatusFound, fmt.Sprintf("%s/pay/checkout-counter/%s", config.GetAppUri(host), order.TradeId))
|
||||
ctx.Redirect(http.StatusFound, fmt.Sprintf("%s/pay/checkout-counter/%s", conf.GetAppUri(host), order.TradeId))
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"net/url"
|
||||
@@ -43,7 +43,7 @@ func Sign(params map[string]string, key string) string {
|
||||
|
||||
func BuildNotifyParams(order model.TradeOrders) string {
|
||||
var sign = help.Md5String(fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(order.Money), order.Name, order.OrderId, Pid, order.TradeId, order.TradeType) + config.GetAuthToken())
|
||||
cast.ToString(order.Money), order.Name, order.OrderId, Pid, order.TradeId, order.TradeType) + conf.GetAuthToken())
|
||||
var params = fmt.Sprintf("money=%s&name=%s&out_trade_no=%s&pid=%s&trade_no=%s&trade_status=TRADE_SUCCESS&type=%s",
|
||||
cast.ToString(order.Money), url.QueryEscape(order.Name), url.QueryEscape(order.OrderId), Pid, order.TradeId, order.TradeType)
|
||||
|
||||
@@ -3,15 +3,16 @@ package web
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/epay"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"net/url"
|
||||
"time"
|
||||
"github.com/v03413/bepusdt/app/web/epay"
|
||||
)
|
||||
|
||||
func signVerify(ctx *gin.Context) {
|
||||
@@ -24,7 +25,7 @@ func signVerify(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var m = make(map[string]any)
|
||||
m := make(map[string]any)
|
||||
if err = json.Unmarshal(rawData, &m); err != nil {
|
||||
log.Error(err.Error())
|
||||
ctx.JSON(400, gin.H{"error": err.Error()})
|
||||
@@ -42,7 +43,7 @@ func signVerify(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if help.EpusdtSign(m, config.GetAuthToken()) != sign {
|
||||
if help.EpusdtSign(m, conf.GetAuthToken()) != sign {
|
||||
log.Warn("签名错误", m)
|
||||
ctx.JSON(400, gin.H{"error": "签名错误"})
|
||||
ctx.Abort()
|
||||
@@ -54,9 +55,9 @@ func signVerify(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
func createTransaction(ctx *gin.Context) {
|
||||
var data = ctx.GetStringMap("data")
|
||||
var tradeType = model.OrderTradeTypeUsdtTrc20
|
||||
var address = ""
|
||||
var address string
|
||||
data := ctx.GetStringMap("data")
|
||||
var timeout uint64 = 0
|
||||
for _, key := range []string{"order_id", "amount", "notify_url", "redirect_url"} {
|
||||
if _, ok := data[key]; !ok {
|
||||
log.Warn(fmt.Sprintf("参数 %s 不存在", key), data)
|
||||
@@ -66,13 +67,23 @@ func createTransaction(ctx *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
if v, ok := data["trade_type"]; ok {
|
||||
tradeType, ok := data["trade_type"]
|
||||
if !ok {
|
||||
tradeType = model.OrderTradeTypeUsdtTrc20 // 默认 USDT TRC20
|
||||
}
|
||||
|
||||
tradeType = model.GetTradeType(cast.ToString(v))
|
||||
if !help.InStrings(tradeType.(string), model.SupportTradeTypes) {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("交易类型(%s)不支持", tradeType)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if v, ok := data["timeout"]; ok {
|
||||
timeout = cast.ToUint64(v)
|
||||
}
|
||||
if v, ok := data["address"]; ok && cast.ToString(v) != "" {
|
||||
address = cast.ToString(v)
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidPolygonAddress(address) {
|
||||
if !help.IsValidTronAddress(address) && !help.IsValidEvmAddress(address) {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("收款钱包地址(%s)不合法", address)))
|
||||
|
||||
return
|
||||
@@ -80,18 +91,26 @@ func createTransaction(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// 解析请求地址
|
||||
var host = "http://" + ctx.Request.Host
|
||||
host := "http://" + ctx.Request.Host
|
||||
if ctx.Request.TLS != nil {
|
||||
|
||||
host = "https://" + ctx.Request.Host
|
||||
}
|
||||
|
||||
var amount = cast.ToFloat64(data["amount"])
|
||||
var orderId = cast.ToString(data["order_id"])
|
||||
var notifyUrl = cast.ToString(data["notify_url"])
|
||||
var redirectUrl = cast.ToString(data["redirect_url"])
|
||||
orderId := cast.ToString(data["order_id"])
|
||||
params := orderParams{
|
||||
Money: cast.ToFloat64(data["amount"]),
|
||||
ApiType: model.OrderApiTypeEpusdt,
|
||||
PayAddress: address,
|
||||
OrderId: orderId,
|
||||
TradeType: tradeType.(string),
|
||||
RedirectUrl: cast.ToString(data["redirect_url"]),
|
||||
NotifyUrl: cast.ToString(data["notify_url"]),
|
||||
Name: orderId,
|
||||
Timeout: timeout,
|
||||
Rate: cast.ToString(data["rate"]),
|
||||
}
|
||||
|
||||
var order, err = buildOrder(amount, model.OrderApiTypeEpusdt, address, orderId, tradeType, redirectUrl, notifyUrl, orderId)
|
||||
order, err := buildOrder(params)
|
||||
if err != nil {
|
||||
ctx.JSON(200, respFailJson(fmt.Sprintf("订单创建失败:%s", err.Error())))
|
||||
|
||||
@@ -101,18 +120,19 @@ func createTransaction(ctx *gin.Context) {
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, respSuccJson(gin.H{
|
||||
"trade_id": order.TradeId,
|
||||
"order_id": orderId,
|
||||
"amount": amount,
|
||||
"order_id": order.OrderId,
|
||||
"status": order.Status,
|
||||
"amount": order.Money,
|
||||
"actual_amount": order.Amount,
|
||||
"token": order.Address,
|
||||
"expiration_time": int64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": fmt.Sprintf("%s/pay/checkout-counter/%s", config.GetAppUri(host), order.TradeId),
|
||||
"expiration_time": uint64(order.ExpiredAt.Sub(time.Now()).Seconds()),
|
||||
"payment_url": fmt.Sprintf("%s/pay/checkout-counter/%s", conf.GetAppUri(host), order.TradeId),
|
||||
}))
|
||||
log.Info(fmt.Sprintf("订单创建成功,商户订单号:%s", orderId))
|
||||
}
|
||||
|
||||
func cancelTransaction(ctx *gin.Context) {
|
||||
var data = ctx.GetStringMap("data")
|
||||
data := ctx.GetStringMap("data")
|
||||
tradeId, ok := data["trade_id"].(string)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("参数 trade_id 不存在"))
|
||||
@@ -120,7 +140,7 @@ func cancelTransaction(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var order, ok2 = model.GetTradeOrder(tradeId)
|
||||
order, ok2 := model.GetTradeOrder(tradeId)
|
||||
if !ok2 {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
@@ -139,12 +159,14 @@ func cancelTransaction(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
model.PushWebhookEvent(model.WebhookEventOrderCancel, order)
|
||||
|
||||
ctx.JSON(200, respSuccJson(gin.H{"trade_id": tradeId}))
|
||||
}
|
||||
|
||||
func checkoutCounter(ctx *gin.Context) {
|
||||
var tradeId = ctx.Param("trade_id")
|
||||
var order, ok = model.GetTradeOrder(tradeId)
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.String(200, "订单不存在")
|
||||
|
||||
@@ -167,13 +189,14 @@ func checkoutCounter(ctx *gin.Context) {
|
||||
"return_url": order.ReturnUrl,
|
||||
"usdt_rate": order.TradeRate,
|
||||
"trade_id": tradeId,
|
||||
"order_id": order.OrderId,
|
||||
"trade_type": order.TradeType,
|
||||
})
|
||||
}
|
||||
|
||||
func checkStatus(ctx *gin.Context) {
|
||||
var tradeId = ctx.Param("trade_id")
|
||||
var order, ok = model.GetTradeOrder(tradeId)
|
||||
tradeId := ctx.Param("trade_id")
|
||||
order, ok := model.GetTradeOrder(tradeId)
|
||||
if !ok {
|
||||
ctx.JSON(200, respFailJson("订单不存在"))
|
||||
|
||||
@@ -190,5 +213,10 @@ func checkStatus(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// 返回响应数据
|
||||
ctx.JSON(200, gin.H{"trade_id": tradeId, "status": order.Status, "return_url": returnUrl})
|
||||
ctx.JSON(200, gin.H{
|
||||
"trade_id": tradeId,
|
||||
"trade_hash": order.TradeHash,
|
||||
"status": order.Status,
|
||||
"return_url": returnUrl,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/bot"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
e "github.com/v03413/bepusdt/app/web/epay"
|
||||
"github.com/v03413/go-cache"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type EpNotify struct {
|
||||
TradeId string `json:"trade_id"` // 本地订单号
|
||||
OrderId string `json:"order_id"` // 客户交易id
|
||||
Amount float64 `json:"amount"` // 订单金额 CNY
|
||||
ActualAmount string `json:"actual_amount"` // USDT 交易数额
|
||||
Token string `json:"token"` // 收款钱包地址
|
||||
BlockTransactionId string `json:"block_transaction_id"` // 区块id
|
||||
Signature string `json:"signature"` // 签名
|
||||
Status int `json:"status"` // 1:等待支付,2:支付成功,3:订单超时
|
||||
}
|
||||
|
||||
func Handle(order model.TradeOrders) {
|
||||
if order.ApiType == model.OrderApiTypeEpay {
|
||||
epay(order)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
epusdt(order)
|
||||
}
|
||||
|
||||
func epay(order model.TradeOrders) {
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var notifyUrl = fmt.Sprintf("%s?%s", order.NotifyUrl, e.BuildNotifyParams(order))
|
||||
|
||||
postReq, err2 := http.NewRequest("GET", notifyUrl, nil)
|
||||
if err2 != nil {
|
||||
log.Error("Notify NewRequest Error:", err2)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
log.Error("Notify Handle Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
markNotifyFail(order, fmt.Sprintf("resp.StatusCode != 200"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
markNotifyFail(order, fmt.Sprintf("io.ReadAll(resp.Body) Error: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 判断是否包含 success
|
||||
if !strings.Contains(strings.ToLower(string(all)), "success") {
|
||||
markNotifyFail(order, fmt.Sprintf("body not contains success (%s)", string(all)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = order.SetNotifyState(model.OrderNotifyStateSucc)
|
||||
if err != nil {
|
||||
log.Error("订单标记通知成功错误:", err, order.OrderId)
|
||||
} else {
|
||||
log.Info("订单通知成功:", order.OrderId)
|
||||
}
|
||||
}
|
||||
|
||||
func epusdt(order model.TradeOrders) {
|
||||
var data = make(map[string]interface{})
|
||||
var body = EpNotify{
|
||||
TradeId: order.TradeId,
|
||||
OrderId: order.OrderId,
|
||||
Amount: order.Money,
|
||||
ActualAmount: order.Amount,
|
||||
Token: order.Address,
|
||||
BlockTransactionId: order.TradeHash,
|
||||
Status: order.Status,
|
||||
}
|
||||
var jsonBody, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
log.Error("Notify Json Marshal Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(jsonBody, &data); err != nil {
|
||||
log.Error("Notify JSON Unmarshal Error:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// 签名
|
||||
body.Signature = help.EpusdtSign(data, conf.GetAuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, err = json.Marshal(body)
|
||||
var client = http.Client{Timeout: time.Second * 5}
|
||||
var postReq, err2 = http.NewRequest("POST", order.NotifyUrl, strings.NewReader(string(jsonBody)))
|
||||
if err2 != nil {
|
||||
markNotifyFail(order, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
postReq.Header.Set("Content-Type", "application/json")
|
||||
postReq.Header.Set("Powered-By", "https://github.com/v03413/bepusdt")
|
||||
postReq.Header.Set("User-Agent", "BEpusdt/"+app.Version)
|
||||
resp, err := client.Do(postReq)
|
||||
if err != nil {
|
||||
markNotifyFail(order, err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
markNotifyFail(order, fmt.Sprintf("resp.StatusCode != 200"))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
all, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
markNotifyFail(order, fmt.Sprintf("io.ReadAll(resp.Body) Error: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if string(all) != "ok" {
|
||||
markNotifyFail(order, fmt.Sprintf("body != ok (%s)", string(all)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = order.SetNotifyState(model.OrderNotifyStateSucc)
|
||||
if err != nil {
|
||||
log.Error("订单标记通知成功错误:", err, order.OrderId)
|
||||
} else {
|
||||
log.Info("订单通知成功:", order.OrderId)
|
||||
}
|
||||
}
|
||||
|
||||
func Bepusdt(order model.TradeOrders) {
|
||||
if order.ApiType != model.OrderApiTypeEpusdt {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var todo = func() error {
|
||||
var o model.TradeOrders
|
||||
var db = model.DB.Begin()
|
||||
if err := db.Where("trade_id = ? and status = ?", order.TradeId, order.Status).First(&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: o.Money,
|
||||
ActualAmount: o.Amount,
|
||||
Token: o.Address,
|
||||
BlockTransactionId: o.TradeHash,
|
||||
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 = help.EpusdtSign(data, conf.GetAuthToken())
|
||||
|
||||
// 再次序列化
|
||||
jsonBody, err = 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 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 {
|
||||
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", order.Status, o.TradeId, string(all)))
|
||||
|
||||
db.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
go func() {
|
||||
if err := todo(); err != nil {
|
||||
log.Warn("notify Bepusdt Error:", err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func markNotifyFail(order model.TradeOrders, reason string) {
|
||||
log.Warn(fmt.Sprintf("订单回调失败(%v):%s %v", order.TradeId, reason, order.SetNotifyState(model.OrderNotifyStateFail)))
|
||||
go func() {
|
||||
bot.SendNotifyFailed(order, reason)
|
||||
}()
|
||||
}
|
||||
@@ -2,72 +2,104 @@ package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/help"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/rate"
|
||||
"sync"
|
||||
"time"
|
||||
"github.com/v03413/bepusdt/app/task/rate"
|
||||
)
|
||||
|
||||
func buildOrder(money float64, apiType, payAddress, orderId, tradeType, redirectUrl, notifyUrl, name string) (model.TradeOrders, error) {
|
||||
type orderParams struct {
|
||||
Money float64 `json:"money"` // 交易金额 CNY
|
||||
ApiType string `json:"api_type"` // 支付API类型
|
||||
PayAddress string `json:"pay_address"` // 收款地址
|
||||
OrderId string `json:"order_id"` // 商户订单ID
|
||||
TradeType string `json:"trade_type"` // 交易类型
|
||||
RedirectUrl string `json:"redirect_url"` // 成功跳转地址
|
||||
NotifyUrl string `json:"notify_url"` // 异步通知地址
|
||||
Name string `json:"name"` // 商品名称
|
||||
Timeout uint64 `json:"timeout"` // 订单超时时间(秒)
|
||||
Rate string `json:"rate"` // 强制指定汇率
|
||||
}
|
||||
|
||||
func buildOrder(p orderParams) (model.TradeOrders, error) {
|
||||
var lock sync.Mutex
|
||||
var order model.TradeOrders
|
||||
|
||||
model.DB.Where("order_id = ?", p.OrderId).Find(&order)
|
||||
if order.Status == model.OrderStatusWaiting || order.Status == model.OrderStatusSuccess {
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// 暂时先强制使用互斥锁,后续有需求的话再考虑优化
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
// 获取兑换汇率
|
||||
var calcRate = rate.GetUsdtCalcRate(config.DefaultUsdtCnyRate)
|
||||
if tradeType == model.OrderTradeTypeTronTrx {
|
||||
|
||||
calcRate = rate.GetTrxCalcRate(config.DefaultTrxCnyRate)
|
||||
var calcRate float64
|
||||
if p.Rate != "" {
|
||||
rawRate := rate.GetOkxUsdtRawRate()
|
||||
if p.TradeType == model.OrderTradeTypeTronTrx {
|
||||
rawRate = rate.GetOkxTrxRawRate()
|
||||
}
|
||||
calcRate = rate.ParseFloatRate(p.Rate, rawRate)
|
||||
} else {
|
||||
calcRate = rate.GetUsdtCalcRate()
|
||||
if p.TradeType == model.OrderTradeTypeTronTrx {
|
||||
calcRate = rate.GetTrxCalcRate()
|
||||
}
|
||||
}
|
||||
|
||||
// 获取钱包地址
|
||||
var wallet = model.GetAvailableAddress(payAddress, tradeType)
|
||||
wallet := model.GetAvailableAddress(p.PayAddress, p.TradeType)
|
||||
if len(wallet) == 0 {
|
||||
log.Error("订单创建失败:还没有配置收款地址")
|
||||
|
||||
return order, fmt.Errorf("还没有配置收款地址")
|
||||
return order, fmt.Errorf(fmt.Sprintf("类型(%s)没检测到可用收款地址", p.TradeType))
|
||||
}
|
||||
|
||||
// 计算交易金额
|
||||
address, amount := model.CalcTradeAmount(wallet, calcRate, money, tradeType)
|
||||
address, amount := model.CalcTradeAmount(wallet, calcRate, p.Money, p.TradeType)
|
||||
tradeId, err := help.GenerateTradeId()
|
||||
if err != nil {
|
||||
|
||||
return order, err
|
||||
}
|
||||
|
||||
// 超时处理
|
||||
timeout := conf.GetExpireTime() * time.Second
|
||||
if p.Timeout >= 60 { // 至少60秒
|
||||
|
||||
timeout = time.Duration(p.Timeout) * time.Second
|
||||
}
|
||||
|
||||
// 创建交易订单
|
||||
var expiredAt = time.Now().Add(config.GetExpireTime() * time.Second)
|
||||
var tradeOrder = model.TradeOrders{
|
||||
OrderId: orderId,
|
||||
expiredAt := time.Now().Add(timeout)
|
||||
tradeOrder := model.TradeOrders{
|
||||
OrderId: p.OrderId,
|
||||
TradeId: tradeId,
|
||||
TradeHash: tradeId, // 这里默认填充一个本地交易ID,等支付成功后再更新为实际交易哈希
|
||||
TradeType: tradeType,
|
||||
TradeType: p.TradeType,
|
||||
TradeRate: fmt.Sprintf("%v", calcRate),
|
||||
Amount: amount,
|
||||
Money: money,
|
||||
Money: p.Money,
|
||||
Address: address.Address,
|
||||
Status: model.OrderStatusWaiting,
|
||||
Name: name,
|
||||
ApiType: apiType,
|
||||
ReturnUrl: redirectUrl,
|
||||
NotifyUrl: notifyUrl,
|
||||
Name: p.Name,
|
||||
ApiType: p.ApiType,
|
||||
ReturnUrl: p.RedirectUrl,
|
||||
NotifyUrl: p.NotifyUrl,
|
||||
NotifyNum: 0,
|
||||
NotifyState: model.OrderNotifyStateFail,
|
||||
ExpiredAt: expiredAt,
|
||||
}
|
||||
var res = model.DB.Create(&tradeOrder)
|
||||
if res.Error != nil {
|
||||
log.Error("订单创建失败:", res.Error.Error())
|
||||
if err = model.DB.Create(&tradeOrder).Error; err != nil {
|
||||
log.Error("订单创建失败:", err.Error())
|
||||
|
||||
return order, res.Error
|
||||
return order, err
|
||||
}
|
||||
|
||||
model.PushWebhookEvent(model.WebhookEventOrderCreate, tradeOrder)
|
||||
|
||||
return tradeOrder, nil
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package web
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/static"
|
||||
"html/template"
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
func Start() {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
var listen = config.GetListen()
|
||||
var listen = conf.GetListen()
|
||||
var engine = loadStatic(gin.New())
|
||||
|
||||
{
|
||||
@@ -57,12 +57,12 @@ func Start() {
|
||||
|
||||
// 加载静态资源
|
||||
func loadStatic(engine *gin.Engine) *gin.Engine {
|
||||
var staticPath = config.GetStaticPath()
|
||||
var staticPath = conf.GetStaticPath()
|
||||
if staticPath != "" {
|
||||
engine.Static("/img", config.GetStaticPath()+"/img")
|
||||
engine.Static("/css", config.GetStaticPath()+"/css")
|
||||
engine.Static("/js", config.GetStaticPath()+"/js")
|
||||
engine.LoadHTMLGlob(config.GetStaticPath() + "/views/*")
|
||||
engine.Static("/img", conf.GetStaticPath()+"/img")
|
||||
engine.Static("/css", conf.GetStaticPath()+"/css")
|
||||
engine.Static("/js", conf.GetStaticPath()+"/js")
|
||||
engine.LoadHTMLGlob(conf.GetStaticPath() + "/views/*")
|
||||
|
||||
return engine
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# 应用访问地址,留空则系统自动获取,前端收银台会用到,建议设置,例如:https://token-pay.example.com
|
||||
app_uri = ""
|
||||
# 认证Token,对接会用到这个参数【很重要建议修改】
|
||||
auth_token = "123234"
|
||||
# 服务器HTTP监听地址
|
||||
listen = ":8080"
|
||||
# 静态资源路径,例如:/root/bepusdt/static;通过此参数可自定义模板,参考static目录,如非必要不建议修改。
|
||||
static_path = ""
|
||||
# SQLite数据库路径
|
||||
sqlite_path = "/var/lib/bepusdt/sqlite.db"
|
||||
# Tron网络GRPC节点,可选列表:https://developers.tron.network/docs/networks#public-node
|
||||
tron_grpc_node = "18.141.79.38:50051"
|
||||
# 日志输出路径
|
||||
output_log = "/var/log/bepusdt.log"
|
||||
# Webhook地址,留空则不弃用
|
||||
webhook_url = ""
|
||||
|
||||
[pay]
|
||||
# usdt 支付原子颗粒度,0.01表示支付数额保留两位小数,相同金额时递增颗粒度为0.01,依次类推,如无特殊需求不建议修改。
|
||||
usdt_atom = 0.01
|
||||
# USDT汇率,默认留空则获取Okx交易所的汇率(分钟/次,失败则取6.4);支持多种写法,如:7.4表示固定7.4、~1.02表示最新汇率上浮2%、~0.97表示最新汇率下浮3%、+0.3表示最新加0.3、-0.2表示最新减0.2
|
||||
usdt_rate = "~0.98"
|
||||
# 同上,TRX支付原子颗粒度
|
||||
trx_atom = 0.01
|
||||
# 同上,TRX汇率
|
||||
trx_rate = "~0.95"
|
||||
# 交易过期时间,单位秒,如无特殊需求不建议修改。
|
||||
expire_time = 1200
|
||||
# 启动时需要添加的钱包地址,多个请用半角符逗号,分开;当然,同样也支持通过机器人添加。
|
||||
wallet_address = [
|
||||
# 写法举例: 币种:地址
|
||||
# "tron.trx:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
# "usdt.trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
# "usdt.bep20:0x55d398326f99059ff775485246999027b3197955",
|
||||
]
|
||||
# 是否需要网络确认,禁用可以提高回调速度,启用则可以防止交易失败
|
||||
trade_is_confirmed = false
|
||||
# 支付监控的允许数额范围(闭区间),设置合理数值可避免一些诱导式诈骗交易提醒
|
||||
payment_amount_min = 0.01
|
||||
payment_amount_max = 99999
|
||||
|
||||
[evm_rpc]
|
||||
bsc = "https://bsc-dataseed.bnbchain.org/"
|
||||
xlayer = "https://xlayerrpc.okx.com/"
|
||||
polygon = "https://polygon-rpc.com/"
|
||||
ethereum = "https://ethereum.publicnode.com/"
|
||||
|
||||
[bot]
|
||||
# Telegram Bot 管理员ID,必须设置,否则无法使用
|
||||
admin_id = 123456
|
||||
# Telegram 群组ID,设置之后机器人会将交易消息会推送到此群
|
||||
group_id = ""
|
||||
# Telegram Bot Token,必须设置,否则无法使用
|
||||
token = ""
|
||||
@@ -0,0 +1,18 @@
|
||||
# 这是一个简化配置文件参考,按此配置文件调整足以满足大部分需求
|
||||
app_uri = "https://coin.example.com"
|
||||
auth_token = "123234zxc"
|
||||
listen = ":8080"
|
||||
|
||||
[pay]
|
||||
usdt_rate = "~0.98"
|
||||
trx_rate = "~0.95"
|
||||
expire_time = 1200
|
||||
wallet_address = [
|
||||
# "交易类型:地址",
|
||||
# "tron.trx:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
# "usdt.trc20:TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
# "usdt.bep20:0x55d398326f99059ff775485246999027b3197955",
|
||||
]
|
||||
[bot]
|
||||
admin_id = 1888888888
|
||||
token = "6888888888:ANGR7LHYm_EAttj9FTq3LtlAa-Nrh4tdNZ8"
|
||||
@@ -0,0 +1,10 @@
|
||||
services:
|
||||
bepusdt:
|
||||
image: v03413/bepusdt:latest # 如果想使用最新的开发版本,可以将镜像名 latest 替换为 beta
|
||||
container_name: bepusdt
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- ./conf.toml:/usr/local/bepusdt/conf.toml
|
||||
- ./data:/var/lib/bepusdt
|
||||
@@ -1,9 +0,0 @@
|
||||
EXPIRE_TIME=600
|
||||
USDT_RATE=
|
||||
AUTH_TOKEN=123234
|
||||
LISTEN=:8080
|
||||
TRADE_IS_CONFIRMED=0
|
||||
APP_URI=
|
||||
WALLET_ADDRESS=
|
||||
TG_BOT_TOKEN=
|
||||
TG_BOT_ADMIN_ID=
|
||||
@@ -0,0 +1,154 @@
|
||||
## 📚 接口文档
|
||||
|
||||
<details>
|
||||
<summary>创建订单</summary>
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/create-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 可根据实际情况传入收款地址,亦可留空
|
||||
"trade_type": "usdt.trc20", // usdt.trc20(默认) tron.trx 可选列表 https://github.com/v03413/bepusdt/blob/16d8df2cc5acc3d41c1c014ecb5370bd97f7e955/app/model/orders.go#L25:L30
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": 28.88, // 请求支付金额,CNY
|
||||
"signature":"123456abcd", // 签名
|
||||
"notify_url": "https://example.com/callback", // 回调地址
|
||||
"redirect_url": "https://example.com/callback", // 支付成功跳转地址
|
||||
"timeout": 1200, // 超时时间(秒) 最低60;留空则取配置文件 expire_time,还是没有取默认600
|
||||
"rate": 7.4 // 强制指定汇率,留空则取配置汇率;支持多种写法,如:7.4表示固定7.4、~1.02表示最新汇率上浮2%、~0.97表示最新汇率下浮3%、+0.3表示最新加0.3、-0.2表示最新减0.2
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"status_code": 200,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415", // 本地交易ID
|
||||
"order_id": "787240927112940881", // 商户订单编号
|
||||
"amount": "28.88", // 请求支付金额,CNY
|
||||
"actual_amount": "10", // 实际支付数额 usdt or trx
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", // 收款地址
|
||||
"expiration_time": 1200, // 订单有效期,秒
|
||||
"payment_url": "https://example.com//pay/checkout-counter/b3d2477c-d945-41da-96b7-f925bbd1b415" // 收银台地址
|
||||
},
|
||||
"request_id": ""
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>取消订单</summary>
|
||||
|
||||
商户端系统可以通过此接口取消订单,取消后,系统将不再监控此订单,同时释放对应金额占用。
|
||||
|
||||
### 请求地址
|
||||
|
||||
```http
|
||||
POST /api/v1/order/cancel-transaction
|
||||
```
|
||||
|
||||
### 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ", // 交易ID
|
||||
"signature":"123456abcd" // 签名内容
|
||||
}
|
||||
```
|
||||
|
||||
### 响应内容
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"trade_id": "0TJV0br98YbNTQe7nQ"
|
||||
},
|
||||
"message": "success",
|
||||
"request_id": "",
|
||||
"status_code": 200
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>回调通知</summary>
|
||||
|
||||
```json
|
||||
{
|
||||
"trade_id": "b3d2477c-d945-41da-96b7-f925bbd1b415",
|
||||
"order_id": "787240927112940881",
|
||||
"amount": 28.88,
|
||||
"actual_amount": 10,
|
||||
"token": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
|
||||
"block_transaction_id": "12ef6267b42e43959795cf31808d0cc72b3d0a48953ed19c61d4b6665a341d10",
|
||||
"signature": "123456abcd",
|
||||
"status": 2 // 1:等待支付 2:支付成功 3:支付超时
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 签名算法
|
||||
|
||||
签名生成的通用步骤如下:
|
||||
|
||||
第一步,将所有非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成
|
||||
`待加密参数`。
|
||||
|
||||
重要规则:
|
||||
◆ 参数名ASCII码从小到大排序(字典序);
|
||||
◆ 如果参数的值为空不参与签名;
|
||||
◆ 参数名区分大小写;
|
||||
第二步,`待加密参数`最后拼接上`api接口认证token`得到`待签名字符串`,并对`待签名字符串`进行MD5运算,再将得到的`MD5字符串`
|
||||
所有字符转换为`小写`,得到签名`signature`。 注意:`signature`的长度为32个字节。
|
||||
|
||||
举例:
|
||||
|
||||
假设传送的参数如下:
|
||||
|
||||
```
|
||||
order_id : 20220201030210321
|
||||
amount : 42
|
||||
notify_url : http://example.com/notify
|
||||
redirect_url : http://example.com/redirect
|
||||
```
|
||||
|
||||
假设api接口认证token为:`epusdt_password_xasddawqe`(api接口认证token可以在`conf.toml`文件设置)
|
||||
|
||||
第一步:对参数按照key=value的格式,并按照参数名ASCII字典序排序如下:
|
||||
|
||||
```
|
||||
amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirect
|
||||
```
|
||||
|
||||
第二步:拼接API密钥并加密:
|
||||
|
||||
```
|
||||
MD5(amount=42¬ify_url=http://example.com/notify&order_id=20220201030210321&redirect_url=http://example.com/redirectepusdt_password_xasddawqe)
|
||||
```
|
||||
|
||||
最终得到最终发送的数据:
|
||||
|
||||
```
|
||||
order_id : 20220201030210321
|
||||
amount : 42
|
||||
notify_url : http://example.com/notify
|
||||
redirect_url : http://example.com/redirect
|
||||
signature : 1cd4b52df5587cfb1968b0c0c6e156cd
|
||||
```
|
||||
|
||||
## 参考引用
|
||||
|
||||
- https://github.com/assimon/epusdt/blob/master/wiki/API.md
|
||||
@@ -5,8 +5,7 @@ After=network.target nss-lookup.target
|
||||
|
||||
[Service]
|
||||
Type = simple
|
||||
EnvironmentFile=/usr/local/bepusdt/Environment.conf
|
||||
ExecStart=/usr/local/bepusdt/bepusdt
|
||||
ExecStart=/usr/local/bin/bepusdt -conf /usr/local/bepusdt/conf.toml
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
|
||||
@@ -1,16 +1,63 @@
|
||||
# Docker安装教程
|
||||
# Docker 部署教程
|
||||
|
||||
保证你的服务器已经安装了`Docker`和`Docker Compose`,如果没有请自行安装。
|
||||
## 准备工作
|
||||
|
||||
直接执行命令,注意下面的参数需要修改为你自己合适的参数,按照相同的格式进行修改。
|
||||
1. **安装 Docker:** 确保服务器已经安装 Docker,这里不阐述安装细节。
|
||||
2. **准备配置文件:**
|
||||
通过这个链接下载示例配置文件:[conf.example.toml](https://github.com/v03413/bepusdt/blob/main/conf.example.toml)
|
||||
下载后,请按照实际需求编辑文件,如果不清楚参数含义请勿修改!
|
||||
3. **推荐服务器:** 推荐使用新加坡服务器(Debian11+),性能无硬性要求,主要确保网络通畅;
|
||||
推荐尽量知名厂商(例如:Aws Gcp Digitalocean 等),一方面安全更有保障,其次一些私人VPS总是出现一些奇奇怪怪的问题!
|
||||
|
||||
## 部署命令
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always \
|
||||
docker run -d --restart=unless-stopped \
|
||||
-p 8080:8080 \
|
||||
-e TG_BOT_TOKEN=6361745888:AAFaX_T9XLe4hvF7vRLf1dvolQcuAkw6888 \
|
||||
-e TG_BOT_ADMIN_ID=1641035888 \
|
||||
-e USDT_RATE=~0.98 \
|
||||
-v [配置文件路径]:/usr/local/bepusdt/conf.toml \
|
||||
v03413/bepusdt:latest
|
||||
```
|
||||
|
||||
执行成功后,访问`http://你的服务器IP:8080`如果能正常打开,则安装成功,你就可以使用机器人添加钱包地址了。
|
||||
### 说明:
|
||||
|
||||
- 请将 `[配置文件路径]` 替换为你的配置文件的实际存放路径。
|
||||
- `-p 8080:8080` 表示将容器的 8080 端口映射到宿主机的 8080 端口,使得应用可以通过宿主机的端口访问。
|
||||
- `--restart=unless-stopped` 确保你的容器在遇到问题时可以自动重启。
|
||||
|
||||
版本说明:`v03413/bepusdt:latest` 为最新发行版镜像,`v03413/bepusdt:nightly`为每日构建的开发版。
|
||||
|
||||
## 验证部署
|
||||
|
||||
部署完成后,你的 Telegram 机器人会收到一条通知消息,说明应用已经启动。你可以通过访问 `http://[你的IP]:8080` 来检查应用是否正常运行。
|
||||
|
||||
## 数据持久化(可选)
|
||||
|
||||
如果你想保存应用数据,确保在配置文件中设置了数据库的路径:
|
||||
|
||||
```toml
|
||||
sqlite_path = "你的数据库文件路径"
|
||||
```
|
||||
|
||||
然后在运行 Docker 命令时,将数据库文件路径映射到宿主机,例如:
|
||||
|
||||
```bash
|
||||
-v 你的数据库文件路径:/var/lib/bepusdt/sqlite.db
|
||||
```
|
||||
|
||||
这样即使容器重新启动或删除,数据也不会丢失。
|
||||
|
||||
## Docker Compose 方式部署
|
||||
|
||||
```yml
|
||||
services:
|
||||
bepusdt:
|
||||
image: v03413/bepusdt:latest
|
||||
container_name: bepusdt
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- ./conf.toml:/usr/local/bepusdt/conf.toml
|
||||
- ./data:/var/lib/bepusdt
|
||||
```
|
||||
|
||||
|
||||
@@ -1,14 +1,29 @@
|
||||
# 独角数卡对接教程
|
||||
|
||||
确保`Bepusdt`已经安装成功,独角数卡后台原生支持对接,按照以下图片格式填写:
|
||||
由于新版`BEpusdt`开始支持不同区块链的USDT、超时回调等新特性,独角自带的`Epusdt`插件已经不再适配,无法直接使用,必须对原有插件进行替换。
|
||||
|
||||
- ‼️重要的事情说三遍,独角自带的`Epusdt`插件无法直接使用,使用必出问题!
|
||||
- ‼️重要的事情说三遍,独角自带的`Epusdt`插件无法直接使用,使用必出问题!
|
||||
- ‼️重要的事情说三遍,独角自带的`Epusdt`插件无法直接使用,使用必出问题!
|
||||
|
||||
因此我对独角数卡进行了适配调整,并对原项目发起了[PR](https://github.com/assimon/dujiaoka/pull/424),只能希望独角能尽快合并吧。
|
||||
|
||||
---
|
||||
|
||||
当你看到这篇文章时,我不确定PR是否已经合并,所以你最好下载此文件 [EpusdtController.php](https://raw.githubusercontent.com/v03413/dujiaoka/refs/heads/master/app/Http/Controllers/Pay/EpusdtController.php)
|
||||
然后在你安装好的独角数卡网站目录`app/Http/Controllers/Pay/`替换原有的同名文件。
|
||||
|
||||
确保`BEpusdt`已经安装成功,独角数卡后台支付对接按照以下图片格式填写:
|
||||
> 独角后台 -> 支付配置 -> 新增
|
||||
>
|
||||

|
||||
|
||||
**重点说下几个参数:**
|
||||
|
||||
- 商户ID:搭建`Bepusdt`时候的参数`AUTH_TOKEN`
|
||||
- 商户ID:搭建`BEpusdt`时候的参数`AUTH_TOKEN`
|
||||
- 支付标识:即收款交易类型,可选`tron.trx usdt.trc20 usdt.erc20`
|
||||
等,[可选列表参考](https://github.com/v03413/BEpusdt/blob/62758f24689a81853a215d122a6012bac8364a82/app/model/orders.go#L25:L30)!
|
||||
- 商户密钥:固定格式为`https://token.pay.com/api/v1/order/create-transaction` ,域名请自行替换
|
||||
- 支付处理路由:固定填写`/pay/epusdt`
|
||||
- 支付处理路由:固定填写`pay/epusdt`
|
||||
|
||||
其它参数按照实际情况填写保存,即可完成对接。
|
||||
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 125 KiB |
@@ -1,44 +0,0 @@
|
||||
# 彩虹易支付对接教程
|
||||
|
||||
从版本号`v1.14.0`开始,Bepusdt开始原生支持易支付对接,没有三方插件依赖,可直接对接使用;目前网上流传的易支付改版很多,可能做不到100%兼容,有问题可以issue反馈。
|
||||
|
||||
本教程测试的易支付版本号,如下:
|
||||
|
||||

|
||||
|
||||
其它版本的易支付,可能会有一些不同,但是大体上是一样。
|
||||
|
||||
## 对接教程
|
||||
|
||||
### 1. 增加支付方式
|
||||
|
||||
找到易支付自带的原生插件文件,增加两种支付方式 `tron.trx`和`usdt.trc20`,照着下图改。
|
||||
|
||||

|
||||
|
||||
改外后回到后台,支付插件刷新,找到易支付插件,确保支付方式添加成功,如图:
|
||||

|
||||
|
||||
增加支付方式:`后台` -> `支付方式` -> `新增`,必须确保`调用值`与下图完全一致:
|
||||
|
||||

|
||||
|
||||
如果保存提示`调用值不符合规则`,请找到下图文件的两行代码临时注释掉,保存后再取消注释即可。
|
||||
|
||||

|
||||
|
||||
### 2. 增加支付通道
|
||||
|
||||
`后台` -> `支付通道` -> `新增`,参考如图:
|
||||
|
||||

|
||||
|
||||
支付方式选择刚才添加的其中一种,插件选择彩虹易支付,其它参数自行调整,最后保存。
|
||||
|
||||
配置密钥,如图,按照自己的情况填写:
|
||||
|
||||

|
||||
|
||||
最后保存,然后就可以开始测试是否可以正常支付了。
|
||||
|
||||
---
|
||||
|
Before Width: | Height: | Size: 137 KiB |
|
Before Width: | Height: | Size: 326 KiB |
|
Before Width: | Height: | Size: 143 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 83 KiB |
|
Before Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 838 KiB |
@@ -1,9 +1,14 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
|
||||
return [
|
||||
'alipay' => '支付宝',
|
||||
'wxpay' => '微信',
|
||||
'qqpay' => 'QQ钱包',
|
||||
'usdt.trc20' => 'USDT.TRC20',
|
||||
'tron.trx' => 'TRON.TRX',
|
||||
'alipay' => '支付宝',
|
||||
'wxpay' => '微信',
|
||||
'qqpay' => 'QQ钱包',
|
||||
'tron.trx' => 'TRON・TRX',
|
||||
'usdt.trc20' => 'USDT・TRC20',
|
||||
'usdt.bep20' => 'USDT・BEP20',
|
||||
'usdt.erc20' => 'USDT・ERC20',
|
||||
'usdt.polygon' => 'USDT・Polygon',
|
||||
'usdt.xlayer' => 'USDT・X-Layer',
|
||||
];
|
||||
@@ -0,0 +1,33 @@
|
||||
# 回调说明
|
||||
|
||||
通过`POST /api/v1/order/create-transaction`创建的订单,自`v1.19.0`版本开始,支持三种回调事件。
|
||||
|
||||
- 支付成功
|
||||
- 等待支付
|
||||
- 支付超时
|
||||
|
||||
首先,三种回调事件的数据结构完全一样,唯一不通的就是`status`整型字段,其目前代表的含义是:
|
||||
|
||||
```
|
||||
3 // 订单过期
|
||||
2 // 订单成功
|
||||
1 // 等待支付
|
||||
```
|
||||
|
||||
## 差异说明
|
||||
|
||||
### 支付成功
|
||||
|
||||
订单支付成功后,系统会向商户端发送支付成功回调通知,字段`status`的值为`2`。
|
||||
当响应状态码是`200`,并且响应内容为`ok`时,系统认定为回调成功;否则认为回调失败。
|
||||
|
||||
失败会进行重试,分钟间隔数:`2 4 8 16 32 64 ...`以此类推,最大重试次数10,当然通过机器人也可以手动标记回调成功。
|
||||
|
||||
### 等待支付
|
||||
|
||||
当订单创建后,系统会向商户端发送等待支付的回调通知,字段`status`的值为`1`,频率为每分钟一次,状态码为`200`认为通知成功,不会重试。
|
||||
|
||||
### 支付超时
|
||||
|
||||
当订单创建后,系统会向商户端发送支付超时的回调通知,字段`status`的值为`3`,只会在订单过期时发送一次,状态码为`200`
|
||||
认为通知成功,不会重试。
|
||||
@@ -1,26 +1,31 @@
|
||||
# Linux 手动安装
|
||||
|
||||
默认认为您已经掌握 Linux 的基本操作常识,否则后续没有查看必要。
|
||||
|
||||
准备服务器,debian11+,架构目前只对amd64做了测试,其他架构请自行测试;以此执行以下命令:
|
||||
|
||||
```bash
|
||||
cd /tmp
|
||||
|
||||
# 下载最新版本
|
||||
# 下载您的对应架构版本
|
||||
wget -O ./bepusdt.zip https://github.com/v03413/bepusdt/releases/latest/download/bepusdt-linux-amd64.zip
|
||||
|
||||
# 解压
|
||||
unzip ./bepusdt.zip
|
||||
|
||||
# 移动安装至系统目录
|
||||
mv ./bepusdt /usr/local
|
||||
# 解压结构如下:
|
||||
#root@debian:~# tree ./bepusdt
|
||||
#./bepusdt
|
||||
#├── bepusdt
|
||||
#├── bepusdt.service
|
||||
#└── conf.example.toml
|
||||
|
||||
# 编辑调整参数配置,并移动到以下目录
|
||||
mv ./bepusdt/conf.example.toml /usr/local/bepusdt/conf.toml
|
||||
|
||||
# 配置软件自启
|
||||
mv /usr/local/bepusdt/bepusdt.service /etc/systemd/system
|
||||
mv ./bepusdt/bepusdt.service /etc/systemd/system
|
||||
systemctl enable bepusdt.service
|
||||
|
||||
# 配置软件参数,请根据实际情况修改文件
|
||||
vi /usr/local/bepusdt/Environment.conf
|
||||
|
||||
# 启动软件
|
||||
systemctl start bepusdt.service
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Webhook
|
||||
|
||||
自版本号`v1.20.6`开始,系统开始支持一个简易的Webhook功能。当系统发生特定事件时,向指定的URL发送HTTP POST请求。
|
||||
该功能默认关闭,当配置文件`webhook_url`参数不为空时,系统会自动开启Webhook功能,发生Post请求时:
|
||||
`Content-Type: application/json`,请求体为JSON格式。
|
||||
|
||||
## 事件类型
|
||||
|
||||
目前已知事件:https://github.com/v03413/BEpusdt/blob/525f0f407915b89ed7bccd14c84f32d22d389df1/app/model/webhook.go#L19:L22
|
||||
|
||||
## 请求数据
|
||||
|
||||
```json
|
||||
{
|
||||
"event": "event_type",
|
||||
"data": {
|
||||
"key1": "value1",
|
||||
"key2": "value2"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 请求说明
|
||||
|
||||
当事件发生时会自动触发一个Post请求,响应状态码必须为`200`,否则会认为失败;失败之后会以`2 4 8 16...`指数间隔分钟数重试,最大重试次数为
|
||||
`10`次。
|
||||
@@ -1,64 +1,69 @@
|
||||
module github.com/v03413/bepusdt
|
||||
|
||||
go 1.23.0
|
||||
go 1.24.3
|
||||
|
||||
require (
|
||||
github.com/btcsuite/btcd/btcutil v1.1.6
|
||||
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/gin-gonic/gin v1.10.1
|
||||
github.com/glebarez/sqlite v1.11.0
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
|
||||
github.com/go-telegram/bot v1.15.0
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||
github.com/shopspring/decimal v1.3.1
|
||||
github.com/panjf2000/ants/v2 v2.11.3
|
||||
github.com/pelletier/go-toml/v2 v2.2.4
|
||||
github.com/shopspring/decimal v1.4.0
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/smallnest/chanx v1.2.0
|
||||
github.com/spf13/cast v1.7.0
|
||||
github.com/tidwall/gjson v1.17.0
|
||||
github.com/spf13/cast v1.9.2
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
github.com/v03413/go-cache v0.0.0-20250526011249-dad9b89e1b2a
|
||||
github.com/v03413/tronprotocol v0.0.0-20240824084238-bbd62f5e0158
|
||||
google.golang.org/grpc v1.65.0
|
||||
gorm.io/gorm v1.25.10
|
||||
google.golang.org/grpc v1.73.0
|
||||
gorm.io/gorm v1.30.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // 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
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.22.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/go-playground/validator/v10 v10.26.0 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/google/uuid v1.6.0 // 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
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
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/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/panjf2000/ants/v2 v2.11.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/crypto v0.24.0 // indirect
|
||||
golang.org/x/net v0.26.0 // indirect
|
||||
golang.org/x/sync v0.12.0 // indirect
|
||||
golang.org/x/sys v0.21.0 // indirect
|
||||
golang.org/x/text v0.16.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240823204242-4ba0660f739c // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect
|
||||
google.golang.org/protobuf v1.34.2 // indirect
|
||||
github.com/ugorji/go/codec v1.2.14 // indirect
|
||||
golang.org/x/arch v0.18.0 // indirect
|
||||
golang.org/x/crypto v0.39.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect
|
||||
golang.org/x/net v0.41.0 // indirect
|
||||
golang.org/x/sync v0.15.0 // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
golang.org/x/text v0.26.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/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.41.0 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.7.2 // indirect
|
||||
modernc.org/sqlite v1.29.1 // indirect
|
||||
modernc.org/libc v1.65.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.38.0 // indirect
|
||||
)
|
||||
|
||||
@@ -23,12 +23,14 @@ github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku
|
||||
github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
|
||||
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
|
||||
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
|
||||
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/bytedance/sonic v1.13.3 h1:MS8gmaH16Gtirygw7jV91pDCN33NyMrPbN7qiYhEsF0=
|
||||
github.com/bytedance/sonic v1.13.3/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
|
||||
github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
|
||||
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -42,28 +44,32 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk
|
||||
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=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
|
||||
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
|
||||
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
|
||||
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
|
||||
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
|
||||
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
|
||||
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
|
||||
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
|
||||
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
|
||||
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/go-telegram/bot v1.15.0 h1:/ba5pp084MUhjR5sQDymQ7JNZ001CQa7QjtxLWcuGpg=
|
||||
github.com/go-telegram/bot v1.15.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
@@ -71,15 +77,17 @@ github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrU
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
@@ -95,18 +103,19 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -123,24 +132,26 @@ github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||
github.com/panjf2000/ants/v2 v2.11.2 h1:AVGpMSePxUNpcLaBO34xuIgM1ZdKOiGnpxLXixLi5Jo=
|
||||
github.com/panjf2000/ants/v2 v2.11.2/go.mod h1:8u92CYMUc6gyvTIw8Ru7Mt7+/ESnJahz5EVtqfrilek=
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
|
||||
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
|
||||
github.com/panjf2000/ants/v2 v2.11.3 h1:AfI0ngBoXJmYOpDh9m516vjqoUu2sLrIVgppI9TZVpg=
|
||||
github.com/panjf2000/ants/v2 v2.11.3/go.mod h1:8u92CYMUc6gyvTIw8Ru7Mt7+/ESnJahz5EVtqfrilek=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8=
|
||||
github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/smallnest/chanx v1.2.0 h1:RLyldZBbQZ4O0dSvdkTMHo4+mDw20Bc1jXXTHf+ymZo=
|
||||
github.com/smallnest/chanx v1.2.0/go.mod h1:+4nWMF0+CqEcU74SnX2NxaGqZ8zX4pcQ8Jcs77DbX5A=
|
||||
github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=
|
||||
github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE=
|
||||
github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -149,14 +160,12 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
|
||||
github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM=
|
||||
github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
@@ -164,30 +173,47 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/ugorji/go/codec v1.2.14 h1:yOQvXCBc3Ij46LRkRoh4Yd5qK6LVOgi0bYOXfb7ifjw=
|
||||
github.com/ugorji/go/codec v1.2.14/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/v03413/go-cache v0.0.0-20250526011249-dad9b89e1b2a h1:yt6xga3sEO5qpOBNap00d1c50FrWBhWJwGaJvPxu4ts=
|
||||
github.com/v03413/go-cache v0.0.0-20250526011249-dad9b89e1b2a/go.mod h1:QKQ2xRbIt1CAA6767Z00YzFWXQ9ihmoIJi7A14klR2g=
|
||||
github.com/v03413/tronprotocol v0.0.0-20240824084238-bbd62f5e0158 h1:zAlBqlv+ljSO0AOvHQo2ur/MiCZFdwMYPVf7Hu0vezE=
|
||||
github.com/v03413/tronprotocol v0.0.0-20240824084238-bbd62f5e0158/go.mod h1:ToWfuVvvk9OTE5i0nisoXPWxVdeBdEduj7ddlwf/s9M=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
|
||||
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
|
||||
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
|
||||
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w=
|
||||
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
|
||||
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
|
||||
go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA=
|
||||
go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
|
||||
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.18.0 h1:WN9poc33zL4AzGxqf8VtpKUnGvMi8O9lhNyBMF/85qc=
|
||||
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.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
|
||||
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
|
||||
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/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.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
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.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
|
||||
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
|
||||
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/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
|
||||
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -197,35 +223,37 @@ golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
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.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
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=
|
||||
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
|
||||
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240823204242-4ba0660f739c h1:e0zB268kOca6FbuJkYUGxfwG4DKFZG/8DLyv9Zv66cE=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240823204242-4ba0660f739c/go.mod h1:fO8wJzT2zbQbAjbIoos1285VfEIYKDDY+Dt+WpTkh6g=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 h1:e7S5W7MGGLaSu8j3YjdezkZ+m1/Nm0uRVRMEMGk26Xs=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=
|
||||
google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc=
|
||||
google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250324211829-b45e905df463 h1:hE3bRWtU6uceqlh4fhrSnUyjKHMKB9KrTLLG+bc0ddM=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250324211829-b45e905df463/go.mod h1:U90ffi8eUL9MwPcrJylN5+Mk2v3vuPDptd5yyNUiRR8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
|
||||
google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok=
|
||||
google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
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/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
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=
|
||||
@@ -234,14 +262,30 @@ 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/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
|
||||
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
modernc.org/libc v1.41.0 h1:g9YAc6BkKlgORsUWj+JwqoB1wU3o4DE3bM3yvA3k+Gk=
|
||||
modernc.org/libc v1.41.0/go.mod h1:w0eszPsiXoOnoMJgrXjglgLuDy/bt5RR4y3QzUUeodY=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
|
||||
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
|
||||
modernc.org/sqlite v1.29.1 h1:19GY2qvWB4VPw0HppFlZCPAbmxFU41r+qjKZQdQ1ryA=
|
||||
modernc.org/sqlite v1.29.1/go.mod h1:hG41jCYxOAOoO6BRK66AdRlmOcDzXf7qnwlwjUIOqa0=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||
modernc.org/cc/v4 v4.26.1 h1:+X5NtzVBn0KgsBCBe+xkDC7twLb/jNVj9FPgiwSQO3s=
|
||||
modernc.org/cc/v4 v4.26.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU=
|
||||
modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE=
|
||||
modernc.org/fileutil v1.3.3 h1:3qaU+7f7xxTUmvU1pJTZiDLAIoJVdUSSauJNHg9yXoA=
|
||||
modernc.org/fileutil v1.3.3/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/libc v1.65.10 h1:ZwEk8+jhW7qBjHIT+wd0d9VjitRyQef9BnzlzGwMODc=
|
||||
modernc.org/libc v1.65.10/go.mod h1:StFvYpx7i/mXtBAfVOjaU0PWZOvIRoZSgXhrwXzr8Po=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.38.0 h1:+4OrfPQ8pxHKuWG4md1JpR/EYAh3Md7TdejuuzE7EUI=
|
||||
modernc.org/sqlite v1.38.0/go.mod h1:1Bj+yES4SVvBZ4cBOpVZ6QgesMCKpJZDq0nxYzOpmNE=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app/config"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
)
|
||||
|
||||
func Init() error {
|
||||
if err := model.Init(); err != nil {
|
||||
|
||||
return fmt.Errorf("数据库初始化失败:" + err.Error())
|
||||
}
|
||||
|
||||
if config.GetTGBotToken() == "" || config.GetTGBotAdminId() == "" {
|
||||
|
||||
return fmt.Errorf("请配置参数 TG_BOT_TOKEN 和 TG_BOT_ADMIN_ID")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -3,20 +3,37 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/v03413/bepusdt/app"
|
||||
"github.com/v03413/bepusdt/app/monitor"
|
||||
"github.com/v03413/bepusdt/app/bot"
|
||||
"github.com/v03413/bepusdt/app/conf"
|
||||
"github.com/v03413/bepusdt/app/log"
|
||||
"github.com/v03413/bepusdt/app/model"
|
||||
"github.com/v03413/bepusdt/app/task"
|
||||
"github.com/v03413/bepusdt/app/web"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := Init(); err != nil {
|
||||
type Initializer func() error
|
||||
|
||||
panic(err)
|
||||
var initializers = []Initializer{conf.Init, log.Init, bot.Init, model.Init, task.Init}
|
||||
|
||||
func init() {
|
||||
for _, initFunc := range initializers {
|
||||
if err := initFunc(); err != nil {
|
||||
|
||||
panic(fmt.Sprintf("初始化失败: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
monitor.Start()
|
||||
if conf.BotToken() == "" || conf.BotAdminID() == 0 {
|
||||
|
||||
panic("请配置参数 BOT_TOKEN 和 BOT_ADMIN_ID")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
task.Start()
|
||||
|
||||
web.Start()
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// 全局变量
|
||||
let countdownTimer = null;
|
||||
let statusCheckTimer = null;
|
||||
let totalSeconds = null;
|
||||
let paymentConfig = {};
|
||||
|
||||
// 初始化配置
|
||||
function initConfig(config) {
|
||||
paymentConfig = config;
|
||||
totalSeconds = config.expire;
|
||||
}
|
||||
|
||||
// 生成二维码
|
||||
function generateQRCode() {
|
||||
const qrContainer = document.getElementById('qrcode');
|
||||
const containerWidth = qrContainer.offsetWidth;
|
||||
const qrSize = Math.min(containerWidth - 10, 150); // 留出10px的边距
|
||||
|
||||
$('#qrcode').qrcode({
|
||||
text: paymentConfig.address,
|
||||
width: qrSize,
|
||||
height: qrSize,
|
||||
foreground: "#000000",
|
||||
background: "#ffffff",
|
||||
typeNumber: -1
|
||||
});
|
||||
}
|
||||
|
||||
// 复制地址
|
||||
function copyAddress() {
|
||||
const address = document.getElementById('walletAddress').textContent;
|
||||
navigator.clipboard.writeText(address).then(function () {
|
||||
const btn = document.querySelector('.copy-btn');
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = '已复制!';
|
||||
btn.style.background = '#48bb78';
|
||||
|
||||
setTimeout(function () {
|
||||
btn.textContent = originalText;
|
||||
btn.style.background = '#667eea';
|
||||
}, 2000);
|
||||
}).catch(function (err) {
|
||||
console.error('复制失败: ', err);
|
||||
// 降级方案
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = address;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
const btn = document.querySelector('.copy-btn');
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = '已复制!';
|
||||
btn.style.background = '#48bb78';
|
||||
setTimeout(function () {
|
||||
btn.textContent = originalText;
|
||||
btn.style.background = '#667eea';
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
alert('复制失败,请手动复制地址');
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
});
|
||||
}
|
||||
|
||||
// 倒计时
|
||||
function startCountdown() {
|
||||
const minutesEl = document.getElementById('minutes');
|
||||
const secondsEl = document.getElementById('seconds');
|
||||
|
||||
function updateDisplay() {
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
if (totalSeconds <= 0) {
|
||||
minutesEl.textContent = '00';
|
||||
secondsEl.textContent = '00';
|
||||
} else {
|
||||
minutesEl.textContent = minutes.toString().padStart(2, '0');
|
||||
secondsEl.textContent = seconds.toString().padStart(2, '0');
|
||||
}
|
||||
|
||||
// 当剩余时间少于5分钟时,倒计时变红色
|
||||
if (totalSeconds <= 300) { // 5分钟 = 300秒
|
||||
document.querySelector('.countdown-banner').style.background = 'linear-gradient(135deg, #ff4757, #ff3838)';
|
||||
}
|
||||
|
||||
// 当剩余时间少于1分钟时,添加紧急闪烁效果
|
||||
if (totalSeconds <= 60) {
|
||||
document.querySelector('.countdown-banner').style.animation = 'urgentBlink 1s infinite';
|
||||
}
|
||||
}
|
||||
|
||||
countdownTimer = setInterval(function () {
|
||||
totalSeconds--;
|
||||
updateDisplay();
|
||||
|
||||
if (totalSeconds <= 0) {
|
||||
clearInterval(countdownTimer);
|
||||
clearInterval(statusCheckTimer);
|
||||
showTimeoutMessage();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
// 初始化显示
|
||||
updateDisplay();
|
||||
}
|
||||
|
||||
// 支付超时
|
||||
function showTimeoutMessage() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
`;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.style.cssText = `
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
width: 90%;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">⏰</div>
|
||||
<h3 style="color: #e53e3e; margin-bottom: 15px;">支付时间已过期</h3>
|
||||
<p style="color: #666; margin-bottom: 25px; line-height: 1.5;">
|
||||
很抱歉,支付时间已超时。<br>
|
||||
请重新发起支付或联系客服处理。
|
||||
</p>
|
||||
<button onclick="location.href='${paymentConfig.return_url}'" style="
|
||||
background: #667eea;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
margin-right: 10px;
|
||||
">返回商户平台</button>
|
||||
`;
|
||||
|
||||
overlay.appendChild(modal);
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
// 支付成功
|
||||
function showSuccessMessage(data) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
`;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.style.cssText = `
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
width: 90%;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">✅</div>
|
||||
<h3 style="color: #48bb78; margin-bottom: 15px;">支付成功!</h3>
|
||||
<p style="color: #666; margin-bottom: 20px; line-height: 1.5;">
|
||||
您的支付已确认,交易哈希:<br>
|
||||
<code style="background: #e6f0fa; color: #2563eb; padding: 4px 8px; border-radius: 4px; font-size: 12px; word-break: break-all;">
|
||||
${data.trade_hash || '处理中...'}
|
||||
</code>
|
||||
</p>
|
||||
<button onclick="location.href='${data.return_url || '/'}'" style="
|
||||
background: #48bb78;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
">返回商户平台</button>
|
||||
`;
|
||||
|
||||
overlay.appendChild(modal);
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
// 清除定时器
|
||||
if (countdownTimer) clearInterval(countdownTimer);
|
||||
if (statusCheckTimer) clearInterval(statusCheckTimer);
|
||||
}
|
||||
|
||||
// 检查支付状态
|
||||
function checkPaymentStatus() {
|
||||
$.ajax({
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
url: "/pay/check-status/" + paymentConfig.trade_id,
|
||||
success: function (data) {
|
||||
if (data.status === 1) {
|
||||
return setTimeout(checkPaymentStatus, 5000); // 等待支付
|
||||
}
|
||||
if (data.status === 2) {
|
||||
return showSuccessMessage(data); // 支付成功
|
||||
}
|
||||
if (data.status === 3) {
|
||||
return showTimeoutMessage(); // 支付超时
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化函数
|
||||
function init(config) {
|
||||
initConfig(config);
|
||||
generateQRCode();
|
||||
startCountdown();
|
||||
setTimeout(checkPaymentStatus, 2000);
|
||||
}
|
||||
|
||||
// 暴露全局函数
|
||||
window.copyAddress = copyAddress;
|
||||
window.USDTPayment = {
|
||||
init: init
|
||||
};
|
||||
|
||||
})();
|
||||
@@ -1,138 +1,93 @@
|
||||
<html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
|
||||
<meta name="renderer" content="webkit">
|
||||
<meta name="HandheldFriendly" content="True"/>
|
||||
<meta name="MobileOptimized" content="320"/>
|
||||
<meta name="format-detection" content="telephone=no"/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
|
||||
<link rel="shortcut icon" href="/img/tron_trx.svg"/>
|
||||
<link href="/css/main.min.css" rel="stylesheet"/>
|
||||
<title>Bepusdt - 一款更好USDT支付中间件</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TRX・Tron 一款更好用的个人TRX收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/clipboard.min.js"></script>
|
||||
<script src="/js/layer.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="icon">
|
||||
<img class="logo" src="/img/trx.png" alt="logo">
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">TRX</div>
|
||||
<h1 class="payment-title">TRX 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 <strong>Tron</strong> 网络进行转账
|
||||
<span class="network-badge">Tron</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} TRX</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
<h1>{{.http_host}}</h1>
|
||||
<label>
|
||||
请扫描二维码或点击金额和地址粘贴转账TRX支付。<br>
|
||||
<b style="color: red">转账金额必须为下方显示的金额且需要在倒计时内完成转账,否则无法被系统确认!</b>
|
||||
</label>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="section">
|
||||
<div class="title">
|
||||
<h1 class="amount parse-amount" data-clipboard-text="{{.amount}}" id="usdt">
|
||||
{{.amount}} <span>TRX</span>
|
||||
</h1>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="address parse-action" data-clipboard-text="{{.address}}" id="address">
|
||||
{{.address}}
|
||||
</div>
|
||||
<div class="main">
|
||||
<div class="qr-image" id="qrcode"></div>
|
||||
</div>
|
||||
<div class="timer">
|
||||
<ul class="downcount">
|
||||
<li>
|
||||
<span class="hours">00</span>
|
||||
<p class="hours_ref">时</p>
|
||||
</li>
|
||||
<li class="seperator">:</li>
|
||||
<li>
|
||||
<span class="minutes">00</span>
|
||||
<p class="minutes_ref">分</p>
|
||||
</li>
|
||||
<li class="seperator">:</li>
|
||||
<li>
|
||||
<span class="seconds">00</span>
|
||||
<p class="seconds_ref">秒</p>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>Powered by <a href="https://github.com/v03413/bepusdt" target="_blank">v03413 - Bepusdt</a></p>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (Tron 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>Tron 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let expire = {{.expire}};
|
||||
let startTime = Date.now();
|
||||
|
||||
// 支付时间倒计时
|
||||
function clock() {
|
||||
let now = Date.now();
|
||||
let elapsed = Math.floor((now - startTime) / 1000); // 计算已过去的秒数
|
||||
let seconds = expire - elapsed; // 计算剩余秒数
|
||||
|
||||
let minute = Math.floor(seconds / 60);
|
||||
let hour = Math.floor(minute / 60);
|
||||
|
||||
if (seconds <= 0) {
|
||||
return layer.alert("支付超时,请重新发起支付!", {icon: 5});
|
||||
}
|
||||
|
||||
$('.hours').text(hour.toString().padStart(2, '0'));
|
||||
$('.minutes').text(minute.toString().padStart(2, '0'));
|
||||
$('.seconds').text((seconds % 60).toString().padStart(2, '0'));
|
||||
|
||||
setTimeout(clock, 1000);
|
||||
}
|
||||
|
||||
function checkStatus() {
|
||||
$.ajax({
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
url: "/pay/check-status/{{.trade_id}}",
|
||||
success: function (data) {
|
||||
if (data.status === 1) {
|
||||
// 等待支付
|
||||
return setTimeout(checkStatus, 5000);
|
||||
}
|
||||
if (data.status === 2) { // 支付成功
|
||||
layer.msg('支付成功,正在跳转中...', {icon: 16, shade: 0.01, time: 20000});
|
||||
|
||||
return window.location.href = data.return_url;
|
||||
}
|
||||
if (data.status === 3) {
|
||||
|
||||
return layer.alert("支付超时,请重新发起支付!", {icon: 5, title: "❌ 支付超时"});
|
||||
}
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
}
|
||||
|
||||
$(function () {
|
||||
$('#qrcode').qrcode({
|
||||
text: "{{.address}}",
|
||||
width: 230,
|
||||
height: 230,
|
||||
foreground: "#000000",
|
||||
background: "#ffffff",
|
||||
typeNumber: -1
|
||||
});
|
||||
|
||||
(new ClipboardJS('#usdt')).on('success', function (e) {
|
||||
return layer.msg('金额复制成功');
|
||||
});
|
||||
(new ClipboardJS('#address')).on('success', function (e) {
|
||||
layer.msg('地址复制成功');
|
||||
});
|
||||
|
||||
setTimeout(clock, 1000);
|
||||
setTimeout(checkStatus, 2000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・Aptos 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 <strong>Aptos</strong> 区块网络进行转账
|
||||
<span class="network-badge">Aptos</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (Aptos 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>Aptos 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,319 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・BEP20 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg" />
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 币安智能链<strong>(BSC)</strong> 进行转账
|
||||
<span class="network-badge">BEP20</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (BEP20 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>BEP20 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">优雅开源</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 全局变量
|
||||
let countdownTimer = null;
|
||||
let statusCheckTimer = null;
|
||||
let totalSeconds = '{{.expire }}';
|
||||
|
||||
// 生成二维码
|
||||
function generateQRCode() {
|
||||
const qrContainer = document.getElementById('qrcode');
|
||||
const containerWidth = qrContainer.offsetWidth;
|
||||
const qrSize = Math.min(containerWidth - 10, 150); // 留出10px的边距
|
||||
|
||||
$('#qrcode').qrcode({
|
||||
text: "{{.address}}",
|
||||
width: qrSize,
|
||||
height: qrSize,
|
||||
foreground: "#000000",
|
||||
background: "#ffffff",
|
||||
typeNumber: -1
|
||||
});
|
||||
}
|
||||
|
||||
// 复制地址
|
||||
function copyAddress() {
|
||||
const address = document.getElementById('walletAddress').textContent;
|
||||
navigator.clipboard.writeText(address).then(function () {
|
||||
const btn = document.querySelector('.copy-btn');
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = '已复制!';
|
||||
btn.style.background = '#48bb78';
|
||||
|
||||
setTimeout(function () {
|
||||
btn.textContent = originalText;
|
||||
btn.style.background = '#667eea';
|
||||
}, 2000);
|
||||
}).catch(function (err) {
|
||||
console.error('复制失败: ', err);
|
||||
// 降级方案
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = address;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
const btn = document.querySelector('.copy-btn');
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = '已复制!';
|
||||
btn.style.background = '#48bb78';
|
||||
setTimeout(function () {
|
||||
btn.textContent = originalText;
|
||||
btn.style.background = '#667eea';
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
alert('复制失败,请手动复制地址');
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
});
|
||||
}
|
||||
|
||||
// 倒计时
|
||||
function startCountdown() {
|
||||
const minutesEl = document.getElementById('minutes');
|
||||
const secondsEl = document.getElementById('seconds');
|
||||
|
||||
function updateDisplay() {
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
if (totalSeconds <= 0) {
|
||||
minutesEl.textContent = '00';
|
||||
secondsEl.textContent = '00';
|
||||
} else {
|
||||
minutesEl.textContent = minutes.toString().padStart(2, '0');
|
||||
secondsEl.textContent = seconds.toString().padStart(2, '0');
|
||||
}
|
||||
|
||||
// 当剩余时间少于5分钟时,倒计时变红色
|
||||
if (totalSeconds <= 300) { // 5分钟 = 300秒
|
||||
document.querySelector('.countdown-banner').style.background = 'linear-gradient(135deg, #ff4757, #ff3838)';
|
||||
}
|
||||
|
||||
// 当剩余时间少于1分钟时,添加紧急闪烁效果
|
||||
if (totalSeconds <= 60) {
|
||||
document.querySelector('.countdown-banner').style.animation = 'urgentBlink 1s infinite';
|
||||
}
|
||||
}
|
||||
|
||||
countdownTimer = setInterval(function () {
|
||||
totalSeconds--;
|
||||
updateDisplay();
|
||||
|
||||
if (totalSeconds <= 0) {
|
||||
clearInterval(countdownTimer);
|
||||
clearInterval(statusCheckTimer);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
// 初始化显示
|
||||
updateDisplay();
|
||||
}
|
||||
|
||||
// 支付超时
|
||||
function showTimeoutMessage() {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
`;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.style.cssText = `
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
width: 90%;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
|
||||
`;
|
||||
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">⏰</div>
|
||||
<h3 style="color: #e53e3e; margin-bottom: 15px;">支付时间已过期</h3>
|
||||
<p style="color: #666; margin-bottom: 25px; line-height: 1.5;">
|
||||
很抱歉,支付时间已超时。<br>
|
||||
请重新发起支付或联系客服处理。
|
||||
</p>
|
||||
<button onclick="location.href='{{.return_url}}'" style="
|
||||
background: #667eea;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
margin-right: 10px;
|
||||
">返回商户平台</button>
|
||||
`;
|
||||
|
||||
overlay.appendChild(modal);
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
// 支付成功
|
||||
function showSuccessMessage(data) {
|
||||
const overlay = document.createElement('div');
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
`;
|
||||
|
||||
const modal = document.createElement('div');
|
||||
modal.style.cssText = `
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
width: 90%;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
|
||||
`;
|
||||
|
||||
modal.innerHTML = `
|
||||
<div style="font-size: 48px; margin-bottom: 20px;">✅</div>
|
||||
<h3 style="color: #48bb78; margin-bottom: 15px;">支付成功!</h3>
|
||||
<p style="color: #666; margin-bottom: 20px; line-height: 1.5;">
|
||||
您的支付已确认,交易哈希:<br>
|
||||
<code style="background: #e6f0fa; color: #2563eb; padding: 4px 8px; border-radius: 4px; font-size: 12px; word-break: break-all;">
|
||||
${data.trade_hash || '处理中...'}
|
||||
</code>
|
||||
</p>
|
||||
<button onclick="location.href='${data.return_url || '/'}'" style="
|
||||
background: #48bb78;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
">返回商户平台</button>
|
||||
`;
|
||||
|
||||
overlay.appendChild(modal);
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
// 清除定时器
|
||||
if (countdownTimer) clearInterval(countdownTimer);
|
||||
if (statusCheckTimer) clearInterval(statusCheckTimer);
|
||||
}
|
||||
|
||||
// 检查支付状态
|
||||
function checkPaymentStatus() {
|
||||
$.ajax({
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
url: "/pay/check-status/{{.trade_id}}",
|
||||
success: function (data) {
|
||||
if (data.status === 1) {
|
||||
|
||||
return setTimeout(checkPaymentStatus, 5000); // 等待支付
|
||||
}
|
||||
if (data.status === 2) {
|
||||
|
||||
return showSuccessMessage(data); // 支付成功
|
||||
}
|
||||
if (data.status === 3) {
|
||||
|
||||
return showTimeoutMessage(); // 支付超时
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
generateQRCode();
|
||||
startCountdown();
|
||||
|
||||
setTimeout(checkPaymentStatus, 2000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・ERC20 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 以太坊<strong>(Ethereum)</strong> 进行转账
|
||||
<span class="network-badge">ERC20</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (ERC20 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>ERC20 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,138 +1,93 @@
|
||||
<html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
|
||||
<meta name="renderer" content="webkit">
|
||||
<meta name="HandheldFriendly" content="True"/>
|
||||
<meta name="MobileOptimized" content="320"/>
|
||||
<meta name="format-detection" content="telephone=no"/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・Polygon 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link href="/css/main.min.css" rel="stylesheet"/>
|
||||
<title>Bepusdt - 一款更好USDT支付中间件</title>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/clipboard.min.js"></script>
|
||||
<script src="/js/layer.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="icon">
|
||||
<img class="logo" src="/img/tether.svg" alt="logo">
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 <strong>Polygon</strong> 进行转账
|
||||
<span class="network-badge">Polygon</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
<h1>{{.http_host}}</h1>
|
||||
<label>
|
||||
请扫描二维码或点击金额和地址粘贴转账USDT(Polygon)支付。<br>
|
||||
<b style="color: red">转账金额必须为下方显示的金额且需要在倒计时内完成转账,否则无法被系统确认!</b>
|
||||
</label>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="section">
|
||||
<div class="title">
|
||||
<h1 class="amount parse-amount" data-clipboard-text="{{.amount}}" id="usdt">
|
||||
{{.amount}} <span>USDT.POLYGON</span>
|
||||
</h1>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="address parse-action" data-clipboard-text="{{.address}}" id="address">
|
||||
{{.address}}
|
||||
</div>
|
||||
<div class="main">
|
||||
<div class="qr-image" id="qrcode"></div>
|
||||
</div>
|
||||
<div class="timer">
|
||||
<ul class="downcount">
|
||||
<li>
|
||||
<span class="hours">00</span>
|
||||
<p class="hours_ref">时</p>
|
||||
</li>
|
||||
<li class="seperator">:</li>
|
||||
<li>
|
||||
<span class="minutes">00</span>
|
||||
<p class="minutes_ref">分</p>
|
||||
</li>
|
||||
<li class="seperator">:</li>
|
||||
<li>
|
||||
<span class="seconds">00</span>
|
||||
<p class="seconds_ref">秒</p>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>Powered by <a href="https://github.com/v03413/bepusdt" target="_blank">v03413 - Bepusdt</a></p>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (Polygon 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>Polygon 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let expire = {{.expire}};
|
||||
let startTime = Date.now();
|
||||
|
||||
// 支付时间倒计时
|
||||
function clock() {
|
||||
let now = Date.now();
|
||||
let elapsed = Math.floor((now - startTime) / 1000); // 计算已过去的秒数
|
||||
let seconds = expire - elapsed; // 计算剩余秒数
|
||||
|
||||
let minute = Math.floor(seconds / 60);
|
||||
let hour = Math.floor(minute / 60);
|
||||
|
||||
if (seconds <= 0) {
|
||||
return layer.alert("支付超时,请重新发起支付!", {icon: 5});
|
||||
}
|
||||
|
||||
$('.hours').text(hour.toString().padStart(2, '0'));
|
||||
$('.minutes').text(minute.toString().padStart(2, '0'));
|
||||
$('.seconds').text((seconds % 60).toString().padStart(2, '0'));
|
||||
|
||||
setTimeout(clock, 1000);
|
||||
}
|
||||
|
||||
function checkStatus() {
|
||||
$.ajax({
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
url: "/pay/check-status/{{.trade_id}}",
|
||||
success: function (data) {
|
||||
if (data.status === 1) {
|
||||
// 等待支付
|
||||
return setTimeout(checkStatus, 5000);
|
||||
}
|
||||
if (data.status === 2) { // 支付成功
|
||||
layer.msg('支付成功,正在跳转中...', {icon: 16, shade: 0.01, time: 20000});
|
||||
|
||||
return window.location.href = data.return_url;
|
||||
}
|
||||
if (data.status === 3) {
|
||||
|
||||
return layer.alert("支付超时,请重新发起支付!", {icon: 5, title: "❌ 支付超时"});
|
||||
}
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
}
|
||||
|
||||
$(function () {
|
||||
$('#qrcode').qrcode({
|
||||
text: "{{.address}}",
|
||||
width: 230,
|
||||
height: 230,
|
||||
foreground: "#000000",
|
||||
background: "#ffffff",
|
||||
typeNumber: -1
|
||||
});
|
||||
|
||||
(new ClipboardJS('#usdt')).on('success', function (e) {
|
||||
return layer.msg('金额复制成功');
|
||||
});
|
||||
(new ClipboardJS('#address')).on('success', function (e) {
|
||||
layer.msg('地址复制成功');
|
||||
});
|
||||
|
||||
setTimeout(clock, 1000);
|
||||
setTimeout(checkStatus, 2000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・Solana 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 <strong>Solana</strong> 区块网络进行转账
|
||||
<span class="network-badge">Solana</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (Solana 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>Solana 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,138 +1,93 @@
|
||||
<html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
|
||||
<meta name="renderer" content="webkit">
|
||||
<meta name="HandheldFriendly" content="True"/>
|
||||
<meta name="MobileOptimized" content="320"/>
|
||||
<meta name="format-detection" content="telephone=no"/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes"/>
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・TRC20 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link href="/css/main.min.css" rel="stylesheet"/>
|
||||
<title>Bepusdt - 一款更好USDT支付中间件</title>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/clipboard.min.js"></script>
|
||||
<script src="/js/layer.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<div class="icon">
|
||||
<img class="logo" src="/img/tether.svg" alt="logo">
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 波场<strong>(TRON)</strong> 进行转账
|
||||
<span class="network-badge">TRC20</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
<h1>{{.http_host}}</h1>
|
||||
<label>
|
||||
请扫描二维码或点击金额和地址粘贴转账USDT(trc-20)支付。<br>
|
||||
<b style="color: red">转账金额必须为下方显示的金额且需要在倒计时内完成转账,否则无法被系统确认!</b>
|
||||
</label>
|
||||
</div>
|
||||
<div class="content">
|
||||
<div class="section">
|
||||
<div class="title">
|
||||
<h1 class="amount parse-amount" data-clipboard-text="{{.amount}}" id="usdt">
|
||||
{{.amount}} <span>USDT.TRC20</span>
|
||||
</h1>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="address parse-action" data-clipboard-text="{{.address}}" id="address">
|
||||
{{.address}}
|
||||
</div>
|
||||
<div class="main">
|
||||
<div class="qr-image" id="qrcode"></div>
|
||||
</div>
|
||||
<div class="timer">
|
||||
<ul class="downcount">
|
||||
<li>
|
||||
<span class="hours">00</span>
|
||||
<p class="hours_ref">时</p>
|
||||
</li>
|
||||
<li class="seperator">:</li>
|
||||
<li>
|
||||
<span class="minutes">00</span>
|
||||
<p class="minutes_ref">分</p>
|
||||
</li>
|
||||
<li class="seperator">:</li>
|
||||
<li>
|
||||
<span class="seconds">00</span>
|
||||
<p class="seconds_ref">秒</p>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>Powered by <a href="https://github.com/v03413/bepusdt" target="_blank">v03413 - Bepusdt</a></p>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (TRC20 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>TRC20 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let expire = {{.expire}};
|
||||
let startTime = Date.now();
|
||||
|
||||
// 支付时间倒计时
|
||||
function clock() {
|
||||
let now = Date.now();
|
||||
let elapsed = Math.floor((now - startTime) / 1000); // 计算已过去的秒数
|
||||
let seconds = expire - elapsed; // 计算剩余秒数
|
||||
|
||||
let minute = Math.floor(seconds / 60);
|
||||
let hour = Math.floor(minute / 60);
|
||||
|
||||
if (seconds <= 0) {
|
||||
return layer.alert("支付超时,请重新发起支付!", {icon: 5});
|
||||
}
|
||||
|
||||
$('.hours').text(hour.toString().padStart(2, '0'));
|
||||
$('.minutes').text(minute.toString().padStart(2, '0'));
|
||||
$('.seconds').text((seconds % 60).toString().padStart(2, '0'));
|
||||
|
||||
setTimeout(clock, 1000);
|
||||
}
|
||||
|
||||
function checkStatus() {
|
||||
$.ajax({
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
url: "/pay/check-status/{{.trade_id}}",
|
||||
success: function (data) {
|
||||
if (data.status === 1) {
|
||||
// 等待支付
|
||||
return setTimeout(checkStatus, 5000);
|
||||
}
|
||||
if (data.status === 2) { // 支付成功
|
||||
layer.msg('支付成功,正在跳转中...', {icon: 16, shade: 0.01, time: 20000});
|
||||
|
||||
return window.location.href = data.return_url;
|
||||
}
|
||||
if (data.status === 3) {
|
||||
|
||||
return layer.alert("支付超时,请重新发起支付!", {icon: 5, title: "❌ 支付超时"});
|
||||
}
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
}
|
||||
|
||||
$(function () {
|
||||
$('#qrcode').qrcode({
|
||||
text: "{{.address}}",
|
||||
width: 230,
|
||||
height: 230,
|
||||
foreground: "#000000",
|
||||
background: "#ffffff",
|
||||
typeNumber: -1
|
||||
});
|
||||
|
||||
(new ClipboardJS('#usdt')).on('success', function (e) {
|
||||
return layer.msg('金额复制成功');
|
||||
});
|
||||
(new ClipboardJS('#address')).on('success', function (e) {
|
||||
layer.msg('地址复制成功');
|
||||
});
|
||||
|
||||
setTimeout(clock, 1000);
|
||||
setTimeout(checkStatus, 2000);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>USDT・X Layer 一款更好用的个人USDT收款网关 Bepusdt</title>
|
||||
<link rel="shortcut icon" href="/img/tether.svg"/>
|
||||
<link rel="stylesheet" href="/css/usdt.min.css">
|
||||
<script src="/js/jquery.min.js"></script>
|
||||
<script src="/js/jquery.qrcode_1.0.min.js"></script>
|
||||
<script src="/js/usdt.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="payment-container">
|
||||
<div class="crypto-icon">USDT</div>
|
||||
<h1 class="payment-title">USDT 支付</h1>
|
||||
<p class="payment-subtitle">
|
||||
<span class="status-indicator"></span>
|
||||
请使用 OKX<strong>(X Layer)</strong> 进行转账
|
||||
<span class="network-badge">X Layer</span>
|
||||
</p>
|
||||
<div class="order-info">
|
||||
<div class="order-item">
|
||||
<span class="order-label">转账金额:</span>
|
||||
<span class="order-value amount-highlight" id="payAmount">{{.amount}} USDT</span>
|
||||
</div>
|
||||
<div class="order-item">
|
||||
<span class="order-label">商户订单:</span>
|
||||
<span class="order-value" id="orderNumber">{{.order_id}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="countdown-banner">
|
||||
<div class="countdown-content">
|
||||
<div class="countdown-info">
|
||||
<div class="countdown-title">⏰ 支付倒计时</div>
|
||||
<div class="countdown-subtitle">请在时间内完成转账</div>
|
||||
</div>
|
||||
<div class="countdown-timer" id="countdown">
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="minutes">15</span>
|
||||
<span class="time-label">分</span>
|
||||
</div>
|
||||
<span class="time-separator">:</span>
|
||||
<div class="time-unit">
|
||||
<span class="time-number" id="seconds">00</span>
|
||||
<span class="time-label">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="qr-section">
|
||||
<div class="qr-code" id="qrcode"></div>
|
||||
<div class="address-section">
|
||||
<div class="address-label">收款地址 (X Layer 网络)</div>
|
||||
<div class="address-text" id="walletAddress">{{.address}}</div>
|
||||
<button class="copy-btn" onclick="copyAddress()">复制地址</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="instructions">
|
||||
<h4>📋 转账说明</h4>
|
||||
<ol>
|
||||
<li>必须使用 <strong>X Layer 网络</strong> 进行转账</li>
|
||||
<li>转账完成后系统会自动确认到账</li>
|
||||
<li>转账金额必须与显示金额完全一致</li>
|
||||
<li>如果有其它疑问 请联系客服处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="footer-info">
|
||||
<div class="project-info">
|
||||
<span class="powered-by">Powered by</span>
|
||||
<a href="https://github.com/v03413/bepusdt" target="_blank" class="project-link">
|
||||
<strong>Bepusdt</strong>
|
||||
</a>
|
||||
<span class="open-source">Github</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
USDTPayment.init({
|
||||
expire: "{{.expire}}",
|
||||
address: "{{.address}}",
|
||||
trade_id: "{{.trade_id}}",
|
||||
return_url: "{{.return_url}}"
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||