forked from ai365vip/chat-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopup.go
264 lines (247 loc) · 8.38 KB
/
topup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package controller
import (
"fmt"
"log"
"net/url"
"one-api/common"
"one-api/model"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/samber/lo"
epay "github.com/star-horizon/go-epay"
)
type EpayRequest struct {
Amount int `json:"amount"`
PaymentMethod string `json:"payment_method"`
TopUpCode string `json:"top_up_code"`
}
type AmountRequest struct {
Amount int `json:"amount"`
TopUpCode string `json:"top_up_code"`
}
func GetEpayClient() *epay.Client {
if common.PayAddress == "" || common.EpayId == "" || common.EpayKey == "" {
return nil
}
withUrl, err := epay.NewClientWithUrl(&epay.Config{
PartnerID: common.EpayId,
Key: common.EpayKey,
}, common.PayAddress)
if err != nil {
return nil
}
return withUrl
}
func GetAmount(count float64, user model.User) float64 {
// 别问为什么用float64,问就是这么点钱没必要
topupGroupRatio := common.GetTopupGroupRatio(user.Group)
if topupGroupRatio == 0 {
topupGroupRatio = 1
}
amount := count * common.Price * topupGroupRatio
return amount
}
func RequestEpay(c *gin.Context) {
var req EpayRequest
err := c.ShouldBindJSON(&req)
if err != nil {
c.JSON(200, gin.H{"message": err.Error(), "data": 10})
return
}
if req.Amount < 1 {
c.JSON(200, gin.H{"message": "充值金额不能小于1", "data": 10})
return
}
id := c.GetInt("id")
user, _ := model.GetUserById(id, false)
amount := GetAmount(float64(req.Amount), *user)
var payType epay.PurchaseType
if req.PaymentMethod == "zfb" {
payType = epay.Alipay
}
if req.PaymentMethod == "wx" {
req.PaymentMethod = "wxpay"
payType = epay.WechatPay
}
returnUrl, _ := url.Parse(common.ServerAddress + "/log")
notifyUrl, _ := url.Parse(common.ServerAddress + "/api/user/epay/notify")
tradeNo := strconv.FormatInt(time.Now().Unix(), 10)
payMoney := amount
client := GetEpayClient()
if client == nil {
c.JSON(200, gin.H{"message": "error", "data": "当前管理员未配置支付信息"})
return
}
uri, params, err := client.Purchase(&epay.PurchaseArgs{
Type: payType,
ServiceTradeNo: "A" + tradeNo,
Name: "B" + tradeNo,
Money: strconv.FormatFloat(payMoney, 'f', 2, 64),
Device: epay.PC,
NotifyUrl: notifyUrl,
ReturnUrl: returnUrl,
})
if err != nil {
c.JSON(200, gin.H{"message": "error", "data": "拉起支付失败"})
return
}
topUp := &model.TopUp{
UserId: id,
Amount: req.Amount,
Money: payMoney,
TradeNo: "A" + tradeNo,
CreateTime: time.Now().Unix(),
Status: "pending",
}
err = topUp.Insert()
if err != nil {
c.JSON(200, gin.H{"message": "error", "data": "创建订单失败"})
return
}
c.JSON(200, gin.H{"message": "success", "data": params, "url": uri})
}
func EpayNotify(c *gin.Context) {
params := lo.Reduce(lo.Keys(c.Request.URL.Query()), func(r map[string]string, t string, i int) map[string]string {
r[t] = c.Request.URL.Query().Get(t)
return r
}, map[string]string{})
client := GetEpayClient()
if client == nil {
log.Println("易支付回调失败 未找到配置信息")
_, err := c.Writer.Write([]byte("fail"))
if err != nil {
log.Println("易支付回调写入失败")
}
notifyEmailForFail() // 发送回调失败通知
notifyWxPusherForFail() // 发送回调失败通知
return
}
verifyInfo, err := client.Verify(params)
if err != nil || !verifyInfo.VerifyStatus {
log.Printf("易支付回调验证失败: %v", err)
_, writeErr := c.Writer.Write([]byte("fail"))
if writeErr != nil {
log.Println("易支付回调写入失败")
}
notifyEmailForFail() // 发送验证失败通知
notifyWxPusherForFail() // 发送验证失败通知
return
}
if verifyInfo.TradeStatus == epay.StatusTradeSuccess {
log.Println(verifyInfo)
topUp := model.GetTopUpByTradeNo(verifyInfo.ServiceTradeNo)
if topUp != nil && topUp.Status == "pending" {
topUp.Status = "success"
err := topUp.Update()
if err != nil {
log.Printf("易支付回调更新订单失败: %v", topUp)
return
}
//user, _ := model.GetUserById(topUp.UserId, false)
//user.Quota += topUp.Amount * 500000
multipliedQuota := float64(topUp.Amount) * common.QuotaPerUnit
err = model.IncreaseUserQuota(topUp.UserId, int(multipliedQuota))
if err != nil {
log.Printf("易支付回调更新用户失败: %v", topUp)
return
}
log.Printf("易支付回调更新用户成功 %v", topUp)
err = model.VipUserQuota(topUp.UserId)
if err != nil {
log.Printf("用户分组更新失败: %v", topUp)
return
}
notifyEmail(topUp)
notifyWxPusher(topUp)
model.RecordLog(topUp.UserId, model.LogTypeTopup, int(multipliedQuota), fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%f", common.LogQuota(int(multipliedQuota)), topUp.Money))
model.VipInsert(topUp.UserId, topUp.Amount)
}
_, writeErr := c.Writer.Write([]byte("success")) // 确保发送 success 响应
if writeErr != nil {
log.Println("易支付回调响应成功写入失败")
}
} else {
log.Printf("易支付异常回调: %v", verifyInfo)
_, writeErr := c.Writer.Write([]byte("fail"))
if writeErr != nil {
log.Println("易支付回调写入失败")
}
}
}
func notifyEmail(topUp *model.TopUp) {
emailNotifEnabled, _ := strconv.ParseBool(common.OptionMap["EmailNotificationsEnabled"])
if emailNotifEnabled {
notificationEmail := common.OptionMap["NotificationEmail"]
if notificationEmail == "" {
// 如果没有设置专门的通知邮箱,则尝试获取 RootUserEmail
if common.RootUserEmail == "" {
common.RootUserEmail = model.GetRootUserEmail()
}
notificationEmail = common.RootUserEmail
}
subject := fmt.Sprintf("充值成功通知: 用户「%d」充值金额:%v,支付金额:%f", topUp.UserId, common.LogQuota(topUp.Amount*500000), topUp.Money)
content := fmt.Sprintf("用户「%d」使用在线充值成功。充值金额:%v,支付金额:%f", topUp.UserId, common.LogQuota(topUp.Amount*500000), topUp.Money)
err := common.SendEmail(subject, notificationEmail, content)
if err != nil {
common.SysError(fmt.Sprintf("failed to send email notification: %s", err.Error()))
}
}
}
func notifyWxPusher(topUp *model.TopUp) {
wxNotifEnabled, _ := strconv.ParseBool(common.OptionMap["WxPusherNotificationsEnabled"])
if wxNotifEnabled {
subject := fmt.Sprintf("充值成功通知: 用户「%d」充值金额:%v,支付金额:%f", topUp.UserId, common.LogQuota(topUp.Amount*500000), topUp.Money)
content := fmt.Sprintf("用户「%d」使用在线充值成功。充值金额:%v,支付金额:%f", topUp.UserId, common.LogQuota(topUp.Amount*500000), topUp.Money)
err := SendWxPusherNotification(subject, content)
if err != nil {
common.SysError(fmt.Sprintf("无法发送WxPusher通知: %s", err))
}
}
}
func notifyEmailForFail() {
emailNotifEnabled, _ := strconv.ParseBool(common.OptionMap["EmailNotificationsEnabled"])
if emailNotifEnabled {
notificationEmail := common.OptionMap["NotificationEmail"]
if notificationEmail == "" {
// 如果没有设置专门的通知邮箱,则尝试获取 RootUserEmail
if common.RootUserEmail == "" {
common.RootUserEmail = model.GetRootUserEmail()
}
notificationEmail = common.RootUserEmail
}
subject := "支付回调失败通知"
content := "一个支付回调未能成功处理,请检查系统日志获取更多信息。"
err := common.SendEmail(subject, notificationEmail, content)
if err != nil {
common.SysError(fmt.Sprintf("failed to send email notification: %s", err.Error()))
}
}
}
func notifyWxPusherForFail() {
wxNotifEnabled, _ := strconv.ParseBool(common.OptionMap["WxPusherNotificationsEnabled"])
if wxNotifEnabled {
subject := "支付回调失败通知"
content := "一个支付回调未能成功处理,请检查系统日志获取更多信息。"
err := SendWxPusherNotification(subject, content)
if err != nil {
common.SysError(fmt.Sprintf("无法发送WxPusher通知: %s", err))
}
}
}
func RequestAmount(c *gin.Context) {
var req AmountRequest
err := c.ShouldBindJSON(&req)
if err != nil {
c.JSON(200, gin.H{"message": "error", "data": "参数错误"})
return
}
if req.Amount < 1 {
c.JSON(200, gin.H{"message": "error", "data": "充值金额不能小于1"})
return
}
id := c.GetInt("id")
user, _ := model.GetUserById(id, false)
payMoney := GetAmount(float64(req.Amount), *user)
c.JSON(200, gin.H{"message": "success", "data": strconv.FormatFloat(payMoney, 'f', 2, 64)})
}