65 lines
1.7 KiB
Go
65 lines
1.7 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"ai_scheduler/internal/config"
|
|
errorcode "ai_scheduler/internal/data/error"
|
|
"ai_scheduler/utils"
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
|
|
oauth2 "github.com/alibabacloud-go/dingtalk/oauth2_1_0"
|
|
"github.com/alibabacloud-go/tea/tea"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type Oauth2Client struct {
|
|
config *config.Config
|
|
cli *oauth2.Client
|
|
redisCli *redis.Client
|
|
}
|
|
|
|
func NewOauth2Client(config *config.Config, rds *utils.Rdb) (*Oauth2Client, error) {
|
|
cfg := &openapi.Config{
|
|
AccessKeyId: tea.String(config.Tools.DingTalkBot.APIKey),
|
|
AccessKeySecret: tea.String(config.Tools.DingTalkBot.APISecret),
|
|
Protocol: tea.String("https"),
|
|
RegionId: tea.String("central"),
|
|
}
|
|
c, err := oauth2.NewClient(cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Oauth2Client{config: config, cli: c, redisCli: rds.Rdb}, nil
|
|
}
|
|
|
|
func (c *Oauth2Client) GetAccessToken() (string, error) {
|
|
// 去cache
|
|
ctx := context.Background()
|
|
accessToken, err := c.redisCli.Get(ctx, "dingtalk:oauth2:access_token").Result()
|
|
if err == nil {
|
|
fmt.Println("get access token from cache:", accessToken)
|
|
return accessToken, nil
|
|
}
|
|
if err != redis.Nil {
|
|
return "", err
|
|
}
|
|
|
|
resp, err := c.cli.GetAccessToken(&oauth2.GetAccessTokenRequest{
|
|
AppKey: tea.String("ding5wwvnf9hxeyjau7t"),
|
|
AppSecret: tea.String("FxXVlTzxrKXvJ8h-9uK0s5TjaBfOJSXumpmrHal-NmQAtku9wOPxcss0Af6WHoAK"),
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if resp.Body == nil {
|
|
return "", errorcode.ParamErrf("empty response body")
|
|
}
|
|
|
|
c.redisCli.Set(ctx, "dingtalk:oauth2:access_token", *resp.Body.AccessToken, time.Duration(*resp.Body.ExpireIn)*time.Second)
|
|
|
|
return *resp.Body.AccessToken, nil
|
|
}
|