xingzai 1 tahun lalu
induk
melakukan
e0202debb9
6 mengubah file dengan 286 tambahan dan 11 penghapusan
  1. 22 4
      controllers/wechat.go
  2. 2 0
      models/db.go
  3. 8 0
      models/order/order.go
  4. 135 0
      models/order/order_user_card.go
  5. 61 1
      services/order.go
  6. 58 6
      services/wx_pay.go

+ 22 - 4
controllers/wechat.go

@@ -446,14 +446,32 @@ func (this *WechatController) Getuserphonenumber() {
 // @Success 200 {object} models.WxLoginResp
 // @router /wxpay/notify [post]
 func (this *WechatCommonController) WxpayNotify() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
 	body := this.Ctx.Input.RequestBody
-	utils.FileLog.Info("wechat notify:" + string(body))
+	//utils.FileLog.Info("wechat notify:" + string(body))
 	item := new(models.CygxShanghaiCompanyLog)
 	item.CreateTime = time.Now()
 	//item.Body = jsonCompany
 	item.Result = string(body)
-
-	fmt.Println(item.Result)
-
 	go models.AddCygxShanghaiCompanyLog(item)
+	itemNotify := services.WxDecodeNotify(body)
+	if itemNotify.OutTradeNo != "" {
+		go services.HandleOrderHandle(itemNotify)
+	}
+	br.Data = itemNotify
+	br.Ret = 200
+	br.Success = true
+
 }
+
+//// 使用gin的外部接口
+//func (orderApi *OrderApi) NotifyOrder(c *gin.Context) {
+//	body,_ := ioutil.ReadAll(c.Request.Body)
+//	b,s := orderService.DecodeNotify(body)
+//	log.Println(b,s)
+//	response.OkWithMessage("收到", c)
+//}

+ 2 - 0
models/db.go

@@ -193,5 +193,7 @@ func initOrder() {
 		new(order.CygxUserBusinessCard), //用户上传名片
 		new(order.CygxOrder),            //订单表
 		new(order.CygxOrderAction),      //订单操表
+		new(order.CygxOrderUserCard),    //用户持卡表
+		new(order.CygxOrderUserCardLog), //用户持卡日志表
 	)
 }

+ 8 - 0
models/order/order.go

@@ -204,6 +204,14 @@ func GetCygxOrderList(condition string, pars []interface{}, startSize, pageSize
 	return
 }
 
+// 根据订单编号获取订单详情
+func GetCygxOrderDetailByOrderCode(orderCode string) (item *CygxOrder, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM cygx_order WHERE order_code = ? `
+	err = o.Raw(sql, orderCode).QueryRow(&item)
+	return
+}
+
 // 获取数量
 func GetCygxOrderCount(condition string, pars []interface{}) (count int, err error) {
 	o := orm.NewOrm()

+ 135 - 0
models/order/order_user_card.go

@@ -0,0 +1,135 @@
+package order
+
+import (
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// 用户持卡表 CygxOrderUserCard 结构体对应 cygx_order_user_card 数据表
+type CygxOrderUserCard struct {
+	UserCardId       int       `orm:"column(user_card_id);pk";comment:"订单id"`
+	OrderCode        string    `comment:"订单编号"`
+	UserId           int       `comment:"用户ID"`
+	Mobile           string    `comment:"手机号"`
+	Email            string    `comment:"邮箱"`
+	CompanyId        int       `comment:"公司ID"`
+	CompanyName      string    `comment:"公司名称"`
+	RealName         string    `comment:"用户实际名称"`
+	SellerName       string    `comment:"所属销售"`
+	CreateTime       time.Time `comment:"创建时间"`
+	ModifyTime       time.Time `comment:"修改时间"`
+	RegisterPlatform int       `comment:"来源"`
+	CardType         string    `comment:"会员卡类型"`
+	StartDate        time.Time `comment:"开始时间"`
+	EndDate          time.Time `comment:"结束时间"`
+	IsSuspend        int       `comment:"是否暂停"`
+}
+
+// 用户持卡日志表 CygxOrderUserCardLog 结构体对应 cygx_order_user_card_log 数据表
+type CygxOrderUserCardLog struct {
+	UserCardId       int       `orm:"column(user_card_log_id);pk";comment:"订单id"`
+	OrderCode        string    `comment:"订单编号"`
+	UserId           int       `comment:"用户ID"`
+	Mobile           string    `comment:"手机号"`
+	Email            string    `comment:"邮箱"`
+	CompanyId        int       `comment:"公司ID"`
+	CompanyName      string    `comment:"公司名称"`
+	RealName         string    `comment:"用户实际名称"`
+	SellerName       string    `comment:"所属销售"`
+	CreateTime       time.Time `comment:"创建时间"`
+	ModifyTime       time.Time `comment:"修改时间"`
+	RegisterPlatform int       `comment:"来源"`
+	CardType         string    `comment:"会员卡类型"`
+	StartDate        time.Time `comment:"开始时间"`
+	EndDate          time.Time `comment:"结束时间"`
+	IsSuspend        int       `comment:"是否暂停"`
+}
+
+// 添加
+func AddCygxOrderUserCard(item *CygxOrderUserCard, itemOrder *CygxOrder) (err error) {
+	o, err := orm.NewOrm().Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		fmt.Println(err)
+		if err == nil {
+			o.Commit()
+		} else {
+			o.Rollback()
+		}
+	}()
+
+	itemOrderAction := new(CygxOrderAction)
+
+	itemOrderAction.Action = "微信小程序已支付"
+	itemOrderAction.OrderStatus = 2
+	itemOrderAction.OrderStatusText = "已支付"
+	itemOrderAction.OrderCode = item.OrderCode
+	itemOrderAction.UserId = item.UserId
+	itemOrderAction.Mobile = item.Mobile
+	itemOrderAction.Email = item.Email
+	itemOrderAction.CompanyId = item.CompanyId
+	itemOrderAction.CompanyName = item.CompanyName
+	itemOrderAction.RealName = item.RealName
+	itemOrderAction.SellerName = item.SellerName
+	itemOrderAction.CreateTime = time.Now()
+	itemOrderAction.ModifyTime = time.Now()
+	itemOrderAction.RegisterPlatform = item.RegisterPlatform
+
+	updateParams := make(map[string]interface{})
+	updateParams["PayTime"] = itemOrder.PayTime
+	updateParams["PayMoney"] = itemOrder.PayMoney
+	updateParams["OrderStatus"] = itemOrder.OrderStatus
+	updateParams["ModifyTime"] = item.ModifyTime
+	ptrStructOrTableName := "cygx_order"
+	whereParam := map[string]interface{}{"order_code": itemOrder.OrderCode}
+	qs := o.QueryTable(ptrStructOrTableName)
+	for expr, exprV := range whereParam {
+		qs = qs.Filter(expr, exprV)
+	}
+	_, err = qs.Update(updateParams) // 修改订单状态
+	if err != nil {
+		return
+	}
+
+	_, err = o.Insert(itemOrderAction) // 写入订单操作信息
+	if err != nil {
+		return
+	}
+
+	sql := ` DELETE FROM cygx_order_user_card  WHERE mobile=? ` // 删除原有的持卡信息
+	_, err = o.Raw(sql, item.Mobile).Exec()
+	if err != nil {
+		return
+	}
+
+	itemLog := new(CygxOrderUserCardLog)
+	itemLog.OrderCode = item.OrderCode
+	itemLog.UserId = item.UserId
+	itemLog.Mobile = item.Mobile
+	itemLog.Email = item.Email
+	itemLog.CompanyId = item.CompanyId
+	itemLog.CompanyName = item.CompanyName
+	itemLog.RealName = item.RealName
+	itemLog.SellerName = item.SellerName
+	itemLog.CreateTime = time.Now()
+	itemLog.ModifyTime = time.Now()
+	itemLog.RegisterPlatform = item.RegisterPlatform
+	itemLog.CardType = item.CardType
+	itemLog.StartDate = item.StartDate
+	itemLog.EndDate = item.EndDate
+	itemLog.IsSuspend = item.IsSuspend
+
+	_, err = o.Insert(item) //写入用户持卡表
+	if err != nil {
+		return
+	}
+
+	_, err = o.Insert(itemLog) // 写入用户持卡日志表
+	if err != nil {
+		return
+	}
+	return
+}

+ 61 - 1
services/order.go

@@ -77,7 +77,7 @@ func GetHaverEquallyOrderByUser10Min(userId, goodsId int) (orderCode string) {
 	}()
 	var condition string
 	var pars []interface{}
-	endTime := time.Now().Add(-15 * time.Minute)
+	endTime := time.Now().Add(-10 * time.Minute)
 	condition = ` AND  user_id = ? AND  goods_id = ? AND create_time > ?  ORDER BY order_id DESC  `
 	pars = append(pars, userId, goodsId, endTime)
 	orderList, e := order.GetCygxOrderList(condition, pars, 0, 1)
@@ -94,3 +94,63 @@ func GetHaverEquallyOrderByUser10Min(userId, goodsId int) (orderCode string) {
 	}
 	return
 }
+
+// 处理订单回调
+func HandleOrderHandle(itemCallback *WechatPayCallback) {
+	var err error
+	defer func() {
+		if err != nil {
+			fmt.Println(err)
+			go utils.SendAlarmMsg(fmt.Sprint("处理订单回调信息失败 HandleOrderHandle, err:", err.Error()), 2)
+		}
+	}()
+	outTradeNo := itemCallback.OutTradeNo
+	orderDetail, e := order.GetCygxOrderDetailByOrderCode(outTradeNo)
+	if e != nil {
+		err = errors.New("GetCygxOrderDetailByOrderCode, Err: " + e.Error())
+		return
+	}
+	itemOrder := new(order.CygxOrder)
+	itemOrder.PayTime = itemCallback.SuccessTime
+	itemOrder.PayMoney = float64(itemCallback.Amount.PayerTotal / 100) // 金额分转换处理
+	itemOrder.OrderStatus = 2
+	//文章处理逻辑
+	if orderDetail.Source == utils.CYGX_OBJ_ARTICLE {
+
+		itemUserCard := new(order.CygxOrderUserCard)
+		itemUserCard.OrderCode = orderDetail.OrderCode
+		itemUserCard.UserId = orderDetail.UserId
+		itemUserCard.Mobile = orderDetail.Mobile
+		itemUserCard.Email = orderDetail.Email
+		itemUserCard.CompanyId = orderDetail.CompanyId
+		itemUserCard.CompanyName = orderDetail.CompanyName
+		itemUserCard.RealName = orderDetail.RealName
+		itemUserCard.SellerName = orderDetail.SellerName
+		itemUserCard.CreateTime = time.Now()
+		itemUserCard.ModifyTime = time.Now()
+		itemUserCard.RegisterPlatform = orderDetail.RegisterPlatform
+
+		if orderDetail.GoodsId == 1 {
+			itemUserCard.StartDate = itemOrder.PayTime
+			itemUserCard.EndDate = itemOrder.PayTime.AddDate(0, 0, 1)
+			itemUserCard.CardType = "日卡"
+		} else {
+			now := time.Now()
+			itemUserCard.StartDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
+			itemUserCard.EndDate = itemUserCard.StartDate.AddDate(0, 1, 0)
+			itemUserCard.CardType = "月卡"
+		}
+		e = order.AddCygxOrderUserCard(itemUserCard, orderDetail)
+		if e != nil {
+			err = errors.New("AddCygxOrderUserCard, Err: " + e.Error())
+			return
+		}
+	} else if orderDetail.Source == utils.CYGX_OBJ_ACTIVITY {
+
+	}
+	fmt.Println(orderDetail.Source)
+	//var condition string
+	//var pars []interface{}
+
+	return
+}

+ 58 - 6
services/wx_pay.go

@@ -2,6 +2,7 @@ package services
 
 import (
 	"context"
+	"encoding/json"
 	"errors"
 	"fmt"
 	"github.com/wechatpay-apiv3/wechatpay-go/core"
@@ -12,6 +13,7 @@ import (
 	"hongze/hongze_mfyx/models/order"
 	"hongze/hongze_mfyx/utils"
 	"log"
+	"time"
 )
 
 const (
@@ -21,11 +23,7 @@ const (
 	MchAPIv3Key                = "W1tbnzQrzQ7yRRNuQCIHjis8dgdasKVX"
 )
 
-//func init() {
-//	ExampleJsapiApiServicePrepay()
-//}
-
-// 获取加解密处理
+// 微信商户建立连接
 func getWechatClient() (context.Context, *core.Client, error) {
 	// 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名
 	mchPrivateKey, err := payUtils.LoadPrivateKeyWithPath(MchPKFileName)
@@ -84,7 +82,6 @@ func ExampleJsapiApiServicePrepay(orderDetail *order.CygxOrder, unionId string)
 			},
 		},
 	)
-
 	JsapiApiResp.PrepayId = *resp.PrepayId
 	JsapiApiResp.Appid = *resp.Appid
 	JsapiApiResp.TimeStamp = *resp.TimeStamp
@@ -94,3 +91,58 @@ func ExampleJsapiApiServicePrepay(orderDetail *order.CygxOrder, unionId string)
 	JsapiApiResp.PaySign = *resp.PaySign
 	return
 }
+
+type WechatPayCallback struct {
+	MchID          string    `json:"mchid"`
+	AppID          string    `json:"appid"`
+	OutTradeNo     string    `json:"out_trade_no"`
+	TransactionID  string    `json:"transaction_id"`
+	TradeType      string    `json:"trade_type"`
+	TradeState     string    `json:"trade_state"`
+	TradeStateDesc string    `json:"trade_state_desc"`
+	BankType       string    `json:"bank_type"`
+	Attach         string    `json:"attach"`
+	SuccessTime    time.Time `json:"success_time"`
+	Payer          struct {
+		OpenID string `json:"openid"`
+	} `json:"payer"`
+	Amount struct {
+		Total         int    `json:"total"`
+		PayerTotal    int    `json:"payer_total"`
+		Currency      string `json:"currency"`
+		PayerCurrency string `json:"payer_currency"`
+	} `json:"amount"`
+}
+
+// 微信支付回调内容解密
+func WxDecodeNotify(body []byte) (wechatPayCallback *WechatPayCallback) {
+	var err error
+	defer func() {
+		if err != nil {
+			fmt.Println(err)
+			go utils.SendAlarmMsg(fmt.Sprint("微信支付回调内容解密失败 WxDecodeNotify, err:", err.Error()), 2)
+		}
+	}()
+
+	var prepaymap map[string]interface{}
+	_ = json.Unmarshal(body, &prepaymap)
+
+	var prepaymap2 = prepaymap["resource"].(map[string]interface{})
+	nonce := prepaymap2["nonce"].(string)
+	associatedData := prepaymap2["associated_data"].(string)
+	ciphertext := prepaymap2["ciphertext"].(string)
+
+	tx, e := payUtils.DecryptAES256GCM(MchAPIv3Key, associatedData, nonce, ciphertext)
+	if e != nil {
+		log.Println(err)
+		return
+	}
+	if e != nil {
+		err = errors.New("DecryptAES256GCM, Err: " + e.Error())
+		return
+	}
+	var datamap *WechatPayCallback
+	_ = json.Unmarshal([]byte(tx), &datamap)
+	wechatPayCallback = datamap
+	return
+}