Skip to content

Commit

Permalink
update http request
Browse files Browse the repository at this point in the history
  • Loading branch information
iGoogle-ink committed Oct 1, 2023
1 parent 13dbee5 commit b692e09
Show file tree
Hide file tree
Showing 13 changed files with 378 additions and 355 deletions.
319 changes: 14 additions & 305 deletions alipay/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ package alipay
import (
"context"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"encoding/json"
"fmt"
"hash"
"sync"
"time"

"github.com/go-pay/gopay"
Expand Down Expand Up @@ -32,6 +36,10 @@ type Client struct {
autoSign bool
DebugSwitch gopay.DebugSwitch
location *time.Location
hc *xhttp.Client
sha1Hash hash.Hash
sha256Hash hash.Hash
mu sync.Mutex
}

// 初始化支付宝客户端
Expand All @@ -55,6 +63,9 @@ func NewClient(appid, privateKey string, isProd bool) (client *Client, err error
IsProd: isProd,
privateKey: priKey,
DebugSwitch: gopay.DebugOff,
hc: xhttp.NewClient(),
sha1Hash: sha1.New(),
sha256Hash: sha256.New(),
}
return client, nil
}
Expand All @@ -76,7 +87,7 @@ func (a *Client) AutoVerifySign(alipayPublicKeyContent []byte) {
// SetBodySize 设置http response body size(MB)
func (a *Client) SetBodySize(sizeMB int) {
if sizeMB > 0 {
a.bodySize = sizeMB
a.hc.SetBodySize(sizeMB)
}
}

Expand Down Expand Up @@ -123,7 +134,7 @@ func (a *Client) RequestParam(bm gopay.BodyMap, method string) (string, error) {

// check sign
if bm.GetString("sign") == "" {
sign, err = a.getRsaSign(bm, bm.GetString("sign_type"), a.privateKey)
sign, err = a.getRsaSign(bm, bm.GetString("sign_type"))
if err != nil {
return "", fmt.Errorf("GetRsaSign Error: %w", err)
}
Expand All @@ -136,229 +147,6 @@ func (a *Client) RequestParam(bm gopay.BodyMap, method string) (string, error) {
return bm.EncodeURLParams(), nil
}

// PostAliPayAPISelfV2 支付宝接口自行实现方法
// 注意:biz_content 需要自行通过bm.SetBodyMap()设置,不设置则没有此参数
// 示例:请参考 client_test.go 的 TestClient_PostAliPayAPISelfV2() 方法
func (a *Client) PostAliPayAPISelfV2(ctx context.Context, bm gopay.BodyMap, method string, aliRsp any) (err error) {
var (
bs, bodyBs []byte
)
// check if there is biz_content
bz := bm.GetInterface("biz_content")
if bzBody, ok := bz.(gopay.BodyMap); ok {
if bodyBs, err = json.Marshal(bzBody); err != nil {
return fmt.Errorf("json.Marshal(%v):%w", bzBody, err)
}
bm.Set("biz_content", string(bodyBs))
}

if bs, err = a.doAliPaySelf(ctx, bm, method); err != nil {
return err
}
if err = json.Unmarshal(bs, aliRsp); err != nil {
return err
}
return nil
}

// 向支付宝发送自定义请求
func (a *Client) doAliPaySelf(ctx context.Context, bm gopay.BodyMap, method string) (bs []byte, err error) {
var (
url, sign string
)
bm.Set("method", method)
// check public parameter
a.checkPublicParam(bm)
// check sign
if bm.GetString("sign") == "" {
sign, err = a.getRsaSign(bm, bm.GetString("sign_type"), a.privateKey)
if err != nil {
return nil, fmt.Errorf("GetRsaSign Error: %w", err)
}
bm.Set("sign", sign)
}
if a.DebugSwitch == gopay.DebugOn {
xlog.Debugf("Alipay_Request: %s", bm.JsonBody())
}

httpClient := xhttp.NewClient()
if a.bodySize > 0 {
httpClient.SetBodySize(a.bodySize)
}
if a.IsProd {
url = baseUrlUtf8
} else {
url = sandboxBaseUrlUtf8
}
res, bs, err := httpClient.Type(xhttp.TypeForm).Post(url).SendString(bm.EncodeURLParams()).EndBytes(ctx)
if err != nil {
return nil, err
}
if a.DebugSwitch == gopay.DebugOn {
xlog.Debugf("Alipay_Response: %s%d %s%s", xlog.Red, res.StatusCode, xlog.Reset, string(bs))
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", res.StatusCode)
}
return bs, nil
}

// 向支付宝发送请求
func (a *Client) doAliPay(ctx context.Context, bm gopay.BodyMap, method string, authToken ...string) (bs []byte, err error) {
var (
bizContent, url string
bodyBs []byte
)
if bm != nil {
_, has := appAuthTokenInBizContent[method]
if has {
if bodyBs, err = json.Marshal(bm); err != nil {
return nil, fmt.Errorf("json.Marshal:%w", err)
}
bizContent = string(bodyBs)
bm.Remove("app_auth_token")
} else {
aat := bm.GetString("app_auth_token")
bm.Remove("app_auth_token")
if bodyBs, err = json.Marshal(bm); err != nil {
return nil, fmt.Errorf("json.Marshal:%w", err)
}
bizContent = string(bodyBs)
bm.Set("app_auth_token", aat)
}
}
// 处理公共参数
param, err := a.pubParamsHandle(bm, method, bizContent, authToken...)
if err != nil {
return nil, err
}
switch method {
case "alipay.trade.app.pay", "alipay.fund.auth.order.app.freeze":
return []byte(param), nil
case "alipay.trade.wap.pay", "alipay.trade.page.pay", "alipay.user.certify.open.certify":
if !a.IsProd {
return []byte(sandboxBaseUrl + "?" + param), nil
}
return []byte(baseUrl + "?" + param), nil
default:
httpClient := xhttp.NewClient()
if a.bodySize > 0 {
httpClient.SetBodySize(a.bodySize)
}
url = baseUrlUtf8
if !a.IsProd {
url = sandboxBaseUrlUtf8
}
res, bs, err := httpClient.Type(xhttp.TypeForm).Post(url).SendString(param).EndBytes(ctx)
if err != nil {
return nil, err
}
if a.DebugSwitch == gopay.DebugOn {
xlog.Debugf("Alipay_Response: %s%d %s%s", xlog.Red, res.StatusCode, xlog.Reset, string(bs))
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", res.StatusCode)
}
return bs, nil
}
}

// 向支付宝发送请求
func (a *Client) DoAliPay(ctx context.Context, bm gopay.BodyMap, method string, authToken ...string) (bs []byte, err error) {
var (
bizContent, url string
bodyBs []byte
)
if bm != nil {
_, has := appAuthTokenInBizContent[method]
if has {
if bodyBs, err = json.Marshal(bm); err != nil {
return nil, fmt.Errorf("json.Marshal:%w", err)
}
bizContent = string(bodyBs)
bm.Remove("app_auth_token")
} else {
aat := bm.GetString("app_auth_token")
bm.Remove("app_auth_token")
if bodyBs, err = json.Marshal(bm); err != nil {
return nil, fmt.Errorf("json.Marshal:%w", err)
}
bizContent = string(bodyBs)
bm.Set("app_auth_token", aat)
}
}
// 处理公共参数
param, err := a.pubParamsHandle(bm, method, bizContent, authToken...)
if err != nil {
return nil, err
}
switch method {
case "alipay.trade.app.pay", "alipay.fund.auth.order.app.freeze":
return []byte(param), nil
case "alipay.trade.wap.pay", "alipay.trade.page.pay", "alipay.user.certify.open.certify":
if !a.IsProd {
return []byte(sandboxBaseUrl + "?" + param), nil
}
return []byte(baseUrl + "?" + param), nil
default:
httpClient := xhttp.NewClient()
if a.bodySize > 0 {
httpClient.SetBodySize(a.bodySize)
}
url = baseUrlUtf8
if !a.IsProd {
url = sandboxBaseUrlUtf8
}
res, bs, err := httpClient.Type(xhttp.TypeForm).Post(url).SendString(param).EndBytes(ctx)
if err != nil {
return nil, err
}
if a.DebugSwitch == gopay.DebugOn {
xlog.Debugf("Alipay_Response: %s%d %s%s", xlog.Red, res.StatusCode, xlog.Reset, string(bs))
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", res.StatusCode)
}
return bs, nil
}
}

// 保持和官方 SDK 命名方式一致
func (a *Client) PageExecute(ctx context.Context, bm gopay.BodyMap, method string, authToken ...string) (url string, err error) {
var (
bizContent string
bodyBs []byte
)
if bm != nil {
_, has := appAuthTokenInBizContent[method]
if has {
if bodyBs, err = json.Marshal(bm); err != nil {
return "", fmt.Errorf("json.Marshal:%w", err)
}
bizContent = string(bodyBs)
bm.Remove("app_auth_token")
} else {
aat := bm.GetString("app_auth_token")
bm.Remove("app_auth_token")
if bodyBs, err = json.Marshal(bm); err != nil {
return "", fmt.Errorf("json.Marshal:%w", err)
}
bizContent = string(bodyBs)
bm.Set("app_auth_token", aat)
}
}
// 处理公共参数
param, err := a.pubParamsHandle(bm, method, bizContent, authToken...)
if err != nil {
return "", err
}

if !a.IsProd {
return sandboxBaseUrl + "?" + param, nil
}
return baseUrl + "?" + param, nil
}

// 公共参数处理
func (a *Client) pubParamsHandle(bm gopay.BodyMap, method, bizContent string, authToken ...string) (param string, err error) {
pubBody := make(gopay.BodyMap)
Expand Down Expand Up @@ -412,7 +200,7 @@ func (a *Client) pubParamsHandle(bm gopay.BodyMap, method, bizContent string, au
pubBody.Set("biz_content", bizContent)
}
// sign
sign, err := a.getRsaSign(pubBody, pubBody.GetString("sign_type"), a.privateKey)
sign, err := a.getRsaSign(pubBody, pubBody.GetString("sign_type"))
if err != nil {
return "", fmt.Errorf("GetRsaSign Error: %w", err)
}
Expand Down Expand Up @@ -454,82 +242,3 @@ func (a *Client) checkPublicParam(bm gopay.BodyMap) {
bm.Set("app_auth_token", a.AppAuthToken)
}
}

// 文件上传
func (a *Client) FileRequest(ctx context.Context, bm gopay.BodyMap, file *util.File, method string) (bs []byte, err error) {
var (
bodyStr string
bodyBs []byte
aat string
)
if bm != nil {
aat = bm.GetString("app_auth_token")
bm.Remove("app_auth_token")
if bodyBs, err = json.Marshal(bm); err != nil {
return nil, fmt.Errorf("json.Marshal:%w", err)
}
bodyStr = string(bodyBs)
}
pubBody := make(gopay.BodyMap)
pubBody.Set("app_id", a.AppId).
Set("method", method).
Set("format", "JSON").
Set("charset", a.Charset).
Set("sign_type", a.SignType).
Set("version", "1.0").
Set("scene", "SYNC_ORDER").
Set("timestamp", time.Now().Format(util.TimeLayout))

if a.AppCertSN != util.NULL {
pubBody.Set("app_cert_sn", a.AppCertSN)
}
if a.AliPayRootCertSN != util.NULL {
pubBody.Set("alipay_root_cert_sn", a.AliPayRootCertSN)
}
if a.ReturnUrl != util.NULL {
pubBody.Set("return_url", a.ReturnUrl)
}
if a.location != nil {
pubBody.Set("timestamp", time.Now().In(a.location).Format(util.TimeLayout))
}
if a.NotifyUrl != util.NULL { //如果返回url为空,传过来的返回url不为空
//fmt.Println("url不为空?", a.NotifyUrl)
pubBody.Set("notify_url", a.NotifyUrl)
}
//fmt.Println("notify,", pubBody.JsonBody())
if a.AppAuthToken != util.NULL {
pubBody.Set("app_auth_token", a.AppAuthToken)
}
if aat != util.NULL {
pubBody.Set("app_auth_token", aat)
}
if bodyStr != util.NULL {
pubBody.Set("biz_content", bodyStr)
}
sign, err := a.getRsaSign(pubBody, pubBody.GetString("sign_type"), a.privateKey)
if err != nil {
return nil, fmt.Errorf("GetRsaSign Error: %w", err)
}
//pubBody.Set("file_content", file.Content)
pubBody.Set("sign", sign)
if a.DebugSwitch == gopay.DebugOn {
xlog.Debugf("Alipay_Request: %s", pubBody.JsonBody())
}
param := pubBody.EncodeURLParams()
url := baseUrlUtf8 + "&" + param
bm.Reset()
bm.SetFormFile("file_content", file)
httpClient := xhttp.NewClient()
res, bs, err := httpClient.Type(xhttp.TypeMultipartFormData).Post(url).
SendMultipartBodyMap(bm).EndBytes(ctx)
if err != nil {
return nil, err
}
if a.DebugSwitch == gopay.DebugOn {
xlog.Debugf("Alipay_Response: %s%d %s%s", xlog.Red, res.StatusCode, xlog.Reset, string(bs))
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("HTTP Request Error, StatusCode = %d", res.StatusCode)
}
return bs, nil
}
4 changes: 2 additions & 2 deletions alipay/common_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ func systemOauthToken(ctx context.Context, appId string, privateKey *rsa.Private
if !isProd {
baseUrl = sandboxBaseUrlUtf8
}
_, bs, err = xhttp.NewClient().Type(xhttp.TypeForm).Post(baseUrl).SendString(bm.EncodeURLParams()).EndBytes(ctx)
_, bs, err = xhttp.NewClient().Req(xhttp.TypeForm).Post(baseUrl).SendString(bm.EncodeURLParams()).EndBytes(ctx)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -220,7 +220,7 @@ func MonitorHeartbeatSyn(ctx context.Context, appId string, privateKey, signType
}
bm.Set("sign", sign)

_, bs, err = xhttp.NewClient().Type(xhttp.TypeForm).Post(baseUrlUtf8).SendString(bm.EncodeURLParams()).EndBytes(ctx)
_, bs, err = xhttp.NewClient().Req(xhttp.TypeForm).Post(baseUrlUtf8).SendString(bm.EncodeURLParams()).EndBytes(ctx)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit b692e09

Please sign in to comment.