feat: init

This commit is contained in:
Rogee
2024-11-27 11:55:09 +08:00
parent e0eb7e5e2e
commit e4b9cc5f26
13 changed files with 462 additions and 2 deletions

69
pkg/wechat/wechat.go Normal file
View File

@@ -0,0 +1,69 @@
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
}