sun_code.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package services
  2. import (
  3. "errors"
  4. "fmt"
  5. "hongze/hongze_yb/models/tables/yb_config"
  6. "hongze/hongze_yb/models/tables/yb_pc_suncode"
  7. "hongze/hongze_yb/models/tables/yb_resource"
  8. "hongze/hongze_yb/models/tables/yb_suncode_pars"
  9. "hongze/hongze_yb/services/wx_app"
  10. "hongze/hongze_yb/utils"
  11. "os"
  12. "time"
  13. )
  14. // SunCodeReq 获取太阳码请求体
  15. type SunCodeReq struct {
  16. CodePage string `json:"CodePage" description:"太阳码page"`
  17. CodeScene string `json:"CodeScene" description:"太阳码scene"`
  18. }
  19. // PcCreateAndUploadSunCode 生成太阳码并上传OSS
  20. func PcCreateAndUploadSunCode(scene, page string) (imgUrl string, err error) {
  21. if page == "" {
  22. err = errors.New("page不能为空")
  23. return
  24. }
  25. // scene超过32位会生成失败,md5处理至32位
  26. sceneMD5 := "a=1"
  27. if scene != "" {
  28. sceneMD5 = utils.MD5(scene)
  29. }
  30. // 根据配置选择小程序
  31. conf, e := yb_config.GetConfigByCode(yb_config.KeyUseCopyYb)
  32. if e != nil {
  33. err = errors.New("获取小程序配置失败, Err: " + e.Error())
  34. return
  35. }
  36. picByte, err := wx_app.GetSunCode(page, sceneMD5, conf.ConfigValue)
  37. if err != nil {
  38. return
  39. }
  40. // 生成图片
  41. localPath := "./static/img"
  42. fileName := utils.GetRandStringNoSpecialChar(28) + ".png"
  43. fpath := fmt.Sprint(localPath, "/", fileName)
  44. f, err := os.Create(fpath)
  45. if err != nil {
  46. return
  47. }
  48. if _, err = f.Write(picByte); err != nil {
  49. return
  50. }
  51. defer func() {
  52. f.Close()
  53. os.Remove(fpath)
  54. }()
  55. // 上传OSS
  56. fileDir := "yb/suncode/"
  57. imgUrl, err = UploadAliyunToDir(fileName, fpath, fileDir)
  58. if err != nil {
  59. return
  60. }
  61. // 记录参数
  62. if scene != "" {
  63. newPars := &yb_pc_suncode.YbPcSuncode{
  64. Scene: scene,
  65. SceneMd5: sceneMD5,
  66. CodePage: page,
  67. SuncodeURL: imgUrl,
  68. CreateTime: time.Now(),
  69. }
  70. err = newPars.Create()
  71. }
  72. // 记录参数md5
  73. if scene != "" {
  74. newPars := &yb_suncode_pars.YbSuncodePars{
  75. Scene: scene,
  76. SceneKey: sceneMD5,
  77. CreateTime: time.Now(),
  78. }
  79. err = newPars.Create()
  80. }
  81. // 记录文件
  82. go func() {
  83. re := new(yb_resource.YbResource)
  84. re.ResourceUrl = imgUrl
  85. re.ResourceType = yb_resource.ResourceTypeImg
  86. re.CreateTime = time.Now().Local()
  87. if e := re.Create(); e != nil {
  88. return
  89. }
  90. }()
  91. return
  92. }