智慧食堂
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

svc_pay.go 22 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. package svc
  2. import (
  3. "applet/app/customer/enum"
  4. "applet/app/customer/md"
  5. "applet/app/db"
  6. "applet/app/db/model"
  7. enum2 "applet/app/enum"
  8. svc3 "applet/app/svc"
  9. "applet/app/utils"
  10. "applet/app/utils/logx"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "github.com/gin-gonic/gin"
  15. "github.com/wechatpay-apiv3/wechatpay-go/core"
  16. "github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/jsapi"
  17. jsapi2 "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
  18. utils2 "github.com/wechatpay-apiv3/wechatpay-go/utils"
  19. "io/ioutil"
  20. "math"
  21. "net/url"
  22. "strconv"
  23. "time"
  24. )
  25. func BuyPackageForAli(c *gin.Context, req md.BuyPackageReq) (outTradeNo, tradeNo, total string, err error) {
  26. user := GetUser(c)
  27. session := db.Db.NewSession()
  28. defer session.Close()
  29. session.Begin()
  30. if err != nil {
  31. _ = session.Rollback()
  32. return
  33. }
  34. //1、判断是否为教师
  35. isTeacher := false
  36. userIdentityDb := db.UserIdentityDb{}
  37. userIdentityDb.Set(0)
  38. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  39. if err != nil {
  40. return
  41. }
  42. if userIdentity == nil {
  43. err = errors.New("未查询到对应身份记录")
  44. return
  45. }
  46. if userIdentity.Identity == enum2.UserIdentityForCentralKitchenForTeacher {
  47. isTeacher = true
  48. }
  49. //2、计算数据(1:按学期购买 2:按月购买 3:按天购买 4:补餐)
  50. var totalPrice float64
  51. var data []*model.CentralKitchenForSchoolUserWithDay
  52. if req.Kind == 1 {
  53. totalPrice, data, err = CalcBySchoolTerm(user.Id, isTeacher, req)
  54. if err != nil {
  55. return
  56. }
  57. }
  58. if req.Kind == 2 {
  59. totalPrice, data, err = CalcByMonth(user.Id, isTeacher, req)
  60. if err != nil {
  61. return
  62. }
  63. }
  64. if req.Kind == 3 {
  65. totalPrice, data, err = CalcByDay(user.Id, isTeacher, req)
  66. if err != nil {
  67. return
  68. }
  69. }
  70. if req.Kind == 4 {
  71. totalPrice, data, err = CalcSupplementaryByDay(user.Id, isTeacher, req)
  72. if err != nil {
  73. return
  74. }
  75. }
  76. total = utils.Float64ToStr(totalPrice)
  77. //3、生成订单号
  78. outTradeNo = utils.OrderUUID(user.Id)
  79. //4、请求 alipay.trade.create(统一收单交易创建接口)
  80. sysCfgDb := db.SysCfgDb{}
  81. sysCfgDb.Set()
  82. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken, enum2.JsapiPayNotifyUrl)
  83. err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{
  84. Config: struct {
  85. PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"`
  86. PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"`
  87. PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"`
  88. }{
  89. PayAliAppId: sysCfg[enum2.OpenAlipayAppid],
  90. PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey],
  91. PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey],
  92. },
  93. OpAppId: sysCfg[enum2.OpenAppletAppid],
  94. BuyerId: user.UserId,
  95. TotalAmount: total,
  96. OutTradeNo: outTradeNo,
  97. Subject: "购买食堂套餐",
  98. AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken],
  99. NotifyUrl: sysCfg[enum2.JsapiPayNotifyUrl],
  100. })
  101. if err != nil {
  102. return
  103. }
  104. //5、插入订单记录
  105. now := time.Now()
  106. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  107. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  108. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{
  109. EnterpriseId: req.EnterpriseId,
  110. Uid: user.Id,
  111. UserIdentityId: req.UserIdentityId,
  112. UserIdentityName: userIdentity.Name,
  113. TotalPrice: total,
  114. Kind: req.Kind,
  115. OutTradeNo: outTradeNo,
  116. TradeNo: resp.TradeNo,
  117. State: enum2.CentralKitchenForSchoolPackageOrdStateForWait,
  118. OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait,
  119. ReqContent: string(utils.Serialize(req)),
  120. WithDayData: string(utils.Serialize(data)),
  121. PayWay: enum.PayWayForAli,
  122. CreateAt: now.Format("2006-01-02 15:04:05"),
  123. UpdateAt: now.Format("2006-01-02 15:04:05"),
  124. })
  125. if err != nil {
  126. _ = session.Rollback()
  127. return
  128. }
  129. session.Commit()
  130. tradeNo = resp.TradeNo
  131. return
  132. }
  133. func BuyPackageForWx(c *gin.Context, req md.BuyPackageReq) (outTradeNo, total string, resp *jsapi2.PrepayWithRequestPaymentResponse, err error) {
  134. user := GetUser(c)
  135. session := db.Db.NewSession()
  136. defer session.Close()
  137. session.Begin()
  138. if err != nil {
  139. _ = session.Rollback()
  140. return
  141. }
  142. //1、判断是否为教师
  143. isTeacher := false
  144. userIdentityDb := db.UserIdentityDb{}
  145. userIdentityDb.Set(0)
  146. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  147. if err != nil {
  148. return
  149. }
  150. if userIdentity == nil {
  151. err = errors.New("未查询到对应身份记录")
  152. return
  153. }
  154. if userIdentity.Identity == enum2.UserIdentityForCentralKitchenForTeacher {
  155. isTeacher = true
  156. }
  157. //2、计算数据(1:按学期购买 2:按月购买 3:按天购买 4:补餐)
  158. var totalPrice float64
  159. var data []*model.CentralKitchenForSchoolUserWithDay
  160. if req.Kind == 1 {
  161. totalPrice, data, err = CalcBySchoolTerm(user.Id, isTeacher, req)
  162. if err != nil {
  163. return
  164. }
  165. }
  166. if req.Kind == 2 {
  167. totalPrice, data, err = CalcByMonth(user.Id, isTeacher, req)
  168. if err != nil {
  169. return
  170. }
  171. }
  172. if req.Kind == 3 {
  173. totalPrice, data, err = CalcByDay(user.Id, isTeacher, req)
  174. if err != nil {
  175. return
  176. }
  177. }
  178. if req.Kind == 4 {
  179. totalPrice, data, err = CalcSupplementaryByDay(user.Id, isTeacher, req)
  180. if err != nil {
  181. return
  182. }
  183. }
  184. total = utils.Float64ToStr(totalPrice)
  185. //3、生成订单号
  186. outTradeNo = utils.OrderUUID(user.Id)
  187. //4、请求 /v3/pay/partner/transactions/jsapi (生成预支付交易单)
  188. sysCfgDb := db.SysCfgDb{}
  189. sysCfgDb.Set()
  190. client, err := svc3.NewWxPayClient(c)
  191. if err != nil {
  192. return
  193. }
  194. wxSvc := jsapi.JsapiApiService{Client: client}
  195. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.WxAppletAppId, enum2.WxSpAppId, enum2.WxSpMchId, enum2.WxAppletAppId, enum2.WxMchId, enum2.WxJsapiPayNotifyUrl)
  196. fmt.Println(int64(math.Round(totalPrice * 100)))
  197. result, _, err := wxSvc.Prepay(c,
  198. jsapi.PrepayRequest{
  199. SpAppid: core.String(sysCfg[enum2.WxSpAppId]),
  200. SpMchid: core.String(sysCfg[enum2.WxSpMchId]),
  201. SubAppid: core.String(sysCfg[enum2.WxAppletAppId]),
  202. SubMchid: core.String(sysCfg[enum2.WxMchId]),
  203. Description: core.String("购买食堂套餐"),
  204. OutTradeNo: core.String(outTradeNo),
  205. TimeExpire: core.Time(time.Now().Add(30 * time.Minute)),
  206. //Attach: core.String("自定义数据说明"),
  207. NotifyUrl: core.String(sysCfg[enum2.WxJsapiPayNotifyUrl]),
  208. Amount: &jsapi.Amount{
  209. Currency: core.String("CNY"),
  210. Total: core.Int64(int64(math.Round(totalPrice * 100))),
  211. },
  212. Payer: &jsapi.Payer{
  213. //SpOpenid: core.String("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"),
  214. SubOpenid: core.String(user.OpenId),
  215. },
  216. },
  217. )
  218. fmt.Println(">>>>>>>>>>>", core.Int64(utils.StrToInt64(total)*100))
  219. if err != nil {
  220. _ = session.Rollback()
  221. return
  222. }
  223. //5、插入订单记录
  224. now := time.Now()
  225. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  226. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  227. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{
  228. EnterpriseId: req.EnterpriseId,
  229. Uid: user.Id,
  230. UserIdentityId: req.UserIdentityId,
  231. UserIdentityName: userIdentity.Name,
  232. TotalPrice: total,
  233. Kind: req.Kind,
  234. OutTradeNo: outTradeNo,
  235. TradeNo: "",
  236. State: enum2.CentralKitchenForSchoolPackageOrdStateForWait,
  237. OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait,
  238. ReqContent: string(utils.Serialize(req)),
  239. WithDayData: string(utils.Serialize(data)),
  240. PayWay: enum.PayWayForWx,
  241. PrepayId: *result.PrepayId,
  242. CreateAt: now.Format("2006-01-02 15:04:05"),
  243. UpdateAt: now.Format("2006-01-02 15:04:05"),
  244. })
  245. if err != nil {
  246. _ = session.Rollback()
  247. return
  248. }
  249. session.Commit()
  250. //prepayId = *resp.PrepayId
  251. resp = new(jsapi2.PrepayWithRequestPaymentResponse)
  252. resp.PrepayId = result.PrepayId
  253. resp.SignType = core.String("RSA")
  254. appid := sysCfg[enum2.WxAppletAppId]
  255. resp.Appid = &appid
  256. resp.TimeStamp = core.String(strconv.FormatInt(time.Now().Unix(), 10))
  257. nonce, err := utils2.GenerateNonce()
  258. if err != nil {
  259. _ = session.Rollback()
  260. return
  261. }
  262. resp.NonceStr = core.String(nonce)
  263. resp.Package = core.String("prepay_id=" + *result.PrepayId)
  264. message := fmt.Sprintf("%s\n%s\n%s\n%s\n", *resp.Appid, *resp.TimeStamp, *resp.NonceStr, *resp.Package)
  265. signatureResult, err := wxSvc.Client.Sign(c, message)
  266. if err != nil {
  267. _ = session.Rollback()
  268. return
  269. }
  270. resp.PaySign = core.String(signatureResult.Signature)
  271. return
  272. }
  273. func NursingHomeBuyPackageReq(c *gin.Context, req md.NursingHomeBuyPackageReq) (outTradeNo, tradeNo, total string, err error) {
  274. user := GetUser(c)
  275. session := db.Db.NewSession()
  276. defer session.Close()
  277. session.Begin()
  278. if err != nil {
  279. _ = session.Rollback()
  280. return
  281. }
  282. userIdentityDb := db.UserIdentityDb{}
  283. userIdentityDb.Set(0)
  284. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  285. if err != nil {
  286. return
  287. }
  288. if userIdentity == nil {
  289. err = errors.New("未查询到对应身份记录")
  290. return
  291. }
  292. //1、计算数据(1:按年购买 2:按月购买 3:按天购买 4:补餐)
  293. var totalPrice float64
  294. var data []*model.NursingHomeUserWithDay
  295. if req.Kind == 1 {
  296. totalPrice, data, err = CalcByYearForNursingHome(user.Id, req)
  297. if err != nil {
  298. return
  299. }
  300. }
  301. if req.Kind == 2 {
  302. totalPrice, data, err = CalcByMonthForNursingHome(user.Id, req)
  303. if err != nil {
  304. return
  305. }
  306. }
  307. if req.Kind == 3 {
  308. totalPrice, data, err = CalcByDayForNursingHome(user.Id, req)
  309. if err != nil {
  310. return
  311. }
  312. }
  313. if req.Kind == 4 {
  314. totalPrice, data, err = CalcByDayForNursingHome(user.Id, req)
  315. if err != nil {
  316. return
  317. }
  318. }
  319. total = utils.Float64ToStr(totalPrice)
  320. //3、生成订单号
  321. outTradeNo = utils.OrderUUID(user.Id)
  322. //4、请求 alipay.trade.create(统一收单交易创建接口)
  323. sysCfgDb := db.SysCfgDb{}
  324. sysCfgDb.Set()
  325. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken)
  326. err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{
  327. Config: struct {
  328. PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"`
  329. PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"`
  330. PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"`
  331. }{
  332. PayAliAppId: sysCfg[enum2.OpenAlipayAppid],
  333. PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey],
  334. PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey],
  335. },
  336. OpAppId: sysCfg[enum2.OpenAppletAppid],
  337. BuyerId: user.UserId,
  338. TotalAmount: total,
  339. OutTradeNo: outTradeNo,
  340. Subject: "购买食堂套餐",
  341. AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken],
  342. })
  343. if err != nil {
  344. return
  345. }
  346. //5、插入订单记录
  347. now := time.Now()
  348. NursingHomePackageOrd := db.NursingHomePackageOrd{}
  349. NursingHomePackageOrd.Set(outTradeNo)
  350. _, err = NursingHomePackageOrd.NursingHomePackageOrdInsertBySession(session, &model.NursingHomePackageOrd{
  351. EnterpriseId: req.EnterpriseId,
  352. Uid: user.Id,
  353. UserIdentityId: req.UserIdentityId,
  354. UserIdentityName: userIdentity.Name,
  355. TotalPrice: total,
  356. Kind: req.Kind,
  357. OutTradeNo: outTradeNo,
  358. TradeNo: resp.TradeNo,
  359. State: enum2.NursingHomePackageOrdStateForWait,
  360. OrdState: enum2.NursingHomePackageOrdOrdStateForWait,
  361. ReqContent: string(utils.Serialize(req)),
  362. WithDayData: string(utils.Serialize(data)),
  363. CreateAt: now.Format("2006-01-02 15:04:05"),
  364. UpdateAt: now.Format("2006-01-02 15:04:05"),
  365. })
  366. if err != nil {
  367. _ = session.Rollback()
  368. return
  369. }
  370. session.Commit()
  371. tradeNo = resp.TradeNo
  372. return
  373. }
  374. func DealCentralKitchenForSchoolOrderCallBack(outTradeNo, tradeStatus string) (state int, err error) {
  375. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  376. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  377. ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd()
  378. if err != nil {
  379. return
  380. }
  381. if ord == nil {
  382. err = errors.New("未查询到对应订单记录")
  383. return
  384. }
  385. if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait {
  386. if tradeStatus == "TRADE_CLOSED" {
  387. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail
  388. }
  389. if tradeStatus == "TRADE_SUCCESS" {
  390. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess
  391. ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess
  392. //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day`
  393. var data []*model.CentralKitchenForSchoolUserWithDay
  394. err = json.Unmarshal([]byte(ord.WithDayData), &data)
  395. if err != nil {
  396. return
  397. }
  398. var hasMonths = map[string]map[string]interface{}{}
  399. var hasKinds = map[string]map[string]string{}
  400. var hasTotalPrice = map[string]map[string]float64{}
  401. for _, v := range data {
  402. date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local)
  403. if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil {
  404. hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{})
  405. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  406. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  407. } else {
  408. startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local)
  409. if startTime.After(date) {
  410. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  411. }
  412. endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local)
  413. if endTime.Before(date) {
  414. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  415. }
  416. }
  417. if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil {
  418. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64)
  419. }
  420. if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil {
  421. hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string)
  422. }
  423. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month())
  424. hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind)
  425. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount)
  426. v.OrdNo = outTradeNo
  427. }
  428. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  429. centralKitchenForSchoolUserWithDayDb.Set(0)
  430. _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data)
  431. if err != nil {
  432. return
  433. }
  434. //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve`
  435. centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{}
  436. centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo)
  437. for k, v := range hasMonths {
  438. for _, v1 := range hasKinds[k] {
  439. _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{
  440. EnterpriseId: ord.EnterpriseId,
  441. Uid: ord.Uid,
  442. UserIdentityName: ord.UserIdentityName,
  443. UserIdentityId: ord.UserIdentityId,
  444. Kind: utils.StrToInt(v1),
  445. OutTradeNo: ord.OutTradeNo,
  446. ReserveMonth: utils.AnyToString(v["month"]),
  447. MealTimeStart: utils.AnyToString(v["meal_time_start"]),
  448. MealTimeEnd: utils.AnyToString(v["meal_time_end"]),
  449. TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]),
  450. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  451. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  452. })
  453. if err != nil {
  454. return
  455. }
  456. }
  457. }
  458. }
  459. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state")
  460. if err != nil {
  461. return
  462. }
  463. }
  464. state = ord.State
  465. return
  466. }
  467. func DealCentralKitchenForSchoolOrderCallBackForWx(outTradeNo, transactionId, tradeStatus string) (state int, err error) {
  468. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  469. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  470. ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd()
  471. if err != nil {
  472. return
  473. }
  474. if ord == nil {
  475. err = errors.New("未查询到对应订单记录")
  476. return
  477. }
  478. if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait {
  479. if tradeStatus == "CLOSED" || tradeStatus == "PAYERROR" {
  480. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail
  481. }
  482. if tradeStatus == "SUCCESS" {
  483. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess
  484. ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess
  485. ord.TradeNo = transactionId
  486. //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day`
  487. var data []*model.CentralKitchenForSchoolUserWithDay
  488. err = json.Unmarshal([]byte(ord.WithDayData), &data)
  489. if err != nil {
  490. return
  491. }
  492. var hasMonths = map[string]map[string]interface{}{}
  493. var hasKinds = map[string]map[string]string{}
  494. var hasTotalPrice = map[string]map[string]float64{}
  495. for _, v := range data {
  496. date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local)
  497. if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil {
  498. hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{})
  499. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  500. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  501. } else {
  502. startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local)
  503. if startTime.After(date) {
  504. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  505. }
  506. endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local)
  507. if endTime.Before(date) {
  508. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  509. }
  510. }
  511. if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil {
  512. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64)
  513. }
  514. if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil {
  515. hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string)
  516. }
  517. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month())
  518. hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind)
  519. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount)
  520. v.OrdNo = outTradeNo
  521. }
  522. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  523. centralKitchenForSchoolUserWithDayDb.Set(0)
  524. _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data)
  525. if err != nil {
  526. return
  527. }
  528. //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve`
  529. centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{}
  530. centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo)
  531. for k, v := range hasMonths {
  532. for _, v1 := range hasKinds[k] {
  533. _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{
  534. EnterpriseId: ord.EnterpriseId,
  535. Uid: ord.Uid,
  536. UserIdentityName: ord.UserIdentityName,
  537. UserIdentityId: ord.UserIdentityId,
  538. Kind: utils.StrToInt(v1),
  539. OutTradeNo: ord.OutTradeNo,
  540. ReserveMonth: utils.AnyToString(v["month"]),
  541. MealTimeStart: utils.AnyToString(v["meal_time_start"]),
  542. MealTimeEnd: utils.AnyToString(v["meal_time_end"]),
  543. TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]),
  544. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  545. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  546. })
  547. if err != nil {
  548. return
  549. }
  550. }
  551. }
  552. }
  553. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state", "trade_no")
  554. if err != nil {
  555. return
  556. }
  557. }
  558. state = ord.State
  559. return
  560. }
  561. func CheckAllCallbackParams(c *gin.Context) interface{} {
  562. body, _ := ioutil.ReadAll(c.Request.Body)
  563. utils.FilePutContents("CheckAllCallbackParams", utils.SerializeStr(string(body)))
  564. dataAlipay, _ := GetAlipayCallbackParams(body)
  565. if dataAlipay != nil {
  566. return dataAlipay
  567. }
  568. return nil
  569. }
  570. // GetAlipayCallbackParams 支付宝参数解析
  571. func GetAlipayCallbackParams(body []byte) (*md.AliPayCallback, error) {
  572. decodeArgs, err := url.QueryUnescape(string(body))
  573. if err != nil {
  574. _ = logx.Warn(err)
  575. return nil, logx.Warn("回调参数解码错误")
  576. }
  577. data, err := url.ParseQuery(decodeArgs)
  578. if err != nil {
  579. return nil, err
  580. }
  581. dataMap := make(map[string]interface{})
  582. for k := range data {
  583. dataMap[k] = data.Get(k)
  584. }
  585. callbackStr := utils.Serialize(dataMap)
  586. fmt.Println("支付宝回调数据", string(callbackStr))
  587. var args md.AliPayCallback
  588. if err := json.Unmarshal(callbackStr, &args); err != nil {
  589. return nil, logx.Warn(err)
  590. }
  591. return &args, nil
  592. }