2025-10-10 07:13:36 -07:00

128 lines
3.2 KiB
Go

package payssion
import (
"bytes"
"encoding/json"
"fmt"
"github.com/perfect-panel/ppanel-server/pkg/md5"
"github.com/pkg/errors"
"go.uber.org/zap"
"io"
"log"
"net/http"
)
type Order struct {
Name string
OrderNo string
Amount float64
NotifyUrl string
ReturnUrl string
}
type Client struct {
Name string
ApiKey string
SecretKey string
QueryUrl string
CreateUrl string
PmId string
Currency string
}
func NewClient(apiKey string, secretKey, pmId, currency, queryUrl, createUrl string) *Client {
return &Client{
ApiKey: apiKey,
SecretKey: secretKey,
PmId: pmId,
Currency: currency,
QueryUrl: queryUrl,
CreateUrl: createUrl,
}
}
func (c *Client) CreateOrder(order Order) (string, error) {
content := fmt.Sprintf("%s|%s|%.2f|%s|%s|%s", c.ApiKey, c.PmId, order.Amount, "USD", order.OrderNo, c.SecretKey)
sign := md5.Sign(content)
params := map[string]string{
"api_key": c.ApiKey,
"pm_id": c.PmId,
"amount": fmt.Sprintf("%.2f", order.Amount),
"currency": "USD",
"description": "shop",
"order_id": order.OrderNo,
"api_sig": sign,
"return_url": order.ReturnUrl,
}
marshal, _ := json.Marshal(params)
resp, err := http.Post(c.CreateUrl, "application/json", bytes.NewBuffer(marshal))
if err != nil {
return "", err
}
all, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
log.Println(string(all))
result := make(map[string]interface{})
err = json.Unmarshal(all, &result)
if err != nil {
return "", err
}
result_code := result["result_code"]
if fmt.Sprintf("%v", result_code) != "200" {
return "", errors.New(result["description"].(string))
}
url := result["redirect_url"]
if url == nil {
return "", errors.New(string(all))
}
return url.(string), nil
}
func (c *Client) QueryOrder(orderNo string) (queryResult *QueryResult, err error) {
content := fmt.Sprintf("%s|%s|%s", c.ApiKey, orderNo, c.SecretKey)
sign := md5.Sign(content)
params := map[string]string{
"api_key": c.ApiKey,
"order_id": orderNo,
"api_sig": sign,
}
marshal, _ := json.Marshal(params)
resp, err := http.Post(c.QueryUrl, "application/json", bytes.NewBuffer(marshal))
if err != nil {
return nil, err
}
all, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
zap.S().Infof("Payssion QueryOrderDetail result: %s", string(all))
err = json.Unmarshal(all, &queryResult)
return queryResult, err
}
type QueryResult struct {
Transaction struct {
TransactionID string `json:"transaction_id"`
Description string `json:"description"`
AppName string `json:"app_name"`
PmID string `json:"pm_id"`
Amount string `json:"amount"`
Currency string `json:"currency"`
OrderID string `json:"order_id"`
Paid string `json:"paid"`
Net string `json:"net"`
State string `json:"state"`
Fee string `json:"fee"`
Refund string `json:"refund"`
RefundFee string `json:"refund_fee"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
Fees string `json:"fees"`
FeesAdd string `json:"fees_add"`
RefundFees string `json:"refund_fees"`
} `json:"transaction"`
ResultCode int64 `json:"result_code"`
}