|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package wx
-
- import (
- "applet/app/db"
- "applet/app/enum"
- "applet/app/md"
- "applet/app/utils"
- "applet/app/utils/cache"
- "encoding/json"
- "errors"
- )
-
- type OfficialAccount struct {
- AccessToken string `json:"access_token"`
- Appid string `json:"appid"`
- Secret string `json:"secret"`
- }
-
- func (officialAccount *OfficialAccount) Set() { // set方法
- sysCfgDb := db.SysCfgDb{}
- sysCfgDb.Set()
- officialAccount.Appid = sysCfgDb.SysCfgGetWithDb(enum.WxOfficialAccountAppId)
- officialAccount.Secret = sysCfgDb.SysCfgGetWithDb(enum.WxOfficialAccountAppSecret)
- officialAccount.AccessToken = officialAccount.createToken()
- }
-
- func (officialAccount *OfficialAccount) createToken() (accessToken string) {
- cacheKey := md.WxOfficialAccountCacheKey
- accessToken, _ = cache.GetString(cacheKey)
- if accessToken != "" {
- return
- }
-
- url := md.WxOfficialAccountRequestBaseUrl + enum.GetAccessToken
- post, err := utils.CurlPost(url, map[string]string{
- "appid": officialAccount.Appid,
- "secret": officialAccount.Secret,
- "grant_type": "client_credential",
- }, nil)
-
- utils.FilePutContents("wx_official_account_create_token", "resp"+string(post))
- var data md.CreateTokenResp
- err = json.Unmarshal(post, &data)
- if err != nil {
- return
- }
- if data.AccessToken == "" {
- panic(errors.New("获取 access_token 失败"))
- }
-
- accessToken = data.AccessToken
- cache.SetEx(cacheKey, accessToken, int(data.ExpiresIn-3600))
- return
- }
-
- func (officialAccount *OfficialAccount) QrcodeCreate(sceneStr string) (qrcodeUrl string, err error) {
- url := md.WxOfficialAccountRequestBaseUrl + enum.QrcodeCreate + "?access_token=" + officialAccount.AccessToken
- //post, err := utils.CurlPost(url, map[string]interface{}{
- // "action_name": "QR_LIMIT_STR_SCENE",
- // "action_info": map[string]interface{}{
- // "scene": map[string]string{
- // "scene_str": sceneStr,
- // },
- // },
- //}, nil)
- requestBody, _ := json.Marshal(map[string]interface{}{
- "action_name": "QR_STR_SCENE",
- "expire_seconds": "6000",
- "action_info": map[string]interface{}{
- "scene": map[string]string{
- "scene_str": sceneStr,
- },
- },
- })
- post, err := utils.CurlPost(url, requestBody, nil)
-
- utils.FilePutContents("wx_official_account_qrcode_create", "resp"+string(post))
- var data md.CreateQrcodeResp
- err = json.Unmarshal(post, &data)
- if err != nil {
- return
- }
- qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + data.Ticket
- return
- }
|