sun_code.go 1.5 KB

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