Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typo && feat #3

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 38 additions & 25 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@ import (
"crypto/tls"
"errors"
"fmt"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-resty/resty/v2"
"github.com/goccy/go-json"
"github.com/hiscaler/gox/stringx"
"github.com/hiscaler/temu-go/config"
"github.com/hiscaler/temu-go/entity"
"github.com/hiscaler/temu-go/normal"
"log/slog"
"net"
"net/http"
"os"
"sort"
"strings"
"time"

validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-resty/resty/v2"
"github.com/goccy/go-json"
"github.com/hiscaler/gox/stringx"
"github.com/hiscaler/temu-go/config"
"github.com/hiscaler/temu-go/entity"
"github.com/hiscaler/temu-go/normal"
)

const (
Expand Down Expand Up @@ -133,22 +134,20 @@ func parseRegionId(regionId int) int {
return regionId
}

func NewClient(config config.Config) *Client {
func NewClient(cfg config.Config) *Client {
var l *slog.Logger
debug := config.Debug
if config.Logger != nil {
l = config.Logger
debug := cfg.Debug
if cfg.Logger != nil {
l = cfg.Logger
} else {
if debug {
l = slog.New(slog.NewTextHandler(os.Stdout, nil))
} else {
l = slog.New(slog.NewJSONHandler(os.Stdout, nil))
}
}
urls := map[int]struct {
Prod string
Test string
}{

urls := map[int]config.URLPair{
entity.ChinaRegionId: {
Prod: "https://openapi.kuajingmaihuo.com/openapi/router",
Test: "https://kj-openapi.temudemo.com/openapi/router",
Expand All @@ -162,11 +161,25 @@ func NewClient(config config.Config) *Client {
Test: "http://openapi-b-eu.temudemo.com/openapi/router",
},
}
env := strings.ToLower(config.Env)

if cfg.OverwriteUrls != nil {
for regionId, overwriteURL := range cfg.OverwriteUrls {
if _, exists := urls[regionId]; exists {
if overwriteURL.Prod != "" {
urls[regionId] = config.URLPair{Prod: overwriteURL.Prod, Test: urls[regionId].Test}
}
if overwriteURL.Test != "" {
urls[regionId] = config.URLPair{Prod: urls[regionId].Prod, Test: overwriteURL.Test}
}
}
}
}

env := strings.ToLower(cfg.Env)
if env != prodEnv {
env = testEnv
}
regionId := parseRegionId(config.RegionId)
regionId := parseRegionId(cfg.RegionId)
url := ""
if v, ok := urls[regionId]; ok {
if env == prodEnv {
Expand All @@ -192,11 +205,11 @@ func NewClient(config config.Config) *Client {
"User-Agent": UserAgent,
}).
SetAllowGetMethodPayload(true).
SetTimeout(config.Timeout * time.Second).
SetTimeout(cfg.Timeout * time.Second).
SetTransport(&http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !config.VerifySSL},
TLSClientConfig: &tls.Config{InsecureSkipVerify: !cfg.VerifySSL},
DialContext: (&net.Dialer{
Timeout: config.Timeout * time.Second,
Timeout: cfg.Timeout * time.Second,
}).DialContext,
}).
OnBeforeRequest(func(client *resty.Client, request *resty.Request) error {
Expand All @@ -212,15 +225,15 @@ func NewClient(config config.Config) *Client {
return e
}
}
values["app_key"] = config.AppKey
values["app_secret"] = config.AppSecret
values["access_token"] = config.AccessToken
values["app_key"] = cfg.AppKey
values["app_secret"] = cfg.AppSecret
values["access_token"] = cfg.AccessToken
values["data_type"] = "JSON"
values["version"] = "V1"
values["timestamp"] = time.Now().Unix()
values["type"] = request.URL
request.URL = ""
request.SetBody(generateSign(values, config.AppSecret))
request.SetBody(generateSign(values, cfg.AppSecret))
return nil
}).
OnAfterResponse(func(client *resty.Client, response *resty.Response) error {
Expand Down Expand Up @@ -272,7 +285,7 @@ func NewClient(config config.Config) *Client {
if v, ok := values["type"]; ok {
endpoint = v.(string)
}
response.Request.SetBody(generateSign(values, config.AppSecret))
response.Request.SetBody(generateSign(values, cfg.AppSecret))
}
}
retry = e == nil
Expand Down
24 changes: 15 additions & 9 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@ import (
"time"
)

type URLPair struct {
Prod string
Test string
}

type Config struct {
Env string `json:"env"` // 环境(dev:开发环境、test:测试环境、prod:生产环境)
Debug bool `json:"debug"` // 是否为调试模式
RegionId int `json:"region_id"` // 区域 ID
AppKey string `json:"app_key"` // App Key
AppSecret string `json:"app_secret"` // App 秘钥
AccessToken string `json:"access_token"` // Access Token
Timeout time.Duration `json:"timeout"` // 超时时间(秒)
VerifySSL bool `json:"verify_ssl"` // 是否验证 SSL
Logger *slog.Logger `json:"-"` // 日志
Env string `json:"env"` // 环境(dev:开发环境、test:测试环境、prod:生产环境)
Debug bool `json:"debug"` // 是否为调试模式
RegionId int `json:"region_id"` // 区域 ID
AppKey string `json:"app_key"` // App Key
AppSecret string `json:"app_secret"` // App 秘钥
AccessToken string `json:"access_token"` // Access Token
Timeout time.Duration `json:"timeout"` // 超时时间(秒)
VerifySSL bool `json:"verify_ssl"` // 是否验证 SSL
Logger *slog.Logger `json:"-"` // 日志
OverwriteUrls map[int]URLPair `json:"overwrite_urls"` // 覆盖 URL
}
27 changes: 17 additions & 10 deletions semi.order.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package temu

import (
"context"
"time"

validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hiscaler/temu-go/entity"
"github.com/hiscaler/temu-go/helpers"
"github.com/hiscaler/temu-go/normal"
"github.com/hiscaler/temu-go/validators/is"
"time"
)

// 订单服务(半托管专属,必须在 US/EU 网关调用)
Expand Down Expand Up @@ -91,26 +92,32 @@ func (s semiOrderService) Query(ctx context.Context, params OrderQueryParams) (i
var result = struct {
normal.Response
Result struct {
TotalItemNum int `json:"totalItemNum"`
PageItems []struct {
ParentOrderMap entity.ParentOrder `json:"parentOrderMap"`
OrderList []entity.ChildOrder `json:"orderList"`
} `json:"pageItems"`
Success bool `json:"success"`
ErrorCode int `json:"errorCode"`
ErrorMsg string `json:"errorMsg"`
ServerTime int64 `json:"serverTime"`
Result struct {
TotalItemNum int `json:"totalItemNum"`
PageItems []struct {
ParentOrderMap entity.ParentOrder `json:"parentOrderMap"`
OrderList []entity.ChildOrder `json:"orderList"`
} `json:"pageItems"`
} `json:"result"`
} `json:"result"`
}{}
resp, err := s.httpClient.R().
SetContext(ctx).
SetBody(params).
SetResult(&result).
Post("bg.goods.list.get")
Post("bg.order.list.get")
if err = recheckError(resp, result.Response, err); err != nil {
return
}

items = make([]entity.Order, len(result.Result.PageItems))
for k, v := range result.Result.PageItems {
items = make([]entity.Order, len(result.Result.Result.PageItems))
for k, v := range result.Result.Result.PageItems {
items[k] = entity.Order{ParentOrder: v.ParentOrderMap, Items: v.OrderList}
}
total, totalPages, isLastPage = parseResponseTotal(params.Page, params.PageSize, result.Result.TotalItemNum)
total, totalPages, isLastPage = parseResponseTotal(params.Page, params.PageSize, result.Result.Result.TotalItemNum)
return
}
17 changes: 17 additions & 0 deletions semi.order_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package temu

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestOrder(t *testing.T) {
params := OrderQueryParams{
ParentOrderStatus: 2,
}
params.Page = 1
params.PageSize = 10
items, total, totalPage, isLatestPage, err := temuClient.Services.SemiManaged.Order.Query(ctx, params)
assert.Equalf(t, nil, err, "Services.SemiManaged.Order.Query(ctx, %#v) err", params)
println(items, total, totalPage, isLatestPage)
}