plugins/plugins/alipay_redpack/internal/alipay_redpack.go

138 lines
2.8 KiB
Go

package internal
import (
"context"
"encoding/json"
"fmt"
"gitea.cdlsxd.cn/sdk/plugin/proto"
"plugins/alipay_redpack/internal/po"
"plugins/utils/alipay"
)
// 插件通信信息,若不对应则会报错panic
const (
Tag = "alipay_redpack"
Version = 1
CookieKey = "alipay_redpack"
CookieValue = "alipay_redpack"
)
const baseUri = "https://openapi.alipay.com/gateway.do"
const (
// 支持幂等请求 https://opendocs.alipay.com/open/02byvi?pathHash=b367173b
orderMethod = "alipay.fund.trans.uni.transfer"
queryMethod = "alipay.fund.trans.common.query"
)
type AlipayRedPackService struct{}
func (s *AlipayRedPackService) Order(ctx context.Context, request *proto.OrderRequest) (resp2 *proto.OrderResponse, respErr error) {
defer func() {
if err := recover(); err != nil {
respErr = fmt.Errorf("panic: %v", err)
}
}()
c, err := transConfig(request.Config)
if err != nil {
return nil, err
}
poReq, err := orderReq(request.Order, request.Product)
if err != nil {
return nil, proto.ErrorParamFail(err.Error())
}
param, err := c.paramReq(poReq, orderMethod)
if err != nil {
return nil, err
}
uv, err := req(c, param)
if err != nil {
return nil, err
}
bodyBytes, _, err := Post(ctx, uv)
if err != nil {
return nil, err
}
var response *po.OrderResp
if err = json.Unmarshal(bodyBytes, &response); err != nil {
return nil, proto.ErrorResponseFail(err.Error())
}
return orderResp(request, response), nil
}
func (s *AlipayRedPackService) Query(ctx context.Context, request *proto.QueryRequest) (resp2 *proto.QueryResponse, respErr error) {
defer func() {
if err := recover(); err != nil {
respErr = fmt.Errorf("panic: %v", err)
}
}()
c, err := transConfig(request.Config)
if err != nil {
return nil, err
}
param, err := c.paramReq(queryReq(request.Order), queryMethod)
if err != nil {
return nil, err
}
uv, err := req(c, param)
if err != nil {
return nil, err
}
bodyBytes, _, err := Post(ctx, uv)
if err != nil {
return nil, err
}
var response po.QueryResp
if err = json.Unmarshal(bodyBytes, &response); err != nil {
return nil, proto.ErrorResponseFail(err.Error())
}
return queryResp(request, response), nil
}
func (s *AlipayRedPackService) Notify(_ context.Context, request *proto.NotifyRequest) (resp2 *proto.NotifyResponse, respErr error) {
defer func() {
if err := recover(); err != nil {
respErr = fmt.Errorf("panic: %v", err)
}
}()
c, err := transConfig(request.Config)
if err != nil {
return nil, err
}
n := notifyReq(request)
cert, err := alipay.GetCert(c.AppId)
if err != nil {
return nil, err
}
b, err := Verify(n, cert.PublicKey)
if err != nil {
return nil, proto.ErrorSignFail(err.Error())
}
if !b {
return nil, proto.ErrorSignFail("验签失败")
}
return notifyResp(n)
}