-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
87 lines (71 loc) · 1.92 KB
/
client.go
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
package solarman
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"golang.org/x/oauth2"
)
const baseURL = "https://globalapi.solarmanpv.com"
type Client struct {
c *http.Client
appID string
}
func New(appID, appSecret, email, password string) (*Client, error) {
t, err := newOauthToken(
appID, appSecret, email,
fmt.Sprintf("%x", sha256.Sum256([]byte(password))),
)
if err != nil {
return nil, err
}
oauthConfg := oauth2.Config{
ClientID: appID,
ClientSecret: appSecret,
}
c := oauthConfg.Client(context.Background(), t)
return &Client{
c: c,
appID: appID,
}, nil
}
func newOauthToken(appID, appSecret, email, password string) (*oauth2.Token, error) {
data := fmt.Sprintf(`{"appSecret":%q,"email":%q,"password":%q}`, appSecret, email, password)
url := fmt.Sprintf(baseURL+"/account/v1.0/token?appId=%s&language=en&=", appID)
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data))
if err != nil {
return nil, fmt.Errorf("could not auth: %w", err)
}
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("could not auth: %w", err)
}
defer func() { _ = resp.Body.Close() }()
bts, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("could not auth: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("could not auth: %w: %s", err, string(bts))
}
var aresp authResponse
if err := json.Unmarshal(bts, &aresp); err != nil {
return nil, fmt.Errorf("could not auth: %w", err)
}
if !aresp.Success {
return nil, fmt.Errorf("could not auth: solarman error: %s", aresp.Msg)
}
var token oauth2.Token
if err := json.Unmarshal(bts, &token); err != nil {
return nil, fmt.Errorf("could not auth: %w", err)
}
return &token, nil
}
type authResponse struct {
Msg string `json:"msg"`
Success bool `json:"success"`
}