mini_wechat_bind_logic.go 2.0 KB
package user

import (
	"context"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/cmd/discuss/interanl/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/contextdata"
	"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 MiniWechatBindLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *MiniWechatBindLogic) MiniWechatBind(req *types.MiniWechatBindRequest) (resp *types.MiniWechatBindResponse, err error) {
	var loginCreator domain.LoginCreator = WxClientLogin{svcCtx: l.svcCtx, ctx: l.ctx}
	openId, err := loginCreator.GetOpenId(domain.WechatLoginRequest{
		Code:          req.WechatAuthCode,
		EncryptedData: req.WechatEncryptedData,
		IV:            req.WechatIV,
	})
	if err != nil {
		return nil, xerr.NewErrMsgErr("授权失败", err)
	}
	var userToken = contextdata.GetUserTokenFromCtx(l.ctx)
	userId := userToken.UserId
	var conn = l.svcCtx.DefaultDBConn()
	//获取用户信息
	userInfo, err := l.svcCtx.UserRepository.FindOne(l.ctx, conn, userId)
	if err != nil {
		return nil, xerr.NewErrMsgErr("获取用户信息失败", err)
	}
	_, err = l.svcCtx.UserWechatRepository.FindOneByPhone(l.ctx, conn, userInfo.Phone)
	if err != nil { // 未存储
		_, err = l.svcCtx.UserWechatRepository.Insert(l.ctx, conn, &domain.UserWechat{
			Phone:  userInfo.Phone,
			OpenId: openId,
		})
		if err != nil {
			return nil, xerr.NewErrMsgErr("授权失败", err)
		}
	}
	if err != nil {
		return nil, xerr.NewErrMsg("保存用户信息失败")
	}
	return &types.MiniWechatBindResponse{
		Bind:   true,
		Phone:  userInfo.Phone,
		OpenId: openId,
	}, nil
}