123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361 |
- package service
- import (
- "context"
- "errors"
- "fmt"
- log "github.com/sirupsen/logrus"
- "github.com/wechatpay-apiv3/wechatpay-go/core"
- "github.com/wechatpay-apiv3/wechatpay-go/core/option"
- "github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
- "github.com/wechatpay-apiv3/wechatpay-go/utils"
- "gorm.io/gorm"
- "time"
- "youngee_b_api/app/dao"
- "youngee_b_api/app/entity"
- "youngee_b_api/app/util"
- "youngee_b_api/app/vo"
- )
- type RechargeService struct{}
- // 充值管理——对公转账
- func (s RechargeService) TransferToPublic(param *vo.RechargeTransferParam) (*string, error) {
- var rechargeId string
- var phone string
- //if param.SubAccountId == 0 {
- // rechargeId = util.MakeRechargeId(param.EnterpriseId)
- // phone, _ = dao.EnterpriseDao{}.GetEnterprisePhone(param.EnterpriseId)
- //} else {
- // rechargeId = util.MakeRechargeId(strconv.FormatInt(param.SubAccountId, 10))
- // phone, _ = dao.SubAccountDao{}.GetSubAccountPhone(param.SubAccountId)
- //}
- rechargeId = util.MakeRechargeId(param.EnterpriseId)
- phone, _ = dao.EnterpriseDao{}.GetEnterprisePhone(param.EnterpriseId)
- rechargeRecord := entity.RechargeRecord{
- RechargeID: rechargeId,
- EnterpriseID: param.EnterpriseId,
- RechargeAmount: param.Amount,
- TransferVoucherUrl: param.TransferVoucherUrl,
- Phone: phone,
- RechargeMethod: 1,
- Status: 1,
- InvoiceStatus: 1,
- CommitAt: time.Now(),
- }
- err := dao.RechargeRecordDao{}.Insert(&rechargeRecord)
- if err != nil {
- return nil, err
- }
- return &rechargeId, nil
- }
- // 获取微信支付CodeUrl
- func (s RechargeService) NativeApiServicePrepay(tradeId string, amount int64) (string, *time.Time, error) {
- var (
- mchID string = "1615933939" // 商户号
- mchCertificateSerialNumber string = "33DDFEC51BF5412F663B9B56510FD567B625FC68" // 商户证书序列号
- mchAPIv3Key string = "V10987654321younggee12345678910V" // 商户APIv3密钥,用于加密和解密平台证书
- )
- fmt.Println("充值的金额为:", amount)
- // 使用 utils 提供的函数从本地文件中加载商户私钥
- mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem") // 商户私钥,用于生成请求的签名
- if err != nil {
- log.Print("load merchant private key error")
- }
- ctx := context.Background()
- // 使用商户私钥等初始化 微信支付client,并使它具有自动定时获取微信支付平台证书的能力
- opts := []core.ClientOption{
- option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
- }
- client, err := core.NewClient(ctx, opts...)
- if err != nil {
- log.Printf("new wechat pay client err: %s", err)
- }
- // 采用 Native 支付方式
- svc := native.NativeApiService{Client: client}
- // 发送请求
- timeExpire := time.Now().Add(10 * time.Minute)
- resp, result, err := svc.Prepay(ctx,
- native.PrepayRequest{
- Appid: core.String("wxac396a3be7a16844"),
- Mchid: core.String("1615933939"),
- Description: core.String("样叽微信支付充值"),
- OutTradeNo: core.String(tradeId),
- TimeExpire: core.Time(timeExpire),
- Attach: core.String("微信支付充值"),
- NotifyUrl: core.String("https://www.weixin.qq.com/wxpay/pay.php"),
- SupportFapiao: core.Bool(true),
- Amount: &native.Amount{
- Currency: core.String("CNY"),
- Total: core.Int64(amount),
- },
- },
- )
- if err != nil {
- // 处理错误
- log.Printf("call Prepay err:%s", err)
- return "", nil, err
- } else {
- // 处理返回结果
- log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
- log.Println("codeUrl:", *resp.CodeUrl)
- }
- return *resp.CodeUrl, &timeExpire, nil
- }
- // 根据交易id查询微信是否扫码付款
- // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_4_2.shtml
- func (s RechargeService) QueryOrderByTradeId(tradeId string) (tradeState string, err error) {
- var (
- mchID string = "1615933939" // 商户号
- mchCertificateSerialNumber string = "33DDFEC51BF5412F663B9B56510FD567B625FC68" // 商户证书序列号
- mchAPIv3Key string = "V10987654321younggee12345678910V" // 商户APIv3密钥
- )
- // 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名
- mchPrivateKey, err := utils.LoadPrivateKeyWithPath("./apiclient_key.pem")
- if err != nil {
- log.Print("load merchant private key error")
- }
- ctx := context.Background()
- // 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
- opts := []core.ClientOption{
- option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
- }
- client, err := core.NewClient(ctx, opts...)
- if err != nil {
- log.Printf("new wechat pay client err: %s", err)
- }
- svc := native.NativeApiService{Client: client}
- resp, result, err := svc.QueryOrderByOutTradeNo(ctx,
- native.QueryOrderByOutTradeNoRequest{
- OutTradeNo: core.String(tradeId),
- Mchid: core.String("1615933939"),
- },
- )
- fmt.Printf("支付 %+v\n", resp)
- if err != nil {
- // 处理错误
- log.Printf("call QueryOrderByOutTradeNo err: %s", err)
- return "", err
- } else {
- // 处理返回结果
- log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
- }
- fmt.Printf("支付状态 %+v\n", *resp.TradeState)
- return *resp.TradeState, nil
- }
- // 余额管理——总金额、可用余额、冻结金额
- func (s RechargeService) ShowBalance(param *vo.BalanceParam) (*vo.ReBalanceShow, error) {
- reBalanceShow := new(vo.ReBalanceShow)
- enterprise, err := dao.EnterpriseDao{}.GetEnterpriseInfo(param.EnterpriseId)
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return reBalanceShow, nil
- } else {
- return nil, err
- }
- }
- reBalanceShow.TotalBalance = enterprise.Balance
- reBalanceShow.AvailBalance = enterprise.AvailableBalance
- reBalanceShow.FrozenBalance = enterprise.FrozenBalance
- return reBalanceShow, nil
- }
- // 余额管理——冻结记录
- func (s RechargeService) FrozenInfoList(param *vo.BalanceParam) (vo.ResultVO, error) {
- if param.Page <= 0 {
- param.Page = 1
- }
- if param.PageSize <= 0 {
- param.PageSize = 10
- }
- var result vo.ResultVO
- var reBalanceShows []*vo.ReFrozenInfo
- var selectionInfos []*entity.SelectionInfo
- var projects []*entity.Project
- if param.FrozenState == 1 {
- // 电商带货
- selectionInfos, _ = dao.SelectionInfoDAO{}.GetSelectionFrozenList(param.EnterpriseId)
- // 品牌种草
- projects, _ = dao.ProjectDAO{}.GetProjectFrozenList(param.EnterpriseId)
- // 本地生活
- } else {
- // 电商带货
- selectionInfos, _ = dao.SelectionInfoDAO{}.GetSelectionFrozenCancelList(param.EnterpriseId)
- // 品牌种草
- projects, _ = dao.ProjectDAO{}.GetProjectFrozenCancelList(param.EnterpriseId)
- // 本地生活
- }
- // 汇总结果
- for _, selection := range selectionInfos {
- // 获取商品详情字段
- var creatorName string
- var productName string
- var productPrice float64
- var mainImage string
- if selection.SubAccountId == 0 {
- enterprise, err := dao.EnterpriseDao{}.GetEnterprise(selection.EnterpriseID)
- if err == nil && enterprise != nil {
- creatorName = enterprise.BusinessName
- }
- } else {
- subAccount, err := dao.SubAccountDao{}.GetSubAccount(selection.SubAccountId)
- if err == nil && subAccount != nil {
- creatorName = subAccount.SubAccountName
- }
- }
- product, err := dao.ProductDAO{}.GetProductByID(selection.ProductID)
- if err == nil && product != nil {
- productName = product.ProductName
- productPrice = product.ProductPrice
- }
- mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(selection.ProductID)
- // 电商带货汇总
- reBalanceShow := &vo.ReFrozenInfo{
- ProductId: selection.ProductID,
- MainImage: mainImage,
- ProductName: productName,
- ProductPrice: productPrice,
- Platform: selection.Platform,
- CreatorName: creatorName,
- TaskType: "电商带货",
- FrozenBalance: selection.EstimatedCost,
- FrozenTime: selection.PayAt.Format("2006-01-02 15:04:05"),
- EnterpriseId: selection.EnterpriseID,
- SubAccountId: selection.SubAccountId,
- TaskId: selection.SelectionID,
- }
- if param.FrozenState == 2 {
- reBalanceShow.FrozenCancelBalance = selection.SettlementAmount
- }
- reBalanceShows = append(reBalanceShows, reBalanceShow)
- }
- for _, project := range projects {
- // 获取商品详情字段
- var creatorName string
- var productName string
- var productPrice float64
- var mainImage string
- if project.SubAccountId == 0 {
- enterprise, err := dao.EnterpriseDao{}.GetEnterprise(project.EnterpriseID)
- if err == nil && enterprise != nil {
- creatorName = enterprise.BusinessName
- }
- } else {
- subAccount, err := dao.SubAccountDao{}.GetSubAccount(project.SubAccountId)
- if err == nil && subAccount != nil {
- creatorName = subAccount.SubAccountName
- }
- }
- product, err := dao.ProductDAO{}.GetProductByID(project.ProductID)
- if err == nil && product != nil {
- productName = product.ProductName
- productPrice = product.ProductPrice
- }
- mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(project.ProductID)
- // 电商带货汇总
- reBalanceShow := &vo.ReFrozenInfo{
- ProductId: project.ProductID,
- MainImage: mainImage,
- ProductName: productName,
- ProductPrice: productPrice,
- Platform: project.ProjectPlatform,
- CreatorName: creatorName,
- TaskType: "品牌种草",
- FrozenBalance: project.PaymentAmount,
- FrozenTime: project.PayAt.Format("2006-01-02 15:04:05"),
- EnterpriseId: project.EnterpriseID,
- SubAccountId: project.SubAccountId,
- TaskId: project.ProjectId,
- }
- if param.FrozenState == 2 {
- reBalanceShow.FrozenCancelBalance = project.SettlementAmount
- }
- reBalanceShows = append(reBalanceShows, reBalanceShow)
- }
- startIndex := (param.Page - 1) * param.PageSize
- endIndex := startIndex + param.PageSize
- // 分页
- if startIndex >= len(reBalanceShows) {
- return result, nil
- }
- if endIndex > len(reBalanceShows) {
- endIndex = len(reBalanceShows)
- }
- result = vo.ResultVO{
- Page: param.Page,
- PageSize: param.PageSize,
- Total: int64(len(reBalanceShows)),
- Data: reBalanceShows[startIndex:endIndex],
- }
- return result, nil
- }
- // 充值管理——累计充值金额、确认中金额
- func (s RechargeService) ShowRecharge(param *vo.RechargeParam) (*vo.ReRechargeShow, error) {
- reRechargeShow := new(vo.ReRechargeShow)
- confirmingRecharge, _ := dao.RechargeRecordDao{}.GetRechargeAmount(param.EnterpriseId, 1)
- totalRecharge, _ := dao.RechargeRecordDao{}.GetRechargeAmount(param.EnterpriseId, 2)
- reRechargeShow.ConfirmingRecharge = confirmingRecharge
- reRechargeShow.TotalRecharge = totalRecharge
- return reRechargeShow, nil
- }
- // 充值管理——充值记录
- func (s RechargeService) RechargeInfoList(param *vo.RechargeParam) (vo.ResultVO, error) {
- if param.Page <= 0 {
- param.Page = 1
- }
- if param.PageSize <= 0 {
- param.PageSize = 10
- }
- var result vo.ResultVO
- var reRechargeInfos []*vo.ReRechargeInfo
- rechargeRecords, total, err := dao.RechargeRecordDao{}.RechargeInfoList(param)
- if err != nil {
- return result, err
- }
- for _, rechargeRecord := range rechargeRecords {
- var creatorName string
- enterprise, err := dao.EnterpriseDao{}.GetEnterprise(param.EnterpriseId)
- if err == nil && enterprise != nil {
- creatorName = enterprise.BusinessName
- }
- reRechargeInfo := &vo.ReRechargeInfo{
- RechargeId: rechargeRecord.RechargeID,
- CreatorName: creatorName,
- RechargeAmount: rechargeRecord.RechargeAmount,
- RechargeMethod: rechargeRecord.RechargeMethod,
- TransferVoucherUrl: rechargeRecord.TransferVoucherUrl,
- }
- if param.RechargeState == 1 {
- reRechargeInfo.CommitAt = rechargeRecord.CommitAt.Format("2006-01-02 15:04:05")
- } else if param.RechargeState == 2 {
- reRechargeInfo.ConfirmAt = rechargeRecord.ConfirmAt.Format("2006-01-02 15:04:05")
- } else if param.RechargeState == 3 {
- reRechargeInfo.RefuseAt = rechargeRecord.RefuseAt.Format("2006-01-02 15:04:05")
- reRechargeInfo.FailReason = rechargeRecord.FailReason
- }
- reRechargeInfos = append(reRechargeInfos, reRechargeInfo)
- }
- result = vo.ResultVO{
- Page: param.Page,
- PageSize: param.PageSize,
- Total: total,
- Data: reRechargeInfos,
- }
- return result, nil
- }
|