pay_api_controller.go 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. package controllers
  2. import (
  3. "XT_New/enums"
  4. "XT_New/models"
  5. "XT_New/service"
  6. "bytes"
  7. "crypto/md5"
  8. "encoding/hex"
  9. "encoding/json"
  10. "encoding/xml"
  11. "errors"
  12. "fmt"
  13. "github.com/astaxie/beego"
  14. "io/ioutil"
  15. "math/rand"
  16. "net/http"
  17. "regexp"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. const (
  24. pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
  25. )
  26. type PayApiController struct {
  27. BaseServeAPIController
  28. parameters map[string]string
  29. resultParameters map[string]string
  30. payUrl string
  31. }
  32. type PayApiController2 struct {
  33. beego.Controller
  34. parameters map[string]string
  35. resultParameters map[string]string
  36. payUrl string
  37. }
  38. func PayApiRegistRouters() {
  39. beego.Router("/api/my/service", &PayApiController{}, "Get:GetMyService")
  40. beego.Router("/api/product", &PayApiController{}, "Get:GetProduct")
  41. beego.Router("/api/pay", &PayApiController{}, "Get:GetPayUrl")
  42. beego.Router("/api/pay/transfer", &PayApiController{}, "Post:PostTransferStatus")
  43. beego.Router("/api/order", &PayApiController{}, "Post:PostOrderInfo")
  44. beego.Router("/api/order/get", &PayApiController{}, "Get:GetOrderInfo")
  45. beego.Router("/api/pay/notify", &PayApiController2{}, "Post:WxPaySuccessNotify")
  46. beego.Router("/api/order/cancel", &PayApiController{}, "Post:CancelOrder")
  47. beego.Router("/api/order/list", &PayApiController{}, "Get:GetOrderList")
  48. beego.Router("/api/order/hetong", &PayApiController{}, "Get:GetHeTong")
  49. beego.Router("/api/order/hetong", &PayApiController{}, "Post:CreateHeTong")
  50. }
  51. func (c *PayApiController) GetOrderList() {
  52. adminUserInfo := c.GetAdminUserInfo()
  53. serviceOrderList, err := service.GetOrderList(adminUserInfo.CurrentOrgId)
  54. if err == nil {
  55. c.ServeSuccessJSON(map[string]interface{}{
  56. "list": serviceOrderList,
  57. })
  58. } else {
  59. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  60. }
  61. }
  62. func (c *PayApiController) CancelOrder() {
  63. adminUserInfo := c.GetAdminUserInfo()
  64. orderId, _ := c.GetInt64("id", 0)
  65. if orderId == 0 {
  66. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  67. return
  68. }
  69. order, err := service.FindServeOrderByID(adminUserInfo.CurrentOrgId, orderId)
  70. if err != nil {
  71. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  72. return
  73. }
  74. if order == nil {
  75. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  76. return
  77. }
  78. errs := service.UpdateOrderStatus(adminUserInfo.CurrentOrgId, orderId)
  79. if errs == nil {
  80. c.ServeSuccessJSON(map[string]interface{}{
  81. "msg": "取消成功",
  82. })
  83. } else {
  84. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  85. }
  86. }
  87. func (c *PayApiController) PostTransferStatus() {
  88. adminUserInfo := c.GetAdminUserInfo()
  89. orderId, _ := c.GetInt64("id", 0)
  90. if orderId == 0 {
  91. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  92. return
  93. }
  94. order, err := service.FindServeOrderByID(adminUserInfo.CurrentOrgId, orderId)
  95. if err != nil {
  96. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  97. return
  98. }
  99. if order == nil {
  100. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  101. return
  102. }
  103. errs := service.UpdateOrderPayType(adminUserInfo.CurrentOrgId, orderId)
  104. if errs == nil {
  105. c.ServeSuccessJSON(map[string]interface{}{
  106. "msg": "确认成功",
  107. })
  108. } else {
  109. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  110. }
  111. }
  112. func (c *PayApiController) GetOrderInfo() {
  113. adminUserInfo := c.GetAdminUserInfo()
  114. orderId, _ := c.GetInt64("id", 0)
  115. order, err := service.FindServeOrderByID(adminUserInfo.CurrentOrgId, orderId)
  116. if err != nil {
  117. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  118. return
  119. }
  120. if order == nil {
  121. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  122. return
  123. }
  124. orderInfo, err := service.FindOrderInfomationByID(order.OrderNumber, adminUserInfo.CurrentOrgId)
  125. if err != nil {
  126. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  127. return
  128. }
  129. if orderInfo == nil {
  130. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  131. return
  132. }
  133. c.ServeSuccessJSON(map[string]interface{}{
  134. "total": order.PaymentAmount,
  135. "orderNumber": order.OrderNumber,
  136. "OrgName": adminUserInfo.Orgs[adminUserInfo.CurrentOrgId].OrgName,
  137. "order": order,
  138. "orderInfo": orderInfo,
  139. })
  140. }
  141. func (c *PayApiController) PostOrderInfo() {
  142. adminUserInfo := c.GetAdminUserInfo()
  143. amount, _ := c.GetInt64("amount", 0)
  144. productId, _ := c.GetInt64("id", 0)
  145. product, err := service.FindProductByID(productId)
  146. if err != nil {
  147. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  148. return
  149. }
  150. if product == nil {
  151. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeProductError)
  152. return
  153. }
  154. timestamp := c.GetTimestamp()
  155. //自定义订单号
  156. bill_no := "S" + strconv.FormatInt(timestamp, 10) + strconv.FormatInt(adminUserInfo.CurrentOrgId, 10)
  157. order := models.ServeOrder{
  158. OrgId: adminUserInfo.CurrentOrgId,
  159. Period: amount * 12,
  160. Status: 1,
  161. CreatedTime: time.Now().Unix(),
  162. UpdatedTime: time.Now().Unix(),
  163. OrderNumber: bill_no,
  164. OrderStatus: 1,
  165. PayableAmount: float64(amount) * product.Price,
  166. PaymentAmount: float64(amount) * product.Price,
  167. ServeName: product.ServeName,
  168. ServeDesc: product.ServeDesc,
  169. OrderExpireTime: time.Now().Unix() + (7 * 24 * 3600),
  170. Quantity: amount,
  171. Price: product.Price,
  172. ServeId: productId,
  173. }
  174. infomation := models.ServeOrderInfomation{
  175. OrgId: adminUserInfo.CurrentOrgId,
  176. OrderNumber: bill_no,
  177. Status: 1,
  178. ProductId: product.ID,
  179. ProductName: product.ServeName,
  180. ProductDesc: product.ServeDesc,
  181. Price: product.Price,
  182. Quantity: amount,
  183. MarketPrice: product.OriginalPrice,
  184. }
  185. service.CreateOrderRecord(&order)
  186. service.CreateOrderInfomation(&infomation)
  187. c.ServeSuccessJSON(map[string]interface{}{
  188. "order": order,
  189. "msg": "提交订单成功",
  190. })
  191. }
  192. func (c *PayApiController) GetProduct() {
  193. adminUserInfo := c.GetAdminUserInfo()
  194. products, err := service.FindAllProduct()
  195. subscibe, _ := service.FindServiceSubscibeByOrgId(adminUserInfo.CurrentOrgId)
  196. if err == nil {
  197. c.ServeSuccessJSON(map[string]interface{}{
  198. "products": products,
  199. "subscibe": subscibe,
  200. "serviceTime": time.Now().Unix(),
  201. //"OrgName": adminUserInfo.Orgs[adminUserInfo.CurrentOrgId].OrgName,
  202. })
  203. } else {
  204. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  205. }
  206. }
  207. func (c *PayApiController) GetMyService() {
  208. adminUserInfo := c.GetAdminUserInfo()
  209. subscibe, err := service.FindServiceSubscibeByOrgId(adminUserInfo.CurrentOrgId)
  210. if err == nil {
  211. c.ServeSuccessJSON(map[string]interface{}{
  212. "subscibe": subscibe,
  213. "serviceTime": time.Now().Unix(),
  214. })
  215. } else {
  216. }
  217. }
  218. func (c *PayApiController) GetPayUrl() {
  219. adminUserInfo := c.GetAdminUserInfo()
  220. orderId, _ := c.GetInt64("id", 0)
  221. if orderId == 0 {
  222. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  223. return
  224. }
  225. order, err := service.FindServeOrderByID(adminUserInfo.CurrentOrgId, orderId)
  226. if err != nil {
  227. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  228. return
  229. }
  230. if order == nil {
  231. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  232. return
  233. }
  234. orderInfo, err := service.FindOrderInfomationByID(order.OrderNumber, adminUserInfo.CurrentOrgId)
  235. if err != nil {
  236. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  237. return
  238. }
  239. if orderInfo == nil {
  240. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  241. return
  242. }
  243. totalPrice := orderInfo.Price * float64(orderInfo.Quantity)
  244. totalFee := fmt.Sprintf("%.0f", totalPrice*100)
  245. c.SetParameter("out_trade_no", orderInfo.OrderNumber)
  246. c.SetParameter("total_fee", totalFee)
  247. c.SetParameter("trade_type", "NATIVE")
  248. c.SetParameter("body", order.ServeName)
  249. notify_url := beego.AppConfig.String("httpdomain") + "/api/pay/notify"
  250. c.SetParameter("product_id", orderInfo.OrderNumber)
  251. c.SetParameter("notify_url", notify_url)
  252. c.SetParameter("spbill_create_ip", c.GetClientIp())
  253. fmt.Println(c.GetClientIp())
  254. url, err := c.GetPayCodeUrl()
  255. fmt.Println(err)
  256. if err == nil {
  257. c.SetPayUrl(url)
  258. c.ServeSuccessJSON(map[string]interface{}{
  259. "payUrl": url,
  260. "price": order.PayableAmount,
  261. //": adminUserInfo.Orgs[adminUserInfo.CurrentOrgId].OrgName,
  262. })
  263. } else {
  264. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  265. // utils.LogError(err)
  266. }
  267. }
  268. func (this *PayApiController2) WxPaySuccessNotify() {
  269. type PaySuccessXmlResp struct {
  270. ReturnCode string `xml:"return_code"`
  271. Appid string `xml:"appid"`
  272. BankType string `xml:"bank_type"`
  273. CashFee int64 `xml:"cash_fee"`
  274. FeeType string `xml:"fee_type"`
  275. IsSubscribe string `xml:"is_subscribe"`
  276. MchId string `xml:"mch_id"`
  277. NonceStr string `xml:"nonce_str"`
  278. OpenId string `xml:"openid"`
  279. OutTradeNo string `xml:"out_trade_no"`
  280. ResultCode string `xml:"result_code"`
  281. Sign string `xml:"sign"`
  282. TimeEnd string `xml:"time_end"`
  283. TotalFee string `xml:"total_fee"`
  284. TradeType string `xml:"trade_type"`
  285. TransactionId string `xml:"transaction_id"`
  286. }
  287. defer this.Ctx.Request.Body.Close()
  288. result, _ := ioutil.ReadAll(this.Ctx.Request.Body)
  289. res := new(PaySuccessXmlResp)
  290. xmlErr := xml.Unmarshal(result, &res)
  291. if xmlErr != nil {
  292. }
  293. order, _ := service.FindServeOrderByOrderNumber(res.OutTradeNo)
  294. service.UpdateOrder(order.OrderNumber, order.Quantity, order.OrgId, res.TransactionId, order.PeriodEnd, order.PeriodStart)
  295. this.SetResultParameter("return_code", res.ReturnCode)
  296. results := this.ParamsToXml2(this.resultParameters)
  297. this.Ctx.WriteString(results)
  298. this.ServeXML()
  299. }
  300. func (this *PayApiController) GetTimestamp() int64 {
  301. return time.Now().UnixNano() / 1000000 //毫秒
  302. }
  303. func (this *PayApiController) GetClientIp() string {
  304. ip := this.Ctx.Request.Header.Get("Remote_addr")
  305. if ip == "" {
  306. ip = this.Ctx.Request.RemoteAddr
  307. }
  308. if strings.Contains(ip, ":") {
  309. ip = this.Substr(ip, 0, strings.Index(ip, ":"))
  310. }
  311. return ip
  312. }
  313. // 截取字符串 start 起点下标 end 终点下标(不包括)
  314. func (this *PayApiController) Substr(str string, start int, end int) string {
  315. rs := []rune(str)
  316. length := len(rs)
  317. if start < 0 || start > length {
  318. return ""
  319. }
  320. if end < 0 || end > length {
  321. return ""
  322. }
  323. return string(rs[start:end])
  324. }
  325. // 设置请求参数
  326. func (this *PayApiController) SetParameter(key string, value string) {
  327. if this.parameters == nil {
  328. this.parameters = make(map[string]string)
  329. }
  330. this.parameters[key] = value
  331. }
  332. // 设置请求参数
  333. func (this *PayApiController2) SetResultParameter(key string, value string) {
  334. if this.resultParameters == nil {
  335. this.resultParameters = make(map[string]string)
  336. }
  337. this.resultParameters[key] = value
  338. }
  339. // 设置prepay_id
  340. func (this *PayApiController) SetPayUrl(payUrl string) {
  341. this.payUrl = payUrl
  342. }
  343. type XmlResp struct {
  344. Return_code string `xml:"return_code"`
  345. Return_msg string `xml:"return_msg"`
  346. Result_code string `xml:"result_code"`
  347. Err_code string `xml:"err_code"`
  348. Err_code_des string `xml:"err_code_des"`
  349. Prepay_id string `xml:"prepay_id"`
  350. Code_url string `xml:"code_url"`
  351. }
  352. func (this *PayApiController) GetPayCodeUrl() (string, error) {
  353. strXml, err := this.CreateXml()
  354. if err != nil {
  355. return "", this.Error("get pay_code_url error", err)
  356. }
  357. result, err := this.http_post(pay_url, strXml)
  358. if err != nil {
  359. return "", this.Error("get pay_code_url error", err)
  360. }
  361. res := new(XmlResp)
  362. xmlErr := xml.Unmarshal(result, &res)
  363. if xmlErr != nil {
  364. return "", this.Error("get pay_code_url xml error", xmlErr)
  365. }
  366. if res.Return_code != "SUCCESS" {
  367. return "", this.Error("get pay_code_url result error: "+res.Return_msg, nil)
  368. }
  369. if res.Result_code != "SUCCESS" {
  370. return "", this.Error("get pay_code_url result error: "+res.Err_code+"-"+res.Err_code_des, nil)
  371. }
  372. if res.Code_url == "" {
  373. return "", this.Error("get pay_code_url result error: not get pay_code_url", nil)
  374. }
  375. return res.Code_url, nil
  376. }
  377. func (this *PayApiController) http_post(url string, xml string) ([]byte, error) {
  378. bc := &http.Client{
  379. Timeout: 30 * time.Second, //设置超时时间30s
  380. }
  381. res, err := bc.Post(url, "text/xml:charset=UTF-8", strings.NewReader(xml))
  382. if err != nil {
  383. return nil, this.Error("post", err)
  384. }
  385. result, err := ioutil.ReadAll(res.Body)
  386. res.Body.Close()
  387. if err != nil {
  388. return nil, this.Error("post result err", err)
  389. }
  390. return result, nil
  391. }
  392. func (this *PayApiController) CreateXml() (string, error) {
  393. //检测必填参数
  394. if this.parameters["out_trade_no"] == "" {
  395. return "", this.Error("缺少统一支付接口必填参数out_trade_no(商户订单号)!", nil)
  396. } else if this.parameters["body"] == "" {
  397. return "", this.Error("缺少统一支付接口必填参数body(商品描述)!", nil)
  398. } else if this.parameters["total_fee"] == "" {
  399. return "", this.Error("缺少统一支付接口必填参数total_fee(交易金额)!", nil)
  400. } else if this.parameters["notify_url"] == "" {
  401. return "", this.Error("缺少统一支付接口必填参数notify_url(异步接收微信支付结果通知的回调地址)!", nil)
  402. } else if this.parameters["trade_type"] == "" {
  403. return "", this.Error("缺少统一支付接口必填参数trade_type(交易类型)!", nil)
  404. } else if this.parameters["spbill_create_ip"] == "" {
  405. return "", this.Error("缺少统一支付接口必填参数spbill_create_ip(终端ip)", nil)
  406. } else if this.parameters["trade_type"] == "NATIVE" && this.parameters["product_id"] == "" {
  407. return "", this.Error("统一支付接口中,缺少必填参数product_id!trade_type为NATIVE时,product_id为必填参数!", nil)
  408. }
  409. this.parameters["appid"] = beego.AppConfig.String("appid") //公众账号ID
  410. this.parameters["mch_id"] = beego.AppConfig.String("mchid") //商户号
  411. this.parameters["nonce_str"] = this.CreateNoncestr(32) //随机字符串
  412. this.parameters["sign"] = this.GetSign(this.parameters, beego.AppConfig.String("key")) //签名
  413. return this.ParamsToXml(this.parameters), nil
  414. }
  415. // 产生随机字符串,不长于32位
  416. func (this *PayApiController) CreateNoncestr(length int) (nonceStr string) {
  417. chars := "abcdefghijklmnopqrstuvwxyz0123456789"
  418. for i := 0; i < length; i++ {
  419. idx := rand.Intn(len(chars) - 1)
  420. nonceStr += chars[idx : idx+1]
  421. }
  422. return
  423. }
  424. func (this *PayApiController) Error(strMsg string, err error) error {
  425. if err == nil {
  426. return errors.New(strMsg)
  427. } else {
  428. return errors.New(strMsg + ": " + err.Error())
  429. }
  430. }
  431. // 格式化参数,签名过程需要使用
  432. func (this *PayApiController) FormatParams(paramsMap map[string]string) string {
  433. //STEP 1, 对key进行升序排序.
  434. var sorted_keys []string
  435. for k, _ := range paramsMap {
  436. sorted_keys = append(sorted_keys, k)
  437. }
  438. sort.Strings(sorted_keys)
  439. //STEP2, 对key=value的键值对用&连接起来,略过空值
  440. var paramsStr []string
  441. for _, k := range sorted_keys {
  442. v := fmt.Sprintf("%v", strings.TrimSpace(paramsMap[k]))
  443. if v != "" {
  444. paramsStr = append(paramsStr, fmt.Sprintf("%s=%s", k, v))
  445. }
  446. }
  447. return strings.Join(paramsStr, "&")
  448. }
  449. // 生成签名
  450. func (this *PayApiController) GetSign(paramsMap map[string]string, wxKey string) string {
  451. //STEP 1:按字典序排序参数
  452. paramsStr := this.FormatParams(paramsMap)
  453. //STEP 2:在string后加入KEY
  454. signStr := paramsStr + "&key=" + wxKey
  455. //STEP 3:MD5加密
  456. sign := md5.New()
  457. sign.Write([]byte(signStr))
  458. //STEP 3:所有字符转为大写
  459. return strings.ToUpper(hex.EncodeToString(sign.Sum(nil)))
  460. }
  461. // xml结构
  462. func (this *PayApiController) ParamsToXml(data map[string]string) string {
  463. fmt.Println(data)
  464. buf := bytes.NewBufferString("<xml>")
  465. for k, v := range data {
  466. str := "<![CDATA[%s]]>"
  467. flag, _ := regexp.MatchString("^\\d+\\.?\\d*$", v)
  468. if flag {
  469. str = "%s"
  470. }
  471. buf.WriteString(fmt.Sprintf("<%s>"+str+"</%s>", k, v, k))
  472. }
  473. buf.WriteString("</xml>")
  474. return buf.String()
  475. }
  476. // xml结构
  477. func (this *PayApiController2) ParamsToXml2(data map[string]string) string {
  478. fmt.Println(data)
  479. buf := bytes.NewBufferString("<xml>")
  480. for k, v := range data {
  481. str := "<![CDATA[%s]]>"
  482. flag, _ := regexp.MatchString("^\\d+\\.?\\d*$", v)
  483. if flag {
  484. str = "%s"
  485. }
  486. buf.WriteString(fmt.Sprintf("<%s>"+str+"</%s>", k, v, k))
  487. }
  488. buf.WriteString("</xml>")
  489. return buf.String()
  490. }
  491. func (this *PayApiController) SetUrl(payUrl string) {
  492. this.payUrl = payUrl
  493. }
  494. func (c *PayApiController) GetHeTong() {
  495. order_id, _ := c.GetInt64("order_id", 0)
  496. if order_id <= 0 {
  497. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  498. return
  499. }
  500. admin := c.GetAdminUserInfo()
  501. ht, err := service.GetHetong(admin.CurrentOrgId, order_id)
  502. if err != nil {
  503. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  504. return
  505. }
  506. c.ServeSuccessJSON(map[string]interface{}{
  507. "ht": ht,
  508. })
  509. }
  510. func (c *PayApiController) CreateHeTong() {
  511. orderId, _ := c.GetInt64("order_id", 0)
  512. if orderId <= 0 {
  513. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  514. return
  515. }
  516. admin := c.GetAdminUserInfo()
  517. order, err := service.FindServeOrderByID(admin.CurrentOrgId, orderId)
  518. if err != nil {
  519. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  520. return
  521. }
  522. if order == nil {
  523. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeServeNotExist)
  524. return
  525. }
  526. ht, err := service.GetHetong(admin.CurrentOrgId, orderId)
  527. if err != nil {
  528. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  529. return
  530. }
  531. if ht != nil {
  532. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHetongHad)
  533. return
  534. }
  535. var hetong models.ServeOrderContract
  536. err = json.Unmarshal(c.Ctx.Input.RequestBody, &hetong)
  537. if err != nil {
  538. fmt.Println(err)
  539. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  540. return
  541. }
  542. hetong.OrderId = orderId
  543. hetong.OrderNumber = order.OrderNumber
  544. hetong.CreatedTime = time.Now().Unix()
  545. hetong.UpdatedTime = time.Now().Unix()
  546. hetong.Status = 1
  547. hetong.OrgId = admin.CurrentOrgId
  548. err = service.CreateHetong(&hetong)
  549. if err != nil {
  550. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateHetongFail)
  551. return
  552. }
  553. c.ServeSuccessJSON(map[string]interface{}{
  554. "ht": hetong,
  555. })
  556. }