forked from TruthHun/BookStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwechat.go
More file actions
79 lines (69 loc) · 2.1 KB
/
wechat.go
File metadata and controls
79 lines (69 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package utils
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/astaxie/beego/httplib"
"github.com/astaxie/beego"
)
type WechatToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
var wechatToken = &WechatToken{}
// 获取access_token
func GetAccessToken() (token *WechatToken) {
now := time.Now().Unix()
if now < wechatToken.ExpiresIn-600 { //提前10分钟失效
return wechatToken
}
appId := beego.AppConfig.String("appId")
appSecret := beego.AppConfig.String("appSecret")
api := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%v&secret=%v", appId, appSecret)
req := httplib.Get(api).SetTimeout(10*time.Second, 10*time.Second).SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
resp, err := req.String()
if err != nil {
beego.Error(err.Error())
}
token = &WechatToken{}
json.Unmarshal([]byte(resp), token)
token.ExpiresIn = now + token.ExpiresIn
wechatToken = token
return
}
// 获取书籍页面小程序码
func GetBookWXACode(accessToken string, bookId int) (tmpFile string, err error) {
api := fmt.Sprintf("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken)
data := map[string]interface{}{"page": "pages/intro/intro", "scene": fmt.Sprint(bookId), "width": 280}
req := httplib.Post(api).SetTimeout(10*time.Second, 10*time.Second).SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
var resp *http.Response
var b []byte
b, err = json.Marshal(data)
if err != nil {
return
}
resp, err = req.Body(b).DoRequest()
if err != nil {
return
}
defer resp.Body.Close()
b, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if contentType := strings.ToLower(resp.Header.Get("content-type")); strings.HasPrefix(contentType, "image/") {
tmpFile = fmt.Sprintf("book-id-%v.%v", bookId, strings.TrimPrefix(contentType, "image/"))
err = ioutil.WriteFile(tmpFile, b, os.ModePerm)
} else {
err = errors.New(string(b))
}
return
}