sun_code.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. defer func() {
  22. if err != nil {
  23. fmt.Println("PcCreateAndUploadSunCode Err:" + err.Error())
  24. }
  25. }()
  26. if page == "" {
  27. err = errors.New("page不能为空")
  28. return
  29. }
  30. // scene超过32位会生成失败,md5处理至32位
  31. sceneMD5 := "a=1"
  32. if scene != "" {
  33. sceneMD5 = utils.MD5(scene)
  34. }
  35. // 根据配置选择小程序
  36. conf, e := yb_config.GetConfigByCode(yb_config.KeyUseCopyYb)
  37. if e != nil {
  38. err = errors.New("获取小程序配置失败, Err: " + e.Error())
  39. return
  40. }
  41. picByte, err := wx_app.GetSunCode(page, sceneMD5, conf.ConfigValue)
  42. if err != nil {
  43. return
  44. }
  45. // 生成图片
  46. localPath := "./static/img"
  47. fileName := utils.GetRandStringNoSpecialChar(28) + ".png"
  48. fpath := fmt.Sprint(localPath, "/", fileName)
  49. f, err := os.Create(fpath)
  50. if err != nil {
  51. return
  52. }
  53. if _, err = f.Write(picByte); err != nil {
  54. return
  55. }
  56. defer func() {
  57. f.Close()
  58. os.Remove(fpath)
  59. }()
  60. // 上传OSS
  61. fileDir := "yb/suncode/"
  62. imgUrl, err = UploadAliyunToDir(fileName, fpath, fileDir)
  63. if err != nil {
  64. return
  65. }
  66. // 记录参数
  67. if scene != "" {
  68. newPars := &yb_pc_suncode.YbPcSuncode{
  69. Scene: scene,
  70. SceneMd5: sceneMD5,
  71. CodePage: page,
  72. SuncodeURL: imgUrl,
  73. CreateTime: time.Now(),
  74. }
  75. err = newPars.Create()
  76. }
  77. // 记录参数md5
  78. if scene != "" {
  79. newPars := &yb_suncode_pars.YbSuncodePars{
  80. Scene: scene,
  81. SceneKey: sceneMD5,
  82. CreateTime: time.Now(),
  83. }
  84. err = newPars.Create()
  85. }
  86. // 记录文件
  87. go func() {
  88. re := new(yb_resource.YbResource)
  89. re.ResourceUrl = imgUrl
  90. re.ResourceType = yb_resource.ResourceTypeImg
  91. re.CreateTime = time.Now().Local()
  92. if e := re.Create(); e != nil {
  93. return
  94. }
  95. }()
  96. return
  97. }