1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package jingdong
import (
"context"
"github.com/gogf/gf/crypto/gmd5"
"github.com/gogf/gf/encoding/gjson"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/util/gconv"
"strings"
"time"
)
type Config struct {
ApiUrl string
BasePathUrl string
GetTokenUrl string
RefreshTokenUrl string
AppKey string
AppSecret string
UserName string
PassWord string
Mobile string
Email string
SubmitState string
CompanyName string
}
type CommonRes struct {
Success bool `json:"success"`
ResultCode string `json:"resultCode"`
ResultMessage string `json:"resultMessage"`
}
type client struct {
*Config
AccessToken string
}
type InvoiceType string
const EI InvoiceType = "4" //电子发票
const VAT InvoiceType = "2" //增值税发票
var server *client
const CacheKey = "jingdong:token"
const pkgName = "jingdong"
func New(config *Config) {
_ = gconv.Scan(config, &server)
return
}
//post 请求
func (s *client) post(ctx context.Context, method string, params g.Map) (str string, err error) {
Start := gtime.TimestampMilli()
Request := g.Client()
Request.SetHeader("Content-Type", "application/x-www-form-urlencoded")
resp, err := Request.Timeout(time.Second*5).Post(method, params)
defer func() {
_ = resp.Close()
paramStr := gjson.New(params).MustToJsonString()
ctx = context.WithValue(ctx, "Method", "POST")
ctx = context.WithValue(ctx, "URI", method)
if err != nil {
g.Log().Ctx(ctx).Cat(pkgName).Cat("error").Infof("参数【%v】错误【%v】响应时间【%v ms】", paramStr, err.Error(), gtime.TimestampMilli()-Start)
} else {
g.Log().Ctx(ctx).Cat(pkgName).Infof("参数【%v】响应【%v】响应时间【%v ms】", paramStr, str, gtime.TimestampMilli()-Start)
}
}()
if err != nil {
return
}
str = resp.ReadAllString()
return
}
//getSign 签名
func (s *client) getSign(timeStamp string) string {
var str = s.AppSecret + timeStamp + s.AppKey + s.UserName
return strings.ToUpper(gmd5.MustEncrypt(str + gmd5.MustEncrypt(s.PassWord) + "access_token" + s.AppSecret))
}
// requestApi 请求
func (s *client) requestApi(ctx context.Context, method string, businessParams g.Map) (str string, err error) {
params, err := s.createPostRequest(ctx, businessParams)
if err != nil {
return
}
urlMethod := s.ApiUrl + method
str, err = s.post(ctx, urlMethod, params)
return
}
func (s *client) createPostRequest(ctx context.Context, businessParams g.Map) (res g.Map, err error) {
err = s.getAccessToken(ctx)
if err != nil {
return
}
res = g.Map{
"token": s.AccessToken,
}
if businessParams != nil {
for k, v := range businessParams {
res[k] = v
}
}
return
}