github.com/fastwego/offiaccount@v1.0.1/offiaccount.go (about) 1 // Copyright 2020 FastWeGo 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 /* 16 微信公众平台开发 SDK 17 18 See: https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html 19 */ 20 package offiaccount 21 22 import ( 23 "log" 24 "os" 25 26 "github.com/faabiosr/cachego" 27 "github.com/faabiosr/cachego/file" 28 ) 29 30 // GetAccessTokenFunc 获取 access_token 方法接口 31 type GetAccessTokenFunc func(ctx *OffiAccount) (accessToken string, err error) 32 33 // NoticeAccessTokenExpireFunc 通知中控 刷新 access_token 34 type NoticeAccessTokenExpireFunc func(ctx *OffiAccount) (err error) 35 36 /* 37 OffiAccount 公众号实例 38 */ 39 type OffiAccount struct { 40 Config Config 41 AccessToken AccessToken 42 Client Client 43 Server Server 44 Logger *log.Logger 45 } 46 47 /* 48 AccessToken 管理器 处理缓存 和 刷新 逻辑 49 */ 50 type AccessToken struct { 51 Cache cachego.Cache 52 GetAccessTokenHandler GetAccessTokenFunc 53 NoticeAccessTokenExpireHandler NoticeAccessTokenExpireFunc 54 } 55 56 /* 57 公众号配置 58 */ 59 type Config struct { 60 Appid string 61 Secret string 62 Token string 63 EncodingAESKey string 64 } 65 66 /* 67 创建公众号实例 68 */ 69 func New(config Config) (offiAccount *OffiAccount) { 70 instance := OffiAccount{ 71 Config: config, 72 AccessToken: AccessToken{ 73 Cache: file.New(os.TempDir()), 74 GetAccessTokenHandler: GetAccessToken, 75 NoticeAccessTokenExpireHandler: NoticeAccessTokenExpire, 76 }, 77 } 78 79 instance.Client = Client{Ctx: &instance} 80 instance.Server = Server{Ctx: &instance} 81 82 instance.Logger = log.New(os.Stdout, "[fastwego/offiaccount] ", log.LstdFlags|log.Llongfile) 83 84 return &instance 85 }