sun_code.go 1.9 KB

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