70 lines
1.3 KiB
Go
70 lines
1.3 KiB
Go
package wechat
|
|
|
|
import (
|
|
"crypto/sha1"
|
|
"encoding/hex"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/imroc/req/v3"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
const BaseURL = "https://api.weixin.qq.com/"
|
|
|
|
var DefaultClient = req.
|
|
NewClient().
|
|
SetBaseURL(BaseURL).
|
|
SetCommonHeader("Content-Type", "application/json")
|
|
|
|
type Client struct {
|
|
client *req.Client
|
|
|
|
appID string
|
|
appSecret string
|
|
token string
|
|
aesKey string
|
|
}
|
|
|
|
func New(options ...Options) *Client {
|
|
we := &Client{
|
|
client: DefaultClient,
|
|
}
|
|
|
|
for _, opt := range options {
|
|
opt(we)
|
|
}
|
|
|
|
return we
|
|
}
|
|
|
|
func (we *Client) VerifyServer(signature, timestamp, nonce string) error {
|
|
params := []string{signature, timestamp, nonce, we.token}
|
|
sort.Strings(params)
|
|
str := strings.Join(params, "")
|
|
hash := sha1.Sum([]byte(str))
|
|
hashStr := hex.EncodeToString(hash[:])
|
|
|
|
if hashStr == signature {
|
|
return errors.New("Signature verification failed")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (we *Client) GetAccessToken() (*AccessTokenResponse, error) {
|
|
params := map[string]string{
|
|
"grant_type": "client_credential",
|
|
"appid": we.appID,
|
|
"secret": we.appSecret,
|
|
}
|
|
|
|
var data AccessTokenResponse
|
|
_, err := we.client.R().SetSuccessResult(&data).SetQueryParams(params).Get("/cgi-bin/token")
|
|
if err != nil {
|
|
return nil, errors.Wrap(err, "call /cgi-bin/token failed")
|
|
}
|
|
|
|
return &data, nil
|
|
}
|