智慧食堂
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

svc_pay.go 22 KiB

1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
10ヶ月前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
1年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. companyWithWxpayInfoDb := db.CompanyWithWxpayInfoDb{}
  196. companyWithWxpayInfoDb.Set()
  197. wxMchId, err := companyWithWxpayInfoDb.GetCompanyWithWxpayInfoByEnterprise(req.EnterpriseId)
  198. if err != nil {
  199. return "", "", nil, err
  200. }
  201. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.WxAppletAppId, enum2.WxSpAppId, enum2.WxSpMchId, enum2.WxAppletAppId, enum2.WxJsapiPayNotifyUrl)
  202. fmt.Println(int64(math.Round(totalPrice * 100)))
  203. result, _, err := wxSvc.Prepay(c,
  204. jsapi.PrepayRequest{
  205. SpAppid: core.String(sysCfg[enum2.WxSpAppId]),
  206. SpMchid: core.String(sysCfg[enum2.WxSpMchId]),
  207. SubAppid: core.String(sysCfg[enum2.WxAppletAppId]),
  208. SubMchid: core.String(wxMchId),
  209. Description: core.String("购买食堂套餐"),
  210. OutTradeNo: core.String(outTradeNo),
  211. TimeExpire: core.Time(time.Now().Add(20 * time.Minute)),
  212. //Attach: core.String("自定义数据说明"),
  213. NotifyUrl: core.String(sysCfg[enum2.WxJsapiPayNotifyUrl]),
  214. Amount: &jsapi.Amount{
  215. Currency: core.String("CNY"),
  216. Total: core.Int64(int64(math.Round(totalPrice * 100))),
  217. },
  218. Payer: &jsapi.Payer{
  219. //SpOpenid: core.String("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"),
  220. SubOpenid: core.String(user.OpenId),
  221. },
  222. },
  223. )
  224. fmt.Println(">>>>>>>>>>>", core.Int64(utils.StrToInt64(total)*100))
  225. if err != nil {
  226. _ = session.Rollback()
  227. return
  228. }
  229. //5、插入订单记录
  230. now := time.Now()
  231. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  232. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  233. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{
  234. EnterpriseId: req.EnterpriseId,
  235. Uid: user.Id,
  236. UserIdentityId: req.UserIdentityId,
  237. UserIdentityName: userIdentity.Name,
  238. TotalPrice: total,
  239. Kind: req.Kind,
  240. OutTradeNo: outTradeNo,
  241. TradeNo: "",
  242. State: enum2.CentralKitchenForSchoolPackageOrdStateForWait,
  243. OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait,
  244. ReqContent: string(utils.Serialize(req)),
  245. WithDayData: string(utils.Serialize(data)),
  246. PayWay: enum.PayWayForWx,
  247. PrepayId: *result.PrepayId,
  248. CreateAt: now.Format("2006-01-02 15:04:05"),
  249. UpdateAt: now.Format("2006-01-02 15:04:05"),
  250. })
  251. if err != nil {
  252. _ = session.Rollback()
  253. return
  254. }
  255. session.Commit()
  256. //prepayId = *resp.PrepayId
  257. resp = new(jsapi2.PrepayWithRequestPaymentResponse)
  258. resp.PrepayId = result.PrepayId
  259. resp.SignType = core.String("RSA")
  260. appid := sysCfg[enum2.WxAppletAppId]
  261. resp.Appid = &appid
  262. resp.TimeStamp = core.String(strconv.FormatInt(time.Now().Unix(), 10))
  263. nonce, err := utils2.GenerateNonce()
  264. if err != nil {
  265. _ = session.Rollback()
  266. return
  267. }
  268. resp.NonceStr = core.String(nonce)
  269. resp.Package = core.String("prepay_id=" + *result.PrepayId)
  270. message := fmt.Sprintf("%s\n%s\n%s\n%s\n", *resp.Appid, *resp.TimeStamp, *resp.NonceStr, *resp.Package)
  271. signatureResult, err := wxSvc.Client.Sign(c, message)
  272. if err != nil {
  273. _ = session.Rollback()
  274. return
  275. }
  276. resp.PaySign = core.String(signatureResult.Signature)
  277. return
  278. }
  279. func NursingHomeBuyPackageReq(c *gin.Context, req md.NursingHomeBuyPackageReq) (outTradeNo, tradeNo, total string, err error) {
  280. user := GetUser(c)
  281. session := db.Db.NewSession()
  282. defer session.Close()
  283. session.Begin()
  284. if err != nil {
  285. _ = session.Rollback()
  286. return
  287. }
  288. userIdentityDb := db.UserIdentityDb{}
  289. userIdentityDb.Set(0)
  290. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  291. if err != nil {
  292. return
  293. }
  294. if userIdentity == nil {
  295. err = errors.New("未查询到对应身份记录")
  296. return
  297. }
  298. //1、计算数据(1:按年购买 2:按月购买 3:按天购买 4:补餐)
  299. var totalPrice float64
  300. var data []*model.NursingHomeUserWithDay
  301. if req.Kind == 1 {
  302. totalPrice, data, err = CalcByYearForNursingHome(user.Id, req)
  303. if err != nil {
  304. return
  305. }
  306. }
  307. if req.Kind == 2 {
  308. totalPrice, data, err = CalcByMonthForNursingHome(user.Id, req)
  309. if err != nil {
  310. return
  311. }
  312. }
  313. if req.Kind == 3 {
  314. totalPrice, data, err = CalcByDayForNursingHome(user.Id, req)
  315. if err != nil {
  316. return
  317. }
  318. }
  319. if req.Kind == 4 {
  320. totalPrice, data, err = CalcByDayForNursingHome(user.Id, req)
  321. if err != nil {
  322. return
  323. }
  324. }
  325. total = utils.Float64ToStr(totalPrice)
  326. //3、生成订单号
  327. outTradeNo = utils.OrderUUID(user.Id)
  328. //4、请求 alipay.trade.create(统一收单交易创建接口)
  329. sysCfgDb := db.SysCfgDb{}
  330. sysCfgDb.Set()
  331. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken)
  332. err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{
  333. Config: struct {
  334. PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"`
  335. PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"`
  336. PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"`
  337. }{
  338. PayAliAppId: sysCfg[enum2.OpenAlipayAppid],
  339. PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey],
  340. PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey],
  341. },
  342. OpAppId: sysCfg[enum2.OpenAppletAppid],
  343. BuyerId: user.UserId,
  344. TotalAmount: total,
  345. OutTradeNo: outTradeNo,
  346. Subject: "购买食堂套餐",
  347. AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken],
  348. })
  349. if err != nil {
  350. return
  351. }
  352. //5、插入订单记录
  353. now := time.Now()
  354. NursingHomePackageOrd := db.NursingHomePackageOrd{}
  355. NursingHomePackageOrd.Set(outTradeNo)
  356. _, err = NursingHomePackageOrd.NursingHomePackageOrdInsertBySession(session, &model.NursingHomePackageOrd{
  357. EnterpriseId: req.EnterpriseId,
  358. Uid: user.Id,
  359. UserIdentityId: req.UserIdentityId,
  360. UserIdentityName: userIdentity.Name,
  361. TotalPrice: total,
  362. Kind: req.Kind,
  363. OutTradeNo: outTradeNo,
  364. TradeNo: resp.TradeNo,
  365. State: enum2.NursingHomePackageOrdStateForWait,
  366. OrdState: enum2.NursingHomePackageOrdOrdStateForWait,
  367. ReqContent: string(utils.Serialize(req)),
  368. WithDayData: string(utils.Serialize(data)),
  369. CreateAt: now.Format("2006-01-02 15:04:05"),
  370. UpdateAt: now.Format("2006-01-02 15:04:05"),
  371. })
  372. if err != nil {
  373. _ = session.Rollback()
  374. return
  375. }
  376. session.Commit()
  377. tradeNo = resp.TradeNo
  378. return
  379. }
  380. func DealCentralKitchenForSchoolOrderCallBack(outTradeNo, tradeStatus string) (state int, err error) {
  381. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  382. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  383. ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd()
  384. if err != nil {
  385. return
  386. }
  387. if ord == nil {
  388. err = errors.New("未查询到对应订单记录")
  389. return
  390. }
  391. if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait {
  392. if tradeStatus == "TRADE_CLOSED" {
  393. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail
  394. }
  395. if tradeStatus == "TRADE_SUCCESS" {
  396. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess
  397. ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess
  398. //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day`
  399. var data []*model.CentralKitchenForSchoolUserWithDay
  400. err = json.Unmarshal([]byte(ord.WithDayData), &data)
  401. if err != nil {
  402. return
  403. }
  404. var hasMonths = map[string]map[string]interface{}{}
  405. var hasKinds = map[string]map[string]string{}
  406. var hasTotalPrice = map[string]map[string]float64{}
  407. for _, v := range data {
  408. date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local)
  409. if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil {
  410. hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{})
  411. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  412. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  413. } else {
  414. startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local)
  415. if startTime.After(date) {
  416. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  417. }
  418. endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local)
  419. if endTime.Before(date) {
  420. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  421. }
  422. }
  423. if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil {
  424. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64)
  425. }
  426. if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil {
  427. hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string)
  428. }
  429. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month())
  430. hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind)
  431. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount)
  432. v.OrdNo = outTradeNo
  433. }
  434. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  435. centralKitchenForSchoolUserWithDayDb.Set(0)
  436. _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data)
  437. if err != nil {
  438. return
  439. }
  440. //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve`
  441. centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{}
  442. centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo)
  443. for k, v := range hasMonths {
  444. for _, v1 := range hasKinds[k] {
  445. _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{
  446. EnterpriseId: ord.EnterpriseId,
  447. Uid: ord.Uid,
  448. UserIdentityName: ord.UserIdentityName,
  449. UserIdentityId: ord.UserIdentityId,
  450. Kind: utils.StrToInt(v1),
  451. OutTradeNo: ord.OutTradeNo,
  452. ReserveMonth: utils.AnyToString(v["month"]),
  453. MealTimeStart: utils.AnyToString(v["meal_time_start"]),
  454. MealTimeEnd: utils.AnyToString(v["meal_time_end"]),
  455. TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]),
  456. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  457. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  458. })
  459. if err != nil {
  460. return
  461. }
  462. }
  463. }
  464. }
  465. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state")
  466. if err != nil {
  467. return
  468. }
  469. }
  470. state = ord.State
  471. return
  472. }
  473. func DealCentralKitchenForSchoolOrderCallBackForWx(outTradeNo, transactionId, tradeStatus string) (state int, err error) {
  474. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  475. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  476. ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd()
  477. if err != nil {
  478. return
  479. }
  480. if ord == nil {
  481. err = errors.New("未查询到对应订单记录")
  482. return
  483. }
  484. if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait {
  485. if tradeStatus == "CLOSED" || tradeStatus == "PAYERROR" {
  486. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail
  487. }
  488. if tradeStatus == "SUCCESS" {
  489. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess
  490. ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess
  491. ord.TradeNo = transactionId
  492. //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day`
  493. var data []*model.CentralKitchenForSchoolUserWithDay
  494. err = json.Unmarshal([]byte(ord.WithDayData), &data)
  495. if err != nil {
  496. return
  497. }
  498. var hasMonths = map[string]map[string]interface{}{}
  499. var hasKinds = map[string]map[string]string{}
  500. var hasTotalPrice = map[string]map[string]float64{}
  501. for _, v := range data {
  502. date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local)
  503. if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil {
  504. hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{})
  505. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  506. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  507. } else {
  508. startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local)
  509. if startTime.After(date) {
  510. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  511. }
  512. endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local)
  513. if endTime.Before(date) {
  514. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  515. }
  516. }
  517. if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil {
  518. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64)
  519. }
  520. if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil {
  521. hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string)
  522. }
  523. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month())
  524. hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind)
  525. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount)
  526. v.OrdNo = outTradeNo
  527. }
  528. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  529. centralKitchenForSchoolUserWithDayDb.Set(0)
  530. _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data)
  531. if err != nil {
  532. return
  533. }
  534. //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve`
  535. centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{}
  536. centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo)
  537. for k, v := range hasMonths {
  538. for _, v1 := range hasKinds[k] {
  539. _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{
  540. EnterpriseId: ord.EnterpriseId,
  541. Uid: ord.Uid,
  542. UserIdentityName: ord.UserIdentityName,
  543. UserIdentityId: ord.UserIdentityId,
  544. Kind: utils.StrToInt(v1),
  545. OutTradeNo: ord.OutTradeNo,
  546. ReserveMonth: utils.AnyToString(v["month"]),
  547. MealTimeStart: utils.AnyToString(v["meal_time_start"]),
  548. MealTimeEnd: utils.AnyToString(v["meal_time_end"]),
  549. TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]),
  550. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  551. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  552. })
  553. if err != nil {
  554. return
  555. }
  556. }
  557. }
  558. }
  559. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state", "trade_no")
  560. if err != nil {
  561. return
  562. }
  563. }
  564. state = ord.State
  565. return
  566. }
  567. func CheckAllCallbackParams(c *gin.Context) interface{} {
  568. body, _ := ioutil.ReadAll(c.Request.Body)
  569. utils.FilePutContents("CheckAllCallbackParams", utils.SerializeStr(string(body)))
  570. dataAlipay, _ := GetAlipayCallbackParams(body)
  571. if dataAlipay != nil {
  572. return dataAlipay
  573. }
  574. return nil
  575. }
  576. // GetAlipayCallbackParams 支付宝参数解析
  577. func GetAlipayCallbackParams(body []byte) (*md.AliPayCallback, error) {
  578. decodeArgs, err := url.QueryUnescape(string(body))
  579. if err != nil {
  580. _ = logx.Warn(err)
  581. return nil, logx.Warn("回调参数解码错误")
  582. }
  583. data, err := url.ParseQuery(decodeArgs)
  584. if err != nil {
  585. return nil, err
  586. }
  587. dataMap := make(map[string]interface{})
  588. for k := range data {
  589. dataMap[k] = data.Get(k)
  590. }
  591. callbackStr := utils.Serialize(dataMap)
  592. fmt.Println("支付宝回调数据", string(callbackStr))
  593. var args md.AliPayCallback
  594. if err := json.Unmarshal(callbackStr, &args); err != nil {
  595. return nil, logx.Warn(err)
  596. }
  597. return &args, nil
  598. }