黄梓健 5 years ago
parent
commit
733071507d
  1. 3
      controllers/client/bully_screen.go
  2. 7
      controllers/client/good.go
  3. 70
      controllers/client/live.go
  4. 3
      controllers/client/reward.go
  5. 1
      models/live_red_envelope_rule.go
  6. 26
      models/user_order.go
  7. 91
      services/pay/order.go

3
controllers/client/bully_screen.go

@ -50,7 +50,8 @@ func (t *BullyScreenCtl) PaScreen() {
var res = make(map[string]interface{}, 0)
res["out_trade_no"] = ""
if activity.RehearsalId == 0 {
res, err = pay_service.UnifiedOrder("欧轩互动-霸屏支付", user.Openid, int64(amount*100), 1, user.Id, activityId)
res, err = pay_service.UnifiedOrder("欧轩互动-霸屏支付", user.Openid, int64(amount*100), 1, user.Id,
activityId, time.Now().Add(24*time.Hour).Unix())
t.CheckErr(err)
}

7
controllers/client/good.go

@ -200,8 +200,8 @@ func (t *GoodCtl) Order() {
}
}
res, err := pay_service.UnifiedOrder("欧轩互动-直播商品", user.Openid,
int64(price+int(option.PostFee*100)), 4, userId, activity.Id)
res, err := pay_service.UnifiedOrder("欧轩互动-直播商品", user.Openid, int64(price+int(option.PostFee*100)),
4, userId, activity.Id, time.Now().Add(30*time.Second).Unix())
if err != nil {
session.Rollback()
t.CheckErr(err)
@ -214,9 +214,6 @@ func (t *GoodCtl) Order() {
}
order := models.CustomerOrder{
IsDelete: false,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
OrderNo: fmt.Sprint(define.DefaultOrderNo + int(count)),
ActivityId: activity.Id,
AreaId: area.Id,

70
controllers/client/live.go

@ -80,6 +80,7 @@ func (t *LiveCtl) Like() {
exist, err := live.GetByActivityId(activityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "直播活动不存在")
t.JSON(map[string]interface{}{
"like": live.LikeNum,
"watch": live.WatchNum,
@ -118,50 +119,47 @@ func (t *LiveCtl) SendLiveRedPack() {
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
area := new(models.AreaStore)
exist, err = models.Get(area, areaId)
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
//area := new(models.AreaStore)
//exist, err = models.Get(area, areaId)
//t.CheckErr(err)
//t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
user := models.User{}
exist, err = models.Get(&user, userId)
t.CheckErr(err)
t.Assert(exist, code.MSG_USER_NOT_EXIST, "用户不存在")
res, err := pay_service.UnifiedOrder("欧轩互动-直播红包", user.Openid, int64(amount*100), 3, userId, activityId)
res, err := pay_service.UnifiedOrder("欧轩互动-直播红包", user.Openid, int64(amount*100),
3, userId, activityId, time.Now().Add(24*time.Hour).Unix())
t.CheckErr(err)
rule := new(models.LiveRedEnvelopeRule)
rule.OutTradeNo = res["out_trade_no"].(string)
rule.ActivityId = activityId
rule.RehearsalId = activity.RehearsalId
rule.AreaId = areaId
rule.UserId = userId
rule.Amount = amount
rule.Num = num
rule.Prompt = filter.Replace(prompt)
rule.IsDelete = false
rule.Status = 0
rule.UpdatedAt = time.Now()
rule.CreatedAt = time.Now()
_, err = models.Add(rule)
rule := models.LiveRedEnvelopeRule{
UserId: 0,
ActivityId: activityId,
AreaId: areaId,
RehearsalId: activity.RehearsalId,
Prompt: filter.Replace(prompt),
Amount: amount,
Num: num,
Status: 0,
}
_, err = models.Add(&rule)
t.CheckErr(err)
records := red_envelope_service.GenRedPack(int(amount*100), num)
for _, v := range records {
record := new(models.ShakeRedEnvelopeRecord)
record.ActivityId = activityId
record.RehearsalId = activity.RehearsalId
record.AreaId = area.Id
record.ShakeRedEnvelopeType = 1
record.ShakeRedEnvelopeRuleId = rule.Id
record.Name = user.Nickname + "发红包"
record.UserId = 0
record.IsDraw = -1 // 未被提现
record.Amount = utils.Float64CusDecimal(float64(v)/float64(100), 2)
record.CreatedAt = time.Now()
record.UpdatedAt = time.Now()
_, err = models.Add(record)
record := models.ShakeRedEnvelopeRecord{
ActivityId: activityId,
RehearsalId: activity.RehearsalId,
ShakeRedEnvelopeType: 1,
ShakeRedEnvelopeRuleId: rule.Id,
AreaId: areaId,
Name: user.Nickname + "发红包",
UserId: user.Id,
Amount: utils.Float64CusDecimal(float64(v)/float64(100), 2),
IsDraw: -1,
}
_, err = models.Add(&record)
t.CheckErr(err)
}
@ -198,10 +196,10 @@ func (t *LiveCtl) GetLiveRedPack() {
t.CheckErr(err)
t.Assert(row == 1, code.MSG_SHAKERB_RECORD_NOT_HIT, "红包被领完了")
//result, err := pay_service.SendRedPack("欧轩互动", user.Openid, rule.Prompt, "直播抢红包活动",
// "抢的多,赚得多", int(record.Amount*100), 1, 2)
//t.CheckErr(err)
//record.MchBillno = result.MchBillno
result, err := pay_service.SendRedPack("欧轩互动", user.Openid, rule.Prompt, "直播抢红包活动",
"抢的多,赚得多", int(record.Amount*100), 1, 2)
t.CheckErr(err)
record.MchBillno = result.MchBillno
record.IsDraw = 1
models.Update(record.Id, record, "mch_billno", "is_draw")
t.JSON(record)

3
controllers/client/reward.go

@ -56,7 +56,8 @@ func (t *RewardCtl) Reward() {
var res = make(map[string]interface{}, 0)
res["out_trade_no"] = ""
if activity.RehearsalId == 0 || _type == 1 { // 直播不用彩排
res, err = pay_service.UnifiedOrder("欧轩互动-打赏支付", user.Openid, int64(amount*100), 2, user.Id, activityId)
res, err = pay_service.UnifiedOrder("欧轩互动-打赏支付", user.Openid, int64(amount*100), 2,
user.Id, activityId, time.Now().Add(24*time.Hour).Unix())
t.CheckErr(err)
}

1
models/live_red_envelope_rule.go

@ -18,7 +18,6 @@ type LiveRedEnvelopeRule struct {
ActivityId int64 `json:"activity_id" xorm:"not null default 0 comment('互动id') INT(11)"`
AreaId int64 `json:"area_id" xorm:"not null default 0 comment('地区id') INT(11)"`
RehearsalId int64 `json:"rehearsal_id" xorm:"not null default 0 comment('彩排id') INT(11)"`
GroupId string `json:"group_id" xorm:"not null default '' comment('聊天室地址') VARCHAR(128)"`
Prompt string `json:"prompt" xorm:"not null default 0 comment('祝福语') VARCHAR(255)"`
Amount float64 `json:"amount" xorm:"not null default 0 comment('红包金额') DECIMAL(18)"`
Num int `json:"num" xorm:"not null default 0 comment('红包个数') INT(11)"`

26
models/user_order.go

@ -25,17 +25,13 @@ type UserOrder struct {
UserId int64 `json:"user_id" xorm:"not null default(0) comment('用户id') INT(11)"`
ActivityId int64 `json:"activity_id" xorm:"not null default(0) comment('活动id') INT(11)"`
TransactionId string `json:"transaction_id" xorm:"not null default('') comment('微信支付订单号') VARCHAR(32)"`
TimeStart string `json:"time_start" xorm:"not null default('') comment('交易起始时间') VARCHAR(14)"`
TimeExpire string `json:"time_expire" xorm:"not null default('') comment('交易结束时间') VARCHAR(14)"`
TimeEnd string `json:"time_end" xorm:"not null default('') comment('交易结算时间') VARCHAR(14)"`
ExpireAt int64 `json:"time_expire" xorm:"not null default('0') comment('交易过期') INT(20)"`
PrepayId string `json:"prepay_id" xorm:"not null default('') comment('预支付交易会话标识') VARCHAR(64)"`
Status int `json:"status" xorm:"not null default(0) comment('0尚未支付/支付中1支付成功2已撤销3转入退款4退款成功5支付失败6订单关闭7订单超时') TINYINT(1)"`
ErrMsg string `json:"err_msg" xorm:"not null default '' comment('出现错误') VARCHAR(255)"`
// 退款
SuccessTime time.Time `json:"success_time" xorm:"not null default '' comment('退款成功时间') VARCHAR(20)"`
RefundRecvAccount string `json:"refund_recv_account" xorm:"not null default '' comment('入账账号') VARCHAR(64)"`
RefundAccount string `json:"refund_account" xorm:"not null default '' comment('入账账号') VARCHAR(64)"`
RefundRecvAccount string `json:"refund_recv_account" xorm:"not null default '' comment('入账账号') VARCHAR(64)"`
RefundAccount string `json:"refund_account" xorm:"not null default '' comment('入账账号') VARCHAR(64)"`
}
func (t *UserOrder) TableName() string {
@ -54,30 +50,20 @@ func (t *UserOrder) GetByOutTradeNo(no string) (bool, error) {
return core.GetXormAuto().Where("is_delete=0 and out_trade_no=?", no).Get(t)
}
func (t *UserOrder) UpdateStatusById(id interface{}) (int64, error) {
return core.GetXormAuto().Where("id=? and is_delete=0", id).
Cols("time_end, transaction_id, status").Update(t)
}
func (t *UserOrder) UpdateStatusByOutTradeNo(outTradeNo interface{}, status int) (int64, error) {
t.Status = status
return core.GetXormAuto().Where("out_trade_no=? and is_delete=0", outTradeNo).
Cols("time_end, transaction_id, status").Update(t)
}
func (t *UserOrder) UpdateErrByOutTradeNo(outTradeNo interface{}) (int64, error) {
return core.GetXormAuto().Where("out_trade_no=? and is_delete=0", outTradeNo).
Cols("err_msg").Update(t)
Cols("status").Update(t)
}
func (t *UserOrder) UpdateRefundByOutTradeNo(outTradeNo interface{}) (int64, error) {
return core.GetXormAuto().Where("out_trade_no=?", outTradeNo).
Cols("success_time", "status", "refund_recv_account", "refund_account").Update(t)
Cols("status", "refund_recv_account", "refund_account").Update(t)
}
func GetUserOrdersByStatus(expire string, status ...int) ([]*UserOrder, error) {
orders := make([]*UserOrder, 0)
err := core.GetXormAuto().Where("is_delete=0 and time_expire <= ?", expire).
err := core.GetXormAuto().Where("is_delete=0 and expire_at <= ?", expire).
In("status", status).Desc("created_at").Find(&orders)
return orders, err
}

91
services/pay/order.go

@ -18,32 +18,26 @@ import (
)
func init() {
//go loopUnifiedOrder()
go loopUnifiedOrder()
}
var orderDelayQueue = make(chan *OrderDelayQueueParam, math.MaxInt8)
type OrderDelayQueueParam struct {
Order *models.UserOrder
First bool `json:"first"`
Expires int64 `json:"expires"`
Delay int `json:"delay"`
Order *models.UserOrder
First bool `json:"first"`
Delay int `json:"delay"`
}
func PutOrderDelayQueue(order *models.UserOrder, expires int64, delay int) {
if expires == 0 {
expires = time.Now().Add(12 * time.Hour).Unix() // 2 个小时
}
func PutOrderDelayQueue(order *models.UserOrder, delay int) {
if delay == 0 {
delay = 0
}
orderDelayQueue <- &OrderDelayQueueParam{
First: true,
Expires: expires,
Delay: delay,
Order: order,
First: true,
Delay: delay,
Order: order,
}
}
@ -54,12 +48,7 @@ func loopUnifiedOrder() {
}
for _, order := range orders {
expire, err := core2.ParseTime(order.TimeExpire)
if err != nil {
expire = time.Now().Add(12 * time.Hour)
}
PutOrderDelayQueue(order, expire.Add(12*time.Hour).Unix(), 0)
PutOrderDelayQueue(order, 0)
}
defer func() {
@ -76,7 +65,7 @@ func loopUnifiedOrder() {
if !ok {
panic("通道异常关闭")
}
if param.Expires <= time.Now().Unix() {
if param.Order.ExpireAt <= time.Now().Unix() {
if param.Order.Status == 0 {
order := new(models.UserOrder)
_, err = order.UpdateStatusByOutTradeNo(param.Order.OutTradeNo, 7)
@ -130,29 +119,26 @@ func loopUnifiedOrder() {
const CallbackOrderUrl = "https://api.ouxuanhudong.com/PcClient/common/WeChatOauthCtl/callbackOrder"
func UnifiedOrder(body, openid string, fee, goodType, userId, activityId int64) (map[string]interface{}, error) {
func UnifiedOrder(content, openId string, fee, goodType, userId, activityId, expireAt int64) (map[string]interface{}, error) {
client, err := Client()
if err != nil {
return nil, err
}
now := time.Now()
timeStart := core2.FormatTime(now)
timeExpire := core2.FormatTime(now.Add(12 * time.Hour))
outTradeNo := utils.RandomStr(32)
nonceStr := utils.RandomStr(32)
resp, err := pay.UnifiedOrder2(client, &pay.UnifiedOrderRequest{
Body: body,
OutTradeNo: outTradeNo,
TotalFee: fee,
NotifyURL: CallbackOrderUrl,
TradeType: "JSAPI",
DeviceInfo: "WEB",
NonceStr: nonceStr,
SignType: core2.SignType_MD5,
TimeStart: now,
OpenId: openid,
})
body := make(map[string]string, 0)
body["body"] = content
body["out_trade_no"] = outTradeNo
body["total_fee"] = fmt.Sprint(fee)
body["notify_url"] = CallbackOrderUrl
body["trade_type"] = "JSAPI"
body["device_info"] = "WEB"
body["nonce_str"] = nonceStr
body["sign_type"] = core2.SignType_MD5
body["open_id"] = openId
resp, err := pay.UnifiedOrder(client, body)
if err != nil {
return nil, err
}
@ -160,32 +146,28 @@ func UnifiedOrder(body, openid string, fee, goodType, userId, activityId int64)
// 记录这次订单
userOrder := new(models.UserOrder)
userOrder.DeviceInfo = "WEB"
userOrder.Body = body
userOrder.Body = content
userOrder.UserId = userId
userOrder.ActivityId = activityId
userOrder.FeeType = "CNY"
userOrder.GoodType = goodType
userOrder.OpenId = openid
userOrder.OpenId = openId
userOrder.OutTradeNo = outTradeNo
userOrder.TimeStart = timeStart
userOrder.TimeExpire = timeExpire
userOrder.ExpireAt = expireAt
userOrder.TotalFee = fee
userOrder.TradeType = "JSAPI"
userOrder.PrepayId = resp.PrepayId
userOrder.PrepayId = resp["prepay_id"]
userOrder.Status = 0
userOrder.IsDelete = false
userOrder.CreatedAt = time.Now()
userOrder.UpdatedAt = time.Now()
if _, err = models.Add(userOrder); err != nil {
return nil, err
}
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
//获取H5支付需要的paySign
pac := "prepay_id=" + resp.PrepayId
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
pac := "prepay_id=" + resp["prepay_id"]
paySign := core2.JsapiSign(client.AppId(), timestamp, nonceStr, pac, core2.SignType_MD5, ApiKey)
go PutOrderDelayQueue(userOrder, 0, 0)
go PutOrderDelayQueue(userOrder, 0)
return map[string]interface{}{
"appid": Appid,
"timestamp": timestamp,
@ -213,7 +195,7 @@ func ReOrder(outTradeNo string) (map[string]interface{}, error) {
//获取H5支付需要的paySign
pac := "prepay_id=" + userOrder.PrepayId
paySign := core2.JsapiSign(Appid, timestamp, nonceStr, pac, core2.SignType_MD5, ApiKey)
go PutOrderDelayQueue(userOrder, 0, 0)
go PutOrderDelayQueue(userOrder, 0)
return map[string]interface{}{
"appid": Appid,
"timestamp": timestamp,
@ -283,7 +265,6 @@ func NotifyOrder(w io.Reader) (order *models.UserOrder, err error) {
if res.ResultCode == CODE_SUCCESS && res.TradeType == CODE_TRADE_SUCCESS {
userOrder := new(models.UserOrder)
userOrder.TimeEnd = res.TimeEnd
userOrder.TransactionId = res.TransactionId
userOrder.Status = 1
_, err = userOrder.UpdateStatusByOutTradeNo(res.OutTradeNo, 1)
@ -337,13 +318,10 @@ func OrderQuery(outTradeNo string) (*OrderQueryResult, error) {
})
if err != nil {
userOrder.ErrMsg = err.Error()
userOrder.UpdateErrByOutTradeNo(outTradeNo)
return nil, err
}
userOrder.TransactionId = res.TransactionId
userOrder.TimeEnd = core2.FormatTime(res.TimeEnd)
switch res.TradeState {
case CODE_TRADE_SUCCESS:
userOrder.Status = 1
@ -413,8 +391,6 @@ func Refund(reason, outTradeNo string) (*pay.RefundResponse, error) {
})
//
if err != nil {
userOrder.ErrMsg = err.Error()
userOrder.UpdateErrByOutTradeNo(outTradeNo)
return nil, err
}
userOrder.Status = 3
@ -423,7 +399,7 @@ func Refund(reason, outTradeNo string) (*pay.RefundResponse, error) {
return nil, err
}
PutOrderDelayQueue(userOrder, 0, 0) // 退款查询
PutOrderDelayQueue(userOrder, 0) // 退款查询
return res, nil
}
@ -450,14 +426,11 @@ func QueryRefund(outTradeNo string) (*QueryRefundResult, error) {
})
//请求申请退款
if err != nil {
userOrder.ErrMsg = err.Error()
userOrder.UpdateErrByOutTradeNo(outTradeNo)
return nil, err
}
userOrder.RefundAccount = res.RefundList[0].RefundAccount
userOrder.RefundRecvAccount = res.RefundList[0].RefundRecvAccout
userOrder.SuccessTime = res.RefundList[0].RefundSuccessTime
userOrder.Status = 4
_, err = userOrder.UpdateRefundByOutTradeNo(outTradeNo)
if err != nil {

Loading…
Cancel
Save