微信客服API接口對接-獲取access_token-調用其他接口時都需要獲取-【唯一客服】

調用任何其他接口的時候,都需要先獲取access_token

並且不能頻繁調用,需要有緩存機制

 

package wechat_kf_sdk

import (
    "bytes"
    "encoding/json"
    "encoding/xml"
    "errors"
    "fmt"
    "github.com/patrickmn/go-cache"
    "io"
    "io/ioutil"
    "log"
    "net/http"
    "sync"
    "time"
)

// 定義獲取access_token的響應數據結構體
type AccessTokenResponse struct {
    ErrCode     int    `json:"errcode"`      // 錯誤碼
    ErrMsg      string `json:"errmsg"`       // 錯誤信息
    AccessToken string `json:"access_token"` // access_token
    ExpiresIn   int    `json:"expires_in"`   // 過期時間
}

// 定義微信客服API的封裝結構體
type KefuWework struct {
    corpid         string     // 企業ID
    corpsecret     string     // 企業密鑰
    Token          string     // 令牌
    EncodingAESKey string     // AES加密密鑰
    mutex          sync.Mutex // 互斥鎖,用於保護access_token的獲取
}



var weworkCache = cache.New(5*time.Minute, 10*time.Minute) // 緩存,用於存儲access_token

// 創建微信客服API的封裝結構體實例
func NewKefuWework(corpid string, corpsecret, Token, EncodingAESKey string) *KefuWework {
    return &KefuWework{
        corpid:         corpid,
        corpsecret:     corpsecret,
        Token:          Token,
        EncodingAESKey: EncodingAESKey,
    }
}

// 獲取access_token的函數
func (s *KefuWework) GetAccessToken() (string, error) {
    // 加鎖,避免併發調用獲取access_token接口
    s.mutex.Lock()
    defer s.mutex.Unlock()

    // 判斷access_token是否過期,如果未過期則直接返回
    cacheKey := "wework_access_" + s.corpid
    if accessToken, ok := weworkCache.Get(cacheKey); ok {
        return accessToken.(string), nil
    }
    // 發送GET請求,構建請求URL
    reqURL := fmt.Sprintf("%s?corpid=%s&corpsecret=%s", "https://qyapi.weixin.qq.com/cgi-bin/gettoken", s.corpid, s.corpsecret)
    resp, err := http.Get(reqURL)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    // 解析響應數據到AccessTokenResponse結構體
    var tokenResp AccessTokenResponse
    if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
        return "", err
    }

    // 判斷獲取access_token是否成功
    if tokenResp.ErrCode != 0 {
        return "", fmt.Errorf("GetAccessToken failed: %s", tokenResp.ErrMsg)
    }
    weworkCache.Set(cacheKey, tokenResp.AccessToken, time.Duration(tokenResp.ExpiresIn-3600)*time.Second)
    log.Printf("GetAccessToken kefuWework:%s\n", tokenResp.AccessToken)
    // 返回access_token
    return tokenResp.AccessToken, nil
}

測試用例

func TestGetAccessToken(t *testing.T) {
    corpid := "xx"
    corpsecret := "xxxxxxxxxxx"

    // 創建微信客服API的封裝結構體實例
    kefuWework := NewKefuWework(corpid, corpsecret, "", "")

    // 獲取access_token
    accessToken, err := kefuWework.GetAccessToken()
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(accessToken)
}

可以正確拿到access_token

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章