feat: update

This commit is contained in:
yanghao05
2025-04-15 21:34:39 +08:00
parent ca08568e1a
commit 8d601d456e
3 changed files with 71 additions and 10 deletions

View File

@@ -1,6 +1,10 @@
package http
import (
_ "embed"
"encoding/json"
"strings"
"text/template"
"time"
"quyun/app/models"
@@ -8,7 +12,6 @@ import (
"quyun/database/schemas/public/model"
"quyun/providers/wepay"
"github.com/go-pay/gopay/wechat/v3"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
"github.com/pkg/errors"
@@ -24,7 +27,7 @@ type posts struct {
}
// List posts
// @Router /posts [get]
// @Router / [get]
// @Bind pagination query
// @Bind query query
// @Bind user local
@@ -49,26 +52,29 @@ func (ctl *posts) Mine(ctx fiber.Ctx, pagination *requests.Pagination, query *Li
return models.Users.PostList(ctx.Context(), 1, pagination, query.Keyword)
}
//go:embed buy.html.tpl
var buyTpl string
// Buy
// @Router /buy/:id [get]
// @Bind id path
func (ctl *posts) Buy(ctx fiber.Ctx, id int64) (*wechat.JSAPIPayParams, error) {
func (ctl *posts) Buy(ctx fiber.Ctx, id int64) error {
var userId int64 = 1
user, err := models.Users.GetByID(ctx.Context(), userId)
if err != nil {
return nil, errors.Wrapf(err, " failed to get user: %d", userId)
return errors.Wrapf(err, " failed to get user: %d", userId)
}
post, err := models.Posts.GetByID(ctx.Context(), id)
if err != nil {
return nil, errors.Wrapf(err, " failed to get post: %d", id)
return errors.Wrapf(err, " failed to get post: %d", id)
}
// create order
order, err := models.Orders.Create(ctx.Context(), userId, post.ID)
if err != nil {
return nil, errors.Wrap(err, "订单创建失败")
return errors.Wrap(err, "订单创建失败")
}
prePayResp, err := ctl.wepay.V3TransactionJsapi(ctx.Context(), func(bm *wepay.BodyMap) {
@@ -80,8 +86,30 @@ func (ctl *posts) Buy(ctx fiber.Ctx, id int64) (*wechat.JSAPIPayParams, error) {
})
if err != nil {
log.Errorf("wepay.V3TransactionJsapi err: %v", err)
return nil, errors.Wrap(err, "微信支付失败")
return errors.Wrap(err, "微信支付失败")
}
return prePayResp.PaySignOfJSAPI()
signature, err := prePayResp.PaySignOfJSAPI()
if err != nil {
return errors.Wrap(err, "failed to get pay sign")
}
// render buyTpl with html/template
tpl, err := template.New("buy").Parse(buyTpl)
if err != nil {
return errors.Wrap(err, "failed to parse template")
}
signatureBytes, err := json.Marshal(signature)
if err != nil {
return errors.Wrap(err, "failed to marshal signature")
}
var buf strings.Builder
if err := tpl.Execute(&buf, map[string]interface{}{"signature": string(signatureBytes)}); err != nil {
return errors.Wrap(err, "failed to execute template")
}
ctx.Set("Content-Type", "text/html; charset=utf-8")
return ctx.SendString(buf.String())
}