recharge_service.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. log "github.com/sirupsen/logrus"
  7. "github.com/wechatpay-apiv3/wechatpay-go/core"
  8. "github.com/wechatpay-apiv3/wechatpay-go/core/option"
  9. "github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
  10. "github.com/wechatpay-apiv3/wechatpay-go/utils"
  11. "gorm.io/gorm"
  12. "time"
  13. "youngee_b_api/app/dao"
  14. "youngee_b_api/app/entity"
  15. "youngee_b_api/app/util"
  16. "youngee_b_api/app/vo"
  17. )
  18. type RechargeService struct{}
  19. // 充值管理——对公转账
  20. func (s RechargeService) TransferToPublic(param *vo.RechargeTransferParam) (*string, error) {
  21. var rechargeId string
  22. var phone string
  23. //if param.SubAccountId == 0 {
  24. // rechargeId = util.MakeRechargeId(param.EnterpriseId)
  25. // phone, _ = dao.EnterpriseDao{}.GetEnterprisePhone(param.EnterpriseId)
  26. //} else {
  27. // rechargeId = util.MakeRechargeId(strconv.FormatInt(param.SubAccountId, 10))
  28. // phone, _ = dao.SubAccountDao{}.GetSubAccountPhone(param.SubAccountId)
  29. //}
  30. rechargeId = util.MakeRechargeId(param.EnterpriseId)
  31. phone, _ = dao.EnterpriseDao{}.GetEnterprisePhone(param.EnterpriseId)
  32. rechargeRecord := entity.RechargeRecord{
  33. RechargeID: rechargeId,
  34. EnterpriseID: param.EnterpriseId,
  35. RechargeAmount: param.Amount,
  36. TransferVoucherUrl: param.TransferVoucherUrl,
  37. Phone: phone,
  38. RechargeMethod: 1,
  39. Status: 1,
  40. InvoiceStatus: 1,
  41. CommitAt: time.Now(),
  42. }
  43. err := dao.RechargeRecordDao{}.Insert(&rechargeRecord)
  44. if err != nil {
  45. return nil, err
  46. }
  47. return &rechargeId, nil
  48. }
  49. // 获取微信支付CodeUrl
  50. func (s RechargeService) NativeApiServicePrepay(tradeId string, amount int64) (string, *time.Time, error) {
  51. var (
  52. mchID string = "1615933939" // 商户号
  53. mchCertificateSerialNumber string = "33DDFEC51BF5412F663B9B56510FD567B625FC68" // 商户证书序列号
  54. mchAPIv3Key string = "V10987654321younggee12345678910V" // 商户APIv3密钥,用于加密和解密平台证书
  55. )
  56. fmt.Println("充值的金额为:", amount)
  57. // 使用 utils 提供的函数从本地文件中加载商户私钥
  58. mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem") // 商户私钥,用于生成请求的签名
  59. if err != nil {
  60. log.Print("load merchant private key error")
  61. }
  62. ctx := context.Background()
  63. // 使用商户私钥等初始化 微信支付client,并使它具有自动定时获取微信支付平台证书的能力
  64. opts := []core.ClientOption{
  65. option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
  66. }
  67. client, err := core.NewClient(ctx, opts...)
  68. if err != nil {
  69. log.Printf("new wechat pay client err: %s", err)
  70. }
  71. // 采用 Native 支付方式
  72. svc := native.NativeApiService{Client: client}
  73. // 发送请求
  74. timeExpire := time.Now().Add(10 * time.Minute)
  75. resp, result, err := svc.Prepay(ctx,
  76. native.PrepayRequest{
  77. Appid: core.String("wxac396a3be7a16844"),
  78. Mchid: core.String("1615933939"),
  79. Description: core.String("样叽微信支付充值"),
  80. OutTradeNo: core.String(tradeId),
  81. TimeExpire: core.Time(timeExpire),
  82. Attach: core.String("微信支付充值"),
  83. NotifyUrl: core.String("https://www.weixin.qq.com/wxpay/pay.php"),
  84. SupportFapiao: core.Bool(true),
  85. Amount: &native.Amount{
  86. Currency: core.String("CNY"),
  87. Total: core.Int64(amount),
  88. },
  89. },
  90. )
  91. if err != nil {
  92. // 处理错误
  93. log.Printf("call Prepay err:%s", err)
  94. return "", nil, err
  95. } else {
  96. // 处理返回结果
  97. log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
  98. log.Println("codeUrl:", *resp.CodeUrl)
  99. }
  100. return *resp.CodeUrl, &timeExpire, nil
  101. }
  102. // 根据交易id查询微信是否扫码付款
  103. // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_4_2.shtml
  104. func (s RechargeService) QueryOrderByTradeId(tradeId string) (tradeState string, err error) {
  105. var (
  106. mchID string = "1615933939" // 商户号
  107. mchCertificateSerialNumber string = "33DDFEC51BF5412F663B9B56510FD567B625FC68" // 商户证书序列号
  108. mchAPIv3Key string = "V10987654321younggee12345678910V" // 商户APIv3密钥
  109. )
  110. // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名
  111. mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
  112. if err != nil {
  113. log.Print("load merchant private key error")
  114. }
  115. ctx := context.Background()
  116. // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
  117. opts := []core.ClientOption{
  118. option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
  119. }
  120. client, err := core.NewClient(ctx, opts...)
  121. if err != nil {
  122. log.Printf("new wechat pay client err: %s", err)
  123. }
  124. svc := native.NativeApiService{Client: client}
  125. resp, result, err := svc.QueryOrderByOutTradeNo(ctx,
  126. native.QueryOrderByOutTradeNoRequest{
  127. OutTradeNo: core.String(tradeId),
  128. Mchid: core.String("1615933939"),
  129. },
  130. )
  131. fmt.Printf("支付 %+v\n", resp)
  132. if err != nil {
  133. // 处理错误
  134. log.Printf("call QueryOrderByOutTradeNo err: %s", err)
  135. return "", err
  136. } else {
  137. // 处理返回结果
  138. log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
  139. }
  140. fmt.Printf("支付状态 %+v\n", *resp.TradeState)
  141. return *resp.TradeState, nil
  142. }
  143. // 余额管理——总金额、可用余额、冻结金额
  144. func (s RechargeService) ShowBalance(param *vo.BalanceParam) (*vo.ReBalanceShow, error) {
  145. reBalanceShow := new(vo.ReBalanceShow)
  146. enterprise, err := dao.EnterpriseDao{}.GetEnterpriseInfo(param.EnterpriseId)
  147. if err != nil {
  148. if errors.Is(err, gorm.ErrRecordNotFound) {
  149. return reBalanceShow, nil
  150. } else {
  151. return nil, err
  152. }
  153. }
  154. reBalanceShow.TotalBalance = enterprise.Balance
  155. reBalanceShow.AvailBalance = enterprise.AvailableBalance
  156. reBalanceShow.FrozenBalance = enterprise.FrozenBalance
  157. return reBalanceShow, nil
  158. }
  159. // 余额管理——冻结记录
  160. func (s RechargeService) FrozenInfoList(param *vo.BalanceParam) (vo.ResultVO, error) {
  161. if param.Page <= 0 {
  162. param.Page = 1
  163. }
  164. if param.PageSize <= 0 {
  165. param.PageSize = 10
  166. }
  167. var result vo.ResultVO
  168. var reBalanceShows []*vo.ReFrozenInfo
  169. var selectionInfos []*entity.SelectionInfo
  170. var projects []*entity.Project
  171. if param.FrozenState == 1 {
  172. // 电商带货
  173. selectionInfos, _ = dao.SelectionInfoDAO{}.GetSelectionFrozenList(param.EnterpriseId)
  174. // 品牌种草
  175. projects, _ = dao.ProjectDAO{}.GetProjectFrozenList(param.EnterpriseId)
  176. // 本地生活
  177. } else {
  178. // 电商带货
  179. selectionInfos, _ = dao.SelectionInfoDAO{}.GetSelectionFrozenCancelList(param.EnterpriseId)
  180. // 品牌种草
  181. projects, _ = dao.ProjectDAO{}.GetProjectFrozenCancelList(param.EnterpriseId)
  182. // 本地生活
  183. }
  184. // 汇总结果
  185. for _, selection := range selectionInfos {
  186. // 获取商品详情字段
  187. var creatorName string
  188. var productName string
  189. var productPrice float64
  190. var mainImage string
  191. if selection.SubAccountId == 0 {
  192. enterprise, err := dao.EnterpriseDao{}.GetEnterprise(selection.EnterpriseID)
  193. if err == nil && enterprise != nil {
  194. creatorName = enterprise.BusinessName
  195. }
  196. } else {
  197. subAccount, err := dao.SubAccountDao{}.GetSubAccount(selection.SubAccountId)
  198. if err == nil && subAccount != nil {
  199. creatorName = subAccount.SubAccountName
  200. }
  201. }
  202. product, err := dao.ProductDAO{}.GetProductByID(selection.ProductID)
  203. if err == nil && product != nil {
  204. productName = product.ProductName
  205. productPrice = product.ProductPrice
  206. }
  207. mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(selection.ProductID)
  208. // 电商带货汇总
  209. reBalanceShow := &vo.ReFrozenInfo{
  210. ProductId: selection.ProductID,
  211. MainImage: mainImage,
  212. ProductName: productName,
  213. ProductPrice: productPrice,
  214. Platform: selection.Platform,
  215. CreatorName: creatorName,
  216. TaskType: "电商带货",
  217. FrozenBalance: selection.EstimatedCost,
  218. FrozenTime: selection.PayAt.Format("2006-01-02 15:04:05"),
  219. EnterpriseId: selection.EnterpriseID,
  220. SubAccountId: selection.SubAccountId,
  221. TaskId: selection.SelectionID,
  222. }
  223. if param.FrozenState == 2 {
  224. reBalanceShow.FrozenCancelBalance = selection.SettlementAmount
  225. }
  226. reBalanceShows = append(reBalanceShows, reBalanceShow)
  227. }
  228. for _, project := range projects {
  229. // 获取商品详情字段
  230. var creatorName string
  231. var productName string
  232. var productPrice float64
  233. var mainImage string
  234. if project.SubAccountId == 0 {
  235. enterprise, err := dao.EnterpriseDao{}.GetEnterprise(project.EnterpriseID)
  236. if err == nil && enterprise != nil {
  237. creatorName = enterprise.BusinessName
  238. }
  239. } else {
  240. subAccount, err := dao.SubAccountDao{}.GetSubAccount(project.SubAccountId)
  241. if err == nil && subAccount != nil {
  242. creatorName = subAccount.SubAccountName
  243. }
  244. }
  245. product, err := dao.ProductDAO{}.GetProductByID(project.ProductID)
  246. if err == nil && product != nil {
  247. productName = product.ProductName
  248. productPrice = product.ProductPrice
  249. }
  250. mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(project.ProductID)
  251. // 电商带货汇总
  252. reBalanceShow := &vo.ReFrozenInfo{
  253. ProductId: project.ProductID,
  254. MainImage: mainImage,
  255. ProductName: productName,
  256. ProductPrice: productPrice,
  257. Platform: project.ProjectPlatform,
  258. CreatorName: creatorName,
  259. TaskType: "品牌种草",
  260. FrozenBalance: project.PaymentAmount,
  261. FrozenTime: project.PayAt.Format("2006-01-02 15:04:05"),
  262. EnterpriseId: project.EnterpriseID,
  263. SubAccountId: project.SubAccountId,
  264. TaskId: project.ProjectId,
  265. }
  266. if param.FrozenState == 2 {
  267. reBalanceShow.FrozenCancelBalance = project.SettlementAmount
  268. }
  269. reBalanceShows = append(reBalanceShows, reBalanceShow)
  270. }
  271. startIndex := (param.Page - 1) * param.PageSize
  272. endIndex := startIndex + param.PageSize
  273. // 分页
  274. if startIndex >= len(reBalanceShows) {
  275. return result, nil
  276. }
  277. if endIndex > len(reBalanceShows) {
  278. endIndex = len(reBalanceShows)
  279. }
  280. result = vo.ResultVO{
  281. Page: param.Page,
  282. PageSize: param.PageSize,
  283. Total: int64(len(reBalanceShows)),
  284. Data: reBalanceShows[startIndex:endIndex],
  285. }
  286. return result, nil
  287. }
  288. // 充值管理——累计充值金额、确认中金额
  289. func (s RechargeService) ShowRecharge(param *vo.RechargeParam) (*vo.ReRechargeShow, error) {
  290. reRechargeShow := new(vo.ReRechargeShow)
  291. confirmingRecharge, _ := dao.RechargeRecordDao{}.GetRechargeAmount(param.EnterpriseId, 1)
  292. totalRecharge, _ := dao.RechargeRecordDao{}.GetRechargeAmount(param.EnterpriseId, 2)
  293. reRechargeShow.ConfirmingRecharge = confirmingRecharge
  294. reRechargeShow.TotalRecharge = totalRecharge
  295. return reRechargeShow, nil
  296. }
  297. // 充值管理——充值记录
  298. func (s RechargeService) RechargeInfoList(param *vo.RechargeParam) (vo.ResultVO, error) {
  299. if param.Page <= 0 {
  300. param.Page = 1
  301. }
  302. if param.PageSize <= 0 {
  303. param.PageSize = 10
  304. }
  305. var result vo.ResultVO
  306. var reRechargeInfos []*vo.ReRechargeInfo
  307. rechargeRecords, total, err := dao.RechargeRecordDao{}.RechargeInfoList(param)
  308. if err != nil {
  309. return result, err
  310. }
  311. for _, rechargeRecord := range rechargeRecords {
  312. var creatorName string
  313. enterprise, err := dao.EnterpriseDao{}.GetEnterprise(param.EnterpriseId)
  314. if err == nil && enterprise != nil {
  315. creatorName = enterprise.BusinessName
  316. }
  317. reRechargeInfo := &vo.ReRechargeInfo{
  318. RechargeId: rechargeRecord.RechargeID,
  319. CreatorName: creatorName,
  320. RechargeAmount: rechargeRecord.RechargeAmount,
  321. RechargeMethod: rechargeRecord.RechargeMethod,
  322. TransferVoucherUrl: rechargeRecord.TransferVoucherUrl,
  323. }
  324. if param.RechargeState == 1 {
  325. reRechargeInfo.CommitAt = rechargeRecord.CommitAt.Format("2006-01-02 15:04:05")
  326. } else if param.RechargeState == 2 {
  327. reRechargeInfo.ConfirmAt = rechargeRecord.ConfirmAt.Format("2006-01-02 15:04:05")
  328. } else if param.RechargeState == 3 {
  329. reRechargeInfo.RefuseAt = rechargeRecord.RefuseAt.Format("2006-01-02 15:04:05")
  330. reRechargeInfo.FailReason = rechargeRecord.FailReason
  331. }
  332. reRechargeInfos = append(reRechargeInfos, reRechargeInfo)
  333. }
  334. result = vo.ResultVO{
  335. Page: param.Page,
  336. PageSize: param.PageSize,
  337. Total: total,
  338. Data: reRechargeInfos,
  339. }
  340. return result, nil
  341. }