mini_qrcode_invite_logic.go 2.5 KB
package common

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/samber/lo"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/gateway/openlib"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/tool"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"

	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/svc"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MiniQrcodeInviteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMiniQrcodeInviteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MiniQrcodeInviteLogic {
	return &MiniQrcodeInviteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MiniQrcodeInviteLogic) MiniQrcodeInvite(req *types.MiniQrCodeRequest) (resp interface{}, err error) {
	var (
		q           = l.svcCtx.MiniProgram.GetQRCode()
		cacheData   = fmt.Sprintf("%s?%s", req.Page, req.Scene)
		cacheKey    = fmt.Sprintf("%s:qrcode:%s", l.svcCtx.Config.Name, tool.Md5ByString(cacheData))
		ok          bool
		qrcodeCache QrcodeCache
	)
	// 从缓存获取
	if ok, err = l.svcCtx.Redis.ExistsCtx(l.ctx, cacheKey); ok && err == nil {
		tmpCacheData, _ := l.svcCtx.Redis.Get(cacheKey)
		if err = json.Unmarshal([]byte(tmpCacheData), &qrcodeCache); err == nil {
			if qrcodeCache.CacheData == cacheData {
				return MiniQrCodeResponse{
					Path: qrcodeCache.QrcodeUrl,
				}, nil
			}
		}
	}

	var data []byte
	data, err = q.GetWXACodeUnlimit(qrcode.QRCoder{
		Page:       req.Page,
		Path:       req.Page,
		Scene:      req.Scene,
		CheckPath:  lo.ToPtr(false),
		EnvVersion: "release",
	})
	if err != nil {
		return nil, xerr.NewErr(err)
	}
	var result *openlib.DataPutFile
	result, err = l.svcCtx.OpenApiService.PutFile(l.ctx, openlib.RequestPutFile{
		File: data,
	})
	if err != nil {
		return nil, xerr.NewErr(err)
	}
	if result == nil || len(*result) == 0 || (*result)[0].Path == "" {
		return nil, xerr.NewErr(fmt.Errorf("上传失败"))
	}

	// 设置缓存
	jsonData, err := json.Marshal(QrcodeCache{
		CacheData: cacheData,
		QrcodeUrl: (*result)[0].Path,
	})
	l.svcCtx.Redis.Set(cacheKey, string(jsonData))

	return MiniQrCodeResponse{
		Path: (*result)[0].Path,
	}, err
}

type MiniQrCodeResponse struct {
	Path string `json:"path"`
}

type QrcodeCache struct {
	CacheData string
	QrcodeUrl string
}