feat: wecom curd
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"lone-services/pkg/redis"
|
||||
"lone-services/pkg/utils"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
CorpId string
|
||||
CorpSecret string
|
||||
}
|
||||
|
||||
type tokenResponse struct {
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
}
|
||||
|
||||
func NewClient(corpId, corpSecret string) *Client {
|
||||
return &Client{
|
||||
CorpId: corpId,
|
||||
CorpSecret: corpSecret,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) AccessToken(ctx context.Context) (string, error) {
|
||||
secretMd5 := md5.Sum([]byte(c.CorpSecret))
|
||||
key := fmt.Sprintf("wecom:access_token:%s:%s", c.CorpId, hex.EncodeToString(secretMd5[:])[:8])
|
||||
|
||||
if redis.Client != nil {
|
||||
token, err := redis.Client.Get(ctx, key).Result()
|
||||
if err == nil && token != utils.StringEmpty {
|
||||
return token, nil
|
||||
}
|
||||
}
|
||||
|
||||
url := fmt.Sprintf(
|
||||
"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s",
|
||||
c.CorpId,
|
||||
c.CorpSecret,
|
||||
)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return utils.StringEmpty, err
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return utils.StringEmpty, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result tokenResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return utils.StringEmpty, err
|
||||
}
|
||||
if result.ErrCode != utils.NumberZero {
|
||||
return utils.StringEmpty, errors.New(result.ErrMsg)
|
||||
}
|
||||
|
||||
expire := time.Duration(result.ExpiresIn-300) * time.Second
|
||||
if redis.Client != nil {
|
||||
_ = redis.Client.Set(ctx, key, result.AccessToken, expire).Err()
|
||||
}
|
||||
return result.AccessToken, nil
|
||||
}
|
||||
Reference in New Issue
Block a user