一物一码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

86 lines
2.4 KiB

  1. package wx
  2. import (
  3. "applet/app/db"
  4. "applet/app/enum"
  5. "applet/app/md"
  6. "applet/app/utils"
  7. "applet/app/utils/cache"
  8. "encoding/json"
  9. "errors"
  10. )
  11. type OfficialAccount struct {
  12. AccessToken string `json:"access_token"`
  13. Appid string `json:"appid"`
  14. Secret string `json:"secret"`
  15. }
  16. func (officialAccount *OfficialAccount) Set() { // set方法
  17. sysCfgDb := db.SysCfgDb{}
  18. sysCfgDb.Set()
  19. officialAccount.Appid = sysCfgDb.SysCfgGetWithDb(enum.WxOfficialAccountAppId)
  20. officialAccount.Secret = sysCfgDb.SysCfgGetWithDb(enum.WxOfficialAccountAppSecret)
  21. officialAccount.AccessToken = officialAccount.createToken()
  22. }
  23. func (officialAccount *OfficialAccount) createToken() (accessToken string) {
  24. cacheKey := md.WxOfficialAccountCacheKey
  25. accessToken, _ = cache.GetString(cacheKey)
  26. if accessToken != "" {
  27. return
  28. }
  29. url := md.WxOfficialAccountRequestBaseUrl + enum.GetAccessToken
  30. post, err := utils.CurlPost(url, map[string]string{
  31. "appid": officialAccount.Appid,
  32. "secret": officialAccount.Secret,
  33. "grant_type": "client_credential",
  34. }, nil)
  35. utils.FilePutContents("wx_official_account_create_token", "resp"+string(post))
  36. var data md.CreateTokenResp
  37. err = json.Unmarshal(post, &data)
  38. if err != nil {
  39. return
  40. }
  41. if data.AccessToken == "" {
  42. panic(errors.New("获取 access_token 失败"))
  43. }
  44. accessToken = data.AccessToken
  45. cache.SetEx(cacheKey, accessToken, int(data.ExpiresIn-3600))
  46. return
  47. }
  48. func (officialAccount *OfficialAccount) QrcodeCreate(sceneStr string) (qrcodeUrl string, err error) {
  49. url := md.WxOfficialAccountRequestBaseUrl + enum.QrcodeCreate + "?access_token=" + officialAccount.AccessToken
  50. //post, err := utils.CurlPost(url, map[string]interface{}{
  51. // "action_name": "QR_LIMIT_STR_SCENE",
  52. // "action_info": map[string]interface{}{
  53. // "scene": map[string]string{
  54. // "scene_str": sceneStr,
  55. // },
  56. // },
  57. //}, nil)
  58. requestBody, _ := json.Marshal(map[string]interface{}{
  59. "action_name": "QR_STR_SCENE",
  60. "expire_seconds": "6000",
  61. "action_info": map[string]interface{}{
  62. "scene": map[string]string{
  63. "scene_str": sceneStr,
  64. },
  65. },
  66. })
  67. post, err := utils.CurlPost(url, requestBody, nil)
  68. utils.FilePutContents("wx_official_account_qrcode_create", "resp"+string(post))
  69. var data md.CreateQrcodeResp
  70. err = json.Unmarshal(post, &data)
  71. if err != nil {
  72. return
  73. }
  74. qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + data.Ticket
  75. return
  76. }