feat: add online payment management and checkout
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-15 09:26:40 +08:00
parent 5353a4a128
commit dc2efcde08
41 changed files with 4855 additions and 21 deletions

View File

@@ -0,0 +1,330 @@
package payments
import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math"
"net"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
type alipay struct {
app, seller, notify string
priv *rsa.PrivateKey
alipayPub *rsa.PublicKey
endpoint string
client *http.Client
}
func newAlipayFromEnv() (Provider, error) { return NewProvider("alipay", ConfigFromEnv("alipay")) }
func newAlipay(config Config) (Provider, error) {
app, e := config.required("ALIPAY_APP_ID")
if e != nil {
return nil, e
}
seller, e := config.required("ALIPAY_SELLER_ID")
if e != nil {
return nil, e
}
notify, e := config.required("ALIPAY_NOTIFY_URL")
if e != nil {
return nil, e
}
if e = validateNotifyURL("ALIPAY_NOTIFY_URL", notify); e != nil {
return nil, e
}
pk, e := config.required("ALIPAY_PRIVATE_KEY")
if e != nil {
return nil, e
}
priv, e := privateKey(pk)
if e != nil {
return nil, e
}
pubs, e := config.required("ALIPAY_PUBLIC_KEY")
if e != nil {
return nil, e
}
pub, e := publicKey(pubs)
if e != nil {
return nil, e
}
return &alipay{app: app, seller: seller, notify: notify, priv: priv, alipayPub: pub, endpoint: alipayEndpoint, client: &http.Client{Timeout: 15 * time.Second, Transport: &http.Transport{DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext}}}, nil
}
func (a *alipay) call(ctx context.Context, method string, args map[string]string) (map[string]any, error) {
v := url.Values{"app_id": {a.app}, "method": {method}, "format": {"JSON"}, "charset": {"utf-8"}, "sign_type": {"RSA2"}, "timestamp": {time.Now().Format("2006-01-02 15:04:05")}, "version": {"1.0"}}
if method == "alipay.trade.precreate" {
v.Set("notify_url", a.notify)
}
for k, x := range args {
v.Set(k, x)
}
sig, e := signRSA(a.priv, canonicalValues(v, "sign"))
if e != nil {
return nil, e
}
v.Set("sign", sig)
req, e := http.NewRequestWithContext(ctx, "POST", a.endpoint, strings.NewReader(v.Encode()))
if e != nil {
return nil, e
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
resp, e := a.client.Do(req)
if e != nil {
return nil, e
}
defer resp.Body.Close()
raw, e := readLimited(resp.Body)
if e != nil {
return nil, e
}
var envelope map[string]json.RawMessage
if e = json.Unmarshal(raw, &envelope); e != nil {
return nil, e
}
payload := envelope[strings.ReplaceAll(method, ".", "_")+"_response"]
var signature string
if e = json.Unmarshal(envelope["sign"], &signature); e != nil {
return nil, errors.New("missing alipay response signature")
}
if e = verifyRSA(a.alipayPub, string(payload), signature); e != nil {
return nil, e
}
var out map[string]any
if e = json.Unmarshal(raw, &out); e != nil {
return nil, e
}
if resp.StatusCode/100 != 2 {
return nil, fmt.Errorf("alipay HTTP %d", resp.StatusCode)
}
return out, nil
}
func (a *alipay) verifyResponse(r map[string]any) error {
if r == nil {
return errors.New("missing alipay response")
}
return nil
}
func (a *alipay) Create(ctx context.Context, no string, amount int64, title string) (string, error) {
if amount <= 0 {
return "", errors.New("invalid amount")
}
raw, _ := json.Marshal(map[string]any{"out_trade_no": no, "total_amount": fmt.Sprintf("%d.%02d", amount/100, amount%100), "subject": title, "product_code": "FACE_TO_FACE_PAYMENT"})
o, e := a.call(ctx, "alipay.trade.precreate", map[string]string{"biz_content": string(raw)})
if e != nil {
return "", e
}
r, _ := o["alipay_trade_precreate_response"].(map[string]any)
if e = a.verifyResponse(r); e != nil {
return "", e
}
if r["code"] != "10000" {
return "", fmt.Errorf("alipay: %v", r["sub_msg"])
}
q, _ := r["qr_code"].(string)
if q == "" {
return "", errors.New("missing qr_code")
}
return q, nil
}
func (a *alipay) Query(ctx context.Context, no string) (Notification, error) {
raw, _ := json.Marshal(map[string]string{"out_trade_no": no})
o, e := a.call(ctx, "alipay.trade.query", map[string]string{"biz_content": string(raw)})
if e != nil {
return Notification{}, e
}
r, _ := o["alipay_trade_query_response"].(map[string]any)
if e = a.verifyResponse(r); e != nil {
return Notification{}, e
}
if r["code"] != "10000" {
return Notification{}, fmt.Errorf("alipay query: %v", r["sub_msg"])
}
if got, _ := r["out_trade_no"].(string); got != no {
return Notification{}, errors.New("merchant order mismatch")
}
n := Notification{EventID: "query-" + no, MerchantOrderNo: no, Currency: "CNY"}
n.TradeNo, _ = r["trade_no"].(string)
if n.TradeNo != "" {
n.EventID = "query-" + n.TradeNo
}
st, _ := r["trade_status"].(string)
n.Paid = st == "TRADE_SUCCESS" || st == "TRADE_FINISHED"
if v, ok := r["total_amount"].(string); ok {
n.AmountCents, e = parseAlipayAmount(v)
}
if n.Paid && (n.AmountCents <= 0 || n.TradeNo == "") {
return Notification{}, errors.New("incomplete paid query")
}
return n, e
}
func (a *alipay) Close(ctx context.Context, no string) error {
rawQuery, _ := json.Marshal(map[string]string{"out_trade_no": no})
o, e := a.call(ctx, "alipay.trade.query", map[string]string{"biz_content": string(rawQuery)})
if e != nil {
return e
}
r, _ := o["alipay_trade_query_response"].(map[string]any)
if r == nil {
return errors.New("missing close query response")
}
if r["code"] != "10000" {
return fmt.Errorf("alipay close query: %v", r["sub_code"])
}
if r["out_trade_no"] != no {
return errors.New("close identity mismatch")
}
if r["trade_status"] == "TRADE_CLOSED" {
return nil
}
raw, _ := json.Marshal(map[string]string{"out_trade_no": no})
return a.simple(ctx, "alipay.trade.close", map[string]string{"biz_content": string(raw)})
}
func (a *alipay) Refund(ctx context.Context, no, refund string, amount int64) error {
if amount <= 0 {
return errors.New("invalid refund amount")
}
raw, _ := json.Marshal(map[string]any{"out_trade_no": no, "refund_amount": fmt.Sprintf("%d.%02d", amount/100, amount%100), "out_request_no": refund})
return a.simple(ctx, "alipay.trade.refund", map[string]string{"biz_content": string(raw)})
}
func (a *alipay) simple(ctx context.Context, m string, p map[string]string) error {
o, e := a.call(ctx, m, p)
if e != nil {
return e
}
var r map[string]any
for _, x := range o {
if z, ok := x.(map[string]any); ok {
r = z
break
}
}
if e = a.verifyResponse(r); e != nil {
return e
}
if m == "alipay.trade.close" && r["sub_code"] == "ACQ.TRADE_HAS_CLOSE" {
return nil
}
if r != nil && r["code"] != "10000" {
return fmt.Errorf("alipay: %v", r["sub_msg"])
}
return nil
}
func (a *alipay) Verify(req *http.Request) (Notification, error) {
if req == nil {
return Notification{}, errors.New("nil request")
}
if req.URL.RawQuery != "" {
return Notification{}, errors.New("query parameters not allowed")
}
if e := req.ParseForm(); e != nil {
return Notification{}, e
}
if hasDuplicate(req.PostForm) {
return Notification{}, errors.New("duplicate field")
}
f := req.PostForm
if f.Get("app_id") != a.app || f.Get("seller_id") != a.seller || f.Get("sign_type") != "RSA2" {
return Notification{}, errors.New("merchant identity mismatch")
}
sig := f.Get("sign")
if sig == "" {
return Notification{}, errors.New("missing sign")
}
b, e := base64.StdEncoding.DecodeString(sig)
if e != nil {
return Notification{}, e
}
m := url.Values{}
for k, v := range f {
if k != "sign" && k != "sign_type" {
m[k] = v
}
}
h := sha256.Sum256([]byte(canonicalValues(m, "")))
if e = rsa.VerifyPKCS1v15(a.alipayPub, crypto.SHA256, h[:], b); e != nil {
return Notification{}, errors.New("invalid alipay signature")
}
n := Notification{EventID: f.Get("notify_id"), MerchantOrderNo: f.Get("out_trade_no"), TradeNo: f.Get("trade_no"), Currency: "CNY", Paid: f.Get("trade_status") == "TRADE_SUCCESS" || f.Get("trade_status") == "TRADE_FINISHED"}
n.AmountCents, e = parseAlipayAmount(f.Get("total_amount"))
if e == nil && (n.AmountCents <= 0 || n.EventID == "" || n.MerchantOrderNo == "" || n.TradeNo == "") {
return Notification{}, errors.New("incomplete payment notification")
}
if c := f.Get("currency"); c != "" && c != "CNY" {
return Notification{}, errors.New("currency mismatch")
}
return n, e
}
func canonicalValues(v url.Values, skip string) string {
keys := make([]string, 0, len(v))
for k := range v {
if k != skip {
keys = append(keys, k)
}
}
sort.Strings(keys)
p := make([]string, 0, len(keys))
for _, k := range keys {
p = append(p, k+"="+v.Get(k))
}
return strings.Join(p, "&")
}
func canonicalMap(v map[string]string) string {
u := url.Values{}
for k, x := range v {
u.Set(k, x)
}
return canonicalValues(u, "")
}
func hasDuplicate(v url.Values) bool {
for _, x := range v {
if len(x) != 1 {
return true
}
}
return false
}
func parseAlipayAmount(s string) (int64, error) {
p := strings.Split(s, ".")
if len(p) > 2 || p[0] == "" {
return 0, errors.New("invalid amount")
}
frac := "00"
if len(p) == 2 {
if len(p[1]) < 1 || len(p[1]) > 2 {
return 0, errors.New("invalid amount")
}
frac = p[1]
if len(frac) == 1 {
frac += "0"
}
}
for _, part := range []string{p[0], frac} {
for _, r := range part {
if r < '0' || r > '9' {
return 0, errors.New("invalid amount")
}
}
}
y, e := strconv.ParseInt(p[0], 10, 64)
if e != nil {
return 0, e
}
f, _ := strconv.ParseInt(frac, 10, 64)
if y > (math.MaxInt64-f)/100 {
return 0, errors.New("amount overflow")
}
return y*100 + f, nil
}