first commit

This commit is contained in:
2026-03-18 00:01:48 +08:00
commit a0c623fd81
425 changed files with 42318 additions and 0 deletions

View File

@@ -0,0 +1,224 @@
package service
import (
"context"
"fmt"
"regexp"
"strings"
"in-server/app/main/model"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest"
"github.com/google/uuid"
)
type ApiRegistryService struct {
adminApiModel model.AdminApiModel
}
func NewApiRegistryService(adminApiModel model.AdminApiModel) *ApiRegistryService {
return &ApiRegistryService{
adminApiModel: adminApiModel,
}
}
// RegisterAllApis 自动注册所有API到数据库
func (s *ApiRegistryService) RegisterAllApis(ctx context.Context, routes []rest.Route) error {
logx.Infof("开始注册API共 %d 个路由", len(routes))
registeredCount := 0
skippedCount := 0
for _, route := range routes {
// 跳过不需要权限控制的API
if s.shouldSkipApi(route.Path) {
skippedCount++
continue
}
// 解析API信息
apiInfo := s.parseRouteToApi(route)
// 检查是否已存在
existing, err := s.adminApiModel.FindOneByApiCode(ctx, apiInfo.ApiCode)
if err != nil && !errors.Is(err, model.ErrNotFound) {
logx.Errorf("查询API失败: %v, apiCode: %s", err, apiInfo.ApiCode)
continue
}
// 如果不存在则插入
if existing == nil {
_, err = s.adminApiModel.Insert(ctx, nil, apiInfo)
if err != nil {
logx.Errorf("插入API失败: %v, apiCode: %s", err, apiInfo.ApiCode)
continue
}
registeredCount++
logx.Infof("注册API成功: %s %s", apiInfo.Method, apiInfo.Url)
} else {
// 如果存在但信息有变化,则更新
if s.shouldUpdateApi(existing, apiInfo) {
existing.ApiName = apiInfo.ApiName
existing.Method = apiInfo.Method
existing.Url = apiInfo.Url
existing.Description = apiInfo.Description
_, err = s.adminApiModel.Update(ctx, nil, existing)
if err != nil {
logx.Errorf("更新API失败: %v, apiCode: %s", err, apiInfo.ApiCode)
continue
}
logx.Infof("更新API成功: %s %s", apiInfo.Method, apiInfo.Url)
}
}
}
logx.Infof("API注册完成新增: %d, 跳过: %d", registeredCount, skippedCount)
return nil
}
// shouldSkipApi 判断是否应该跳过此API
func (s *ApiRegistryService) shouldSkipApi(path string) bool {
// 跳过公开API
skipPaths := []string{
"/api/v1/admin/auth/login", // 登录接口
"/api/v1/app/", // 前端应用接口
"/api/v1/agent/", // 代理接口
"/api/v1/user/", // 用户接口
"/api/v1/auth/", // 认证接口
"/api/v1/notification/", // 通知接口
"/api/v1/pay/", // 支付接口
"/api/v1/query/", // 查询接口
"/api/v1/product/", // 产品接口
"/api/v1/authorization/", // 授权接口
"/health", // 健康检查
}
for _, skipPath := range skipPaths {
if strings.HasPrefix(path, skipPath) {
return true
}
}
return false
}
// parseRouteToApi 将路由解析为API信息
func (s *ApiRegistryService) parseRouteToApi(route rest.Route) *model.AdminApi {
// 生成API编码
apiCode := s.generateApiCode(route.Method, route.Path)
// 生成API名称
apiName := s.generateApiName(route.Path)
// 生成描述
description := s.generateDescription(route.Method, route.Path)
return &model.AdminApi{
Id: uuid.NewString(),
ApiName: apiName,
ApiCode: apiCode,
Method: route.Method,
Url: route.Path,
Status: 1, // 默认启用
Description: description,
}
}
// generateApiCode 生成API编码
func (s *ApiRegistryService) generateApiCode(method, path string) string {
// 移除路径参数,如 :id
cleanPath := regexp.MustCompile(`/:[\w]+`).ReplaceAllString(path, "")
// 转换为小写并替换特殊字符
apiCode := strings.ToLower(method) + "_" + strings.ReplaceAll(cleanPath, "/", "_")
apiCode = strings.TrimPrefix(apiCode, "_")
apiCode = strings.TrimSuffix(apiCode, "_")
return apiCode
}
// generateApiName 生成API名称
func (s *ApiRegistryService) generateApiName(path string) string {
// 从路径中提取模块和操作
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) < 3 {
return path
}
// 获取模块名和操作名
module := parts[len(parts)-2]
action := parts[len(parts)-1]
// 转换为中文描述
moduleMap := map[string]string{
"agent": "代理管理",
"auth": "认证管理",
"feature": "功能管理",
"menu": "菜单管理",
"notification": "通知管理",
"order": "订单管理",
"platform_user": "平台用户",
"product": "产品管理",
"query": "查询管理",
"role": "角色管理",
"user": "用户管理",
}
actionMap := map[string]string{
"list": "列表",
"create": "创建",
"update": "更新",
"delete": "删除",
"detail": "详情",
"login": "登录",
"config": "配置",
"example": "示例",
"refund": "退款",
"link": "链接",
"stats": "统计",
"cleanup": "清理",
"record": "记录",
}
moduleName := moduleMap[module]
if moduleName == "" {
moduleName = module
}
actionName := actionMap[action]
if actionName == "" {
actionName = action
}
return fmt.Sprintf("%s-%s", moduleName, actionName)
}
// generateDescription 生成API描述
func (s *ApiRegistryService) generateDescription(method, path string) string {
methodMap := map[string]string{
"GET": "查询",
"POST": "创建",
"PUT": "更新",
"DELETE": "删除",
}
methodDesc := methodMap[method]
if methodDesc == "" {
methodDesc = method
}
apiName := s.generateApiName(path)
return fmt.Sprintf("%s%s", methodDesc, apiName)
}
// shouldUpdateApi 判断是否需要更新API
func (s *ApiRegistryService) shouldUpdateApi(existing, new *model.AdminApi) bool {
return existing.ApiName != new.ApiName ||
existing.Method != new.Method ||
existing.Url != new.Url ||
existing.Description != new.Description
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,123 @@
// asynq_service.go
package service
import (
"encoding/json"
"time"
"in-server/app/main/api/internal/config"
"in-server/app/main/api/internal/types"
"github.com/hibiken/asynq"
"github.com/zeromicro/go-zero/core/logx"
)
type AsynqService struct {
client *asynq.Client
config config.Config
}
// NewAsynqService 创建并初始化 Asynq 客户端
func NewAsynqService(c config.Config) *AsynqService {
client := asynq.NewClient(asynq.RedisClientOpt{
Addr: c.CacheRedis[0].Host,
Password: c.CacheRedis[0].Pass,
})
return &AsynqService{client: client, config: c}
}
// Close 关闭 Asynq 客户端
func (s *AsynqService) Close() error {
return s.client.Close()
}
func (s *AsynqService) SendQueryTask(orderID string) error {
// 准备任务的 payload
payload := types.MsgPaySuccessQueryPayload{
OrderID: orderID,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
logx.Errorf("发送异步任务失败 (无法编码 payload): %v, 订单号: %s", err, orderID)
return err // 直接返回错误,避免继续执行
}
options := []asynq.Option{
asynq.MaxRetry(5), // 设置最大重试次数
}
// 创建任务
task := asynq.NewTask(types.MsgPaySuccessQuery, payloadBytes, options...)
// 将任务加入队列并获取任务信息
info, err := s.client.Enqueue(task)
if err != nil {
logx.Errorf("发送异步任务失败 (加入队列失败): %+v, 订单号: %s", err, orderID)
return err
}
// 记录成功日志,带上任务 ID 和队列信息
logx.Infof("发送异步任务成功任务ID: %s, 队列: %s, 订单号: %s", info.ID, info.Queue, orderID)
return nil
}
// SendAgentProcessTask 发送代理处理任务
func (s *AsynqService) SendAgentProcessTask(orderID string) error {
// 准备任务的 payload
payload := types.MsgAgentProcessPayload{
OrderID: orderID,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
logx.Errorf("发送代理处理任务失败 (无法编码 payload): %v, 订单号: %s", err, orderID)
return err
}
options := []asynq.Option{
asynq.MaxRetry(5), // 设置最大重试次数
}
// 创建任务
task := asynq.NewTask(types.MsgAgentProcess, payloadBytes, options...)
// 将任务加入队列并获取任务信息
info, err := s.client.Enqueue(task)
if err != nil {
logx.Errorf("发送代理处理任务失败 (加入队列失败): %+v, 订单号: %s", err, orderID)
return err
}
// 记录成功日志,带上任务 ID 和队列信息
logx.Infof("发送代理处理任务成功任务ID: %s, 队列: %s, 订单号: %s", info.ID, info.Queue, orderID)
return nil
}
// SendUnfreezeTask 发送解冻任务(延迟执行)
func (s *AsynqService) SendUnfreezeTask(freezeTaskId string, processAt time.Time) error {
// 准备任务的 payload
payload := types.MsgUnfreezeCommissionPayload{
FreezeTaskId: freezeTaskId,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
logx.Errorf("发送解冻任务失败 (无法编码 payload): %v, 冻结任务ID: %s", err, freezeTaskId)
return err
}
options := []asynq.Option{
asynq.MaxRetry(5), // 设置最大重试次数
asynq.ProcessAt(processAt), // 延迟到指定时间执行
asynq.Queue("critical"), // 使用关键队列
}
// 创建任务
task := asynq.NewTask(types.MsgUnfreezeCommission, payloadBytes, options...)
// 将任务加入队列并获取任务信息
info, err := s.client.Enqueue(task)
if err != nil {
logx.Errorf("发送解冻任务失败 (加入队列失败): %+v, 冻结任务ID: %s", err, freezeTaskId)
return err
}
// 记录成功日志,带上任务 ID 和队列信息
logx.Infof("发送解冻任务成功任务ID: %s, 队列: %s, 冻结任务ID: %s, 执行时间: %v", info.ID, info.Queue, freezeTaskId, processAt)
return nil
}

View File

@@ -0,0 +1,225 @@
package service
import (
"bytes"
"context"
"database/sql"
"fmt"
"in-server/app/main/api/internal/config"
"in-server/app/main/model"
"os"
"path/filepath"
"time"
"github.com/google/uuid"
"github.com/jung-kurt/gofpdf"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type AuthorizationService struct {
config config.Config
authDocModel model.AuthorizationDocumentModel
fileStoragePath string
fileBaseURL string
}
// NewAuthorizationService 创建授权书服务实例
func NewAuthorizationService(c config.Config, authDocModel model.AuthorizationDocumentModel) *AuthorizationService {
return &AuthorizationService{
config: c,
authDocModel: authDocModel,
fileStoragePath: "data/authorization_docs", // 使用相对路径,兼容开发环境
fileBaseURL: c.Authorization.FileBaseURL, // 从配置文件读取
}
}
// GenerateAuthorizationDocument 生成授权书PDF
func (s *AuthorizationService) GenerateAuthorizationDocument(
ctx context.Context,
userID string,
orderID string,
queryID string,
userInfo map[string]interface{},
) (*model.AuthorizationDocument, error) {
// 1. 生成PDF内容
pdfBytes, err := s.generatePDFContent(userInfo)
if err != nil {
return nil, errors.Wrapf(err, "生成PDF内容失败")
}
// 2. 创建文件存储目录
year := time.Now().Format("2006")
month := time.Now().Format("01")
dirPath := filepath.Join(s.fileStoragePath, year, month)
if err := os.MkdirAll(dirPath, 0755); err != nil {
return nil, errors.Wrapf(err, "创建存储目录失败: %s", dirPath)
}
// 3. 生成文件名和路径
fileName := fmt.Sprintf("auth_%s_%s_%s.pdf", userID, orderID, time.Now().Format("20060102_150405"))
filePath := filepath.Join(dirPath, fileName)
// 只存储相对路径,不包含域名
relativePath := fmt.Sprintf("%s/%s/%s", year, month, fileName)
// 4. 保存PDF文件
if err := os.WriteFile(filePath, pdfBytes, 0644); err != nil {
return nil, errors.Wrapf(err, "保存PDF文件失败: %s", filePath)
}
// 5. 保存到数据库
authDoc := &model.AuthorizationDocument{
Id: uuid.NewString(),
UserId: userID,
OrderId: orderID,
QueryId: queryID,
FileName: fileName,
FilePath: filePath,
FileUrl: relativePath, // 只存储相对路径
FileSize: int64(len(pdfBytes)),
FileType: "pdf",
Status: "active",
ExpireTime: sql.NullTime{Valid: false}, // 永久保留,不设置过期时间
}
_, err = s.authDocModel.Insert(ctx, nil, authDoc)
if err != nil {
// 如果数据库保存失败,删除已创建的文件
os.Remove(filePath)
return nil, errors.Wrapf(err, "保存授权书记录失败")
}
logx.Infof("授权书生成成功: userID=%s, orderID=%s, filePath=%s", userID, orderID, filePath)
return authDoc, nil
}
// GetFullFileURL 获取完整的文件访问URL
func (s *AuthorizationService) GetFullFileURL(relativePath string) string {
if relativePath == "" {
return ""
}
return fmt.Sprintf("%s/%s", s.fileBaseURL, relativePath)
}
// generatePDFContent 生成PDF内容
func (s *AuthorizationService) generatePDFContent(userInfo map[string]interface{}) ([]byte, error) {
// 创建PDF文档
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
// 添加中文字体支持 - 参考imageService的路径处理方式
fontPaths := []string{
"static/SIMHEI.TTF", // 相对于工作目录的路径与imageService一致
"/app/static/SIMHEI.TTF", // Docker容器内的字体文件
"app/main/api/static/SIMHEI.TTF", // 开发环境备用路径
}
// 尝试添加字体
fontAdded := false
for _, fontPath := range fontPaths {
if _, err := os.Stat(fontPath); err == nil {
pdf.AddUTF8Font("ChineseFont", "", fontPath)
fontAdded = true
logx.Infof("成功加载字体: %s", fontPath)
break
} else {
logx.Debugf("字体文件不存在: %s, 错误: %v", fontPath, err)
}
}
// 如果没有找到字体文件,使用默认字体,并记录警告
if !fontAdded {
pdf.SetFont("Arial", "", 12)
logx.Errorf("未找到中文字体文件使用默认Arial字体可能无法正确显示中文")
} else {
// 设置默认字体
pdf.SetFont("ChineseFont", "", 12)
}
// 获取用户信息
name := getUserInfoString(userInfo, "name")
idCard := getUserInfoString(userInfo, "id_card")
// 生成当前日期
currentDate := time.Now().Format("2006年1月2日")
// 设置标题样式 - 大字体、居中
if fontAdded {
pdf.SetFont("ChineseFont", "", 20) // 使用20号字体
} else {
pdf.SetFont("Arial", "", 20)
}
pdf.CellFormat(0, 15, "授权书", "", 1, "C", false, 0, "")
// 添加空行
pdf.Ln(5)
// 设置正文样式 - 正常字体
if fontAdded {
pdf.SetFont("ChineseFont", "", 12)
} else {
pdf.SetFont("Arial", "", 12)
}
// 构建授权书内容(去掉标题部分)
content := fmt.Sprintf(`郴州市北湖区融享信息技术服务部:
本人%s拟向贵司申请大数据分析报告查询业务贵司需要了解本人相关状况用于查询大数据分析报告因此本人同意向贵司提供本人的姓名和手机号等个人信息并同意贵司向第三方包括但不限于西部数据交易有限公司传送上述信息。第三方将使用上述信息核实信息真实情况查询信用记录并生成报告。
授权内容如下:
贵司向依法成立的第三方服务商(包括但不限于西部数据交易有限公司)根据本人提交的信息进行核实,并有权通过前述第三方服务机构查询、使用本人的身份信息、设备信息、运营商信息等,查询本人信息(包括但不限于学历、婚姻、资产状况及对信息主体产生负面影响的不良信息),出具相关报告。
依法成立的第三方服务商查询或核实、搜集、保存、处理、共享、使用(含合法业务应用)本人相关数据,且不再另行告知本人,但法律、法规、监管政策禁止的除外。
本人授权有效期为自授权之日起 1个月。本授权为不可撤销授权但法律法规另有规定的除外。
用户声明与承诺:
本人在授权签署前,已通过实名认证及动态验证码验证(或其他身份验证手段),确认本授权行为为本人真实意思表示,平台已履行身份验证义务。
本人在此声明已充分理解上述授权条款含义,知晓并自愿承担因授权数据使用可能带来的后果,包括但不限于影响个人信用评分、生活行为等。本人确认授权范围内的相关信息由本人提供并真实有效。
若用户冒名签署或提供虚假信息,由用户自行承担全部法律责任,平台不承担任何后果。
特别提示:
本产品所有数据均来自第三方。可能部分数据未公开、数据更新延迟或信息受到限制,贵司不对数据的准确性、真实性、完整性做任何承诺。用户需根据实际情况,结合报告内容自行判断与决策。
本产品仅供用户本人查询或被授权查询。除非用户取得合法授权,用户不得利用本产品查询他人信息。用户因未获得合法授权而擅自查询他人信息所产生的任何后果,由用户自行承担责任。
本授权书涉及对本人敏感信息(包括但不限于婚姻状态、资产状况等)的查询与使用。本人已充分知晓相关信息的敏感性,并明确同意贵司及其合作方依据授权范围使用相关信息。
平台声明:本授权书涉及的信息核实及查询结果由第三方服务商提供,平台不对数据的准确性、完整性、实时性承担责任;用户根据报告所作决策的风险由用户自行承担,平台对此不承担法律责任。
本授权书中涉及的数据查询和报告生成由依法成立的第三方服务商提供。若因第三方行为导致数据错误或损失,用户应向第三方主张权利,平台不承担相关责任。
附加说明:
本人在授权的相关数据将依据法律法规及贵司内部数据管理规范妥善存储,存储期限为法律要求的最短必要时间。超过存储期限或在数据使用目的达成后,贵司将对相关数据进行销毁或匿名化处理。
本人有权随时撤回本授权书中的授权,但撤回前的授权行为及其法律后果仍具有法律效力。若需撤回授权,本人可通过贵司官方渠道提交书面申请,贵司将在收到申请后依法停止对本人数据的使用。
你通过"财神"自愿支付相应费用用于购买郴州市北湖区融享信息技术服务部的大数据报告产品。如若对产品内容存在异议可通过邮箱admin@iieeii.com或APP"联系客服"按钮进行反馈贵司将在收到异议之日起20日内进行核查和处理并将结果答复。
你向郴州市北湖区融享信息技术服务部的支付方式为:郴州市北湖区融享信息技术服务部及其经官方授权的相关企业的支付宝账户。
争议解决机制:
若因本授权书引发争议,双方应友好协商解决;协商不成的,双方同意将争议提交至授权书签署地(四川省)有管辖权的人民法院解决。
签署方式的法律效力声明:
本授权书通过用户在线勾选、电子签名或其他网络签署方式完成,与手写签名具有同等法律效力。平台已通过技术手段保存签署过程的完整记录,作为用户真实意思表示的证据。
本授权书于 %s 生效。
授权人:%s
身份证号:%s
签署时间:%s`, name, currentDate, name, idCard, currentDate)
// 将内容写入PDF
pdf.MultiCell(0, 6, content, "", "", false)
// 生成PDF字节数组
var buf bytes.Buffer
err := pdf.Output(&buf)
if err != nil {
return nil, errors.Wrapf(err, "生成PDF字节数组失败")
}
return buf.Bytes(), nil
}
// getUserInfoString 安全获取用户信息字符串
func getUserInfoString(userInfo map[string]interface{}, key string) string {
if value, exists := userInfo[key]; exists {
if str, ok := value.(string); ok {
return str
}
}
return ""
}

View File

@@ -0,0 +1,47 @@
package service
import (
"context"
"in-server/app/main/model"
"errors"
)
type DictService struct {
adminDictTypeModel model.AdminDictTypeModel
adminDictDataModel model.AdminDictDataModel
}
func NewDictService(adminDictTypeModel model.AdminDictTypeModel, adminDictDataModel model.AdminDictDataModel) *DictService {
return &DictService{adminDictTypeModel: adminDictTypeModel, adminDictDataModel: adminDictDataModel}
}
func (s *DictService) GetDictLabel(ctx context.Context, dictType string, dictValue int64) (string, error) {
dictTypeModel, err := s.adminDictTypeModel.FindOneByDictType(ctx, dictType)
if err != nil {
return "", err
}
if dictTypeModel.Status != 1 {
return "", errors.New("字典类型未启用")
}
dictData, err := s.adminDictDataModel.FindOneByDictTypeDictValue(ctx, dictTypeModel.DictType, dictValue)
if err != nil {
return "", err
}
if dictData.Status != 1 {
return "", errors.New("字典数据未启用")
}
return dictData.DictLabel, nil
}
func (s *DictService) GetDictValue(ctx context.Context, dictType string, dictLabel string) (int64, error) {
dictTypeModel, err := s.adminDictTypeModel.FindOneByDictType(ctx, dictType)
if err != nil {
return 0, err
}
if dictTypeModel.Status != 1 {
return 0, errors.New("字典类型未启用")
}
dictData, err := s.adminDictDataModel.FindOneByDictTypeDictLabel(ctx, dictTypeModel.DictType, dictLabel)
if err != nil {
return 0, err
}
return dictData.DictValue, nil
}

View File

@@ -0,0 +1,173 @@
package service
import (
"bytes"
"fmt"
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"github.com/fogleman/gg"
"github.com/skip2/go-qrcode"
"github.com/zeromicro/go-zero/core/logx"
)
type ImageService struct {
baseImagePath string
}
func NewImageService() *ImageService {
return &ImageService{
baseImagePath: "static/images", // 原图存放目录
}
}
// ProcessImageWithQRCode 处理图片,在中间添加二维码
func (s *ImageService) ProcessImageWithQRCode(qrcodeType, qrcodeUrl string) ([]byte, string, error) {
// 1. 根据qrcodeType确定使用哪张背景图
var backgroundImageName string
switch qrcodeType {
case "promote":
backgroundImageName = "tg_qrcode_1.png"
case "invitation":
backgroundImageName = "yq_qrcode_1.png"
default:
backgroundImageName = "tg_qrcode_1.png" // 默认使用第一张图片
}
// 2. 读取原图
originalImagePath := filepath.Join(s.baseImagePath, backgroundImageName)
originalImage, err := s.loadImage(originalImagePath)
if err != nil {
logx.Errorf("加载原图失败: %v, 图片路径: %s", err, originalImagePath)
return nil, "", fmt.Errorf("加载原图失败: %v", err)
}
// 3. 获取原图尺寸
bounds := originalImage.Bounds()
imgWidth := bounds.Dx()
imgHeight := bounds.Dy()
// 4. 创建绘图上下文
dc := gg.NewContext(imgWidth, imgHeight)
// 5. 绘制原图作为背景
dc.DrawImageAnchored(originalImage, imgWidth/2, imgHeight/2, 0.5, 0.5)
// 6. 生成二维码(去掉白边)
qrCode, err := qrcode.New(qrcodeUrl, qrcode.Medium)
if err != nil {
logx.Errorf("生成二维码失败: %v, 二维码内容: %s", err, qrcodeUrl)
return nil, "", fmt.Errorf("生成二维码失败: %v", err)
}
// 禁用二维码边框,去掉白边
qrCode.DisableBorder = true
// 7. 根据二维码类型设置不同的尺寸和位置
var qrSize int
var qrX, qrY int
switch qrcodeType {
case "promote":
// promote类型精确设置二维码尺寸
qrSize = 280 // 固定尺寸280px
// 左下角位置:距左边和底边留一些边距
qrX = 192 // 距左边180px
qrY = imgHeight - qrSize - 190 // 距底边100px
case "invitation":
// invitation类型精确设置二维码尺寸
qrSize = 360 // 固定尺寸320px
// 中间偏上位置
qrX = (imgWidth - qrSize) / 2 // 水平居中
qrY = 555 // 垂直位置200px
default:
// 默认promote样式
qrSize = 280 // 固定尺寸280px
qrX = 200 // 距左边180px
qrY = imgHeight - qrSize - 200 // 距底边100px
}
// 8. 生成指定尺寸的二维码图片
qrCodeImage := qrCode.Image(qrSize)
// 9. 直接绘制二维码(不添加背景)
dc.DrawImageAnchored(qrCodeImage, qrX+qrSize/2, qrY+qrSize/2, 0.5, 0.5)
// 11. 输出为字节数组
var buf bytes.Buffer
err = png.Encode(&buf, dc.Image())
if err != nil {
logx.Errorf("编码图片失败: %v", err)
return nil, "", fmt.Errorf("编码图片失败: %v", err)
}
logx.Infof("成功生成带二维码的图片,类型: %s, 二维码内容: %s, 图片尺寸: %dx%d, 二维码尺寸: %dx%d, 位置: (%d,%d)",
qrcodeType, qrcodeUrl, imgWidth, imgHeight, qrSize, qrSize, qrX, qrY)
return buf.Bytes(), "image/png", nil
}
// loadImage 加载图片文件
func (s *ImageService) loadImage(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
// 尝试解码PNG
img, err := png.Decode(file)
if err != nil {
// 如果PNG解码失败重新打开文件尝试JPEG
file.Close()
file, err = os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, err = jpeg.Decode(file)
if err != nil {
// 如果还是失败,使用通用解码器
file.Close()
file, err = os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err = image.Decode(file)
if err != nil {
return nil, err
}
}
}
return img, nil
}
// GetSupportedImageTypes 获取支持的图片类型列表
func (s *ImageService) GetSupportedImageTypes() []string {
return []string{"promote", "invitation"}
}
// CheckImageExists 检查指定类型的背景图是否存在
func (s *ImageService) CheckImageExists(qrcodeType string) bool {
var backgroundImageName string
switch qrcodeType {
case "promote":
backgroundImageName = "tg_qrcode_1.png"
case "invitation":
backgroundImageName = "yq_qrcode_1.png"
default:
backgroundImageName = "tg_qrcode_1.png"
}
imagePath := filepath.Join(s.baseImagePath, backgroundImageName)
_, err := os.Stat(imagePath)
return err == nil
}

View File

@@ -0,0 +1,144 @@
package service
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/zeromicro/go-zero/core/logx"
)
// ReportPDFService 负责根据订单信息渲染前端报告页面并生成 PDF。
type ReportPDFService struct {
baseReportURL string
outputDir string
}
func NewReportPDFService(baseReportURL, outputDir string) *ReportPDFService {
return &ReportPDFService{
baseReportURL: baseReportURL,
outputDir: outputDir,
}
}
// GenerateReportPDF 根据 orderId / orderNo 生成报告 PDF。
// orderId 与 orderNo 至少需要一个非空,否则返回错误。
func (s *ReportPDFService) GenerateReportPDF(ctx context.Context, orderId, orderNo string) ([]byte, error) {
if orderId == "" && orderNo == "" {
return nil, fmt.Errorf("orderId 和 orderNo 不能同时为空")
}
reportURL := s.buildReportURL(orderId, orderNo)
logx.WithContext(ctx).Infof("GenerateReportPDF, reportURL=%s", reportURL)
// 为单次渲染创建 chromedp 上下文,并设置超时。
// 如需更高性能,可在外层维护一个共享的 chromedp 池。
ctxt, cancel := chromedp.NewContext(ctx)
defer cancel()
ctxt, timeoutCancel := context.WithTimeout(ctxt, 40*time.Second)
defer timeoutCancel()
var pdfBuf []byte
err := chromedp.Run(ctxt,
chromedp.Navigate(reportURL),
// 等待报告根节点渲染完成
chromedp.WaitVisible(`.pc-report-page`, chromedp.ByQuery),
// 再等待一小段时间以便异步数据加载
chromedp.Sleep(500*time.Millisecond),
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, pdfErr := page.PrintToPDF().
WithPrintBackground(true).
WithMarginTop(0).
WithMarginBottom(0).
WithMarginLeft(0).
WithMarginRight(0).
Do(ctx)
if pdfErr != nil {
return pdfErr
}
pdfBuf = buf
return nil
}),
)
if err != nil {
return nil, fmt.Errorf("使用 chromedp 生成报告 PDF 失败: %w", err)
}
return pdfBuf, nil
}
// GetOrGenerateReportPDF 先从本地缓存读取,若不存在则生成并写入磁盘。
func (s *ReportPDFService) GetOrGenerateReportPDF(ctx context.Context, orderId, orderNo string) ([]byte, error) {
if orderId == "" && orderNo == "" {
return nil, fmt.Errorf("orderId 和 orderNo 不能同时为空")
}
// 优先使用订单ID作为文件名否则退回订单号
fileKey := orderId
if fileKey == "" {
fileKey = orderNo
}
fileName := fmt.Sprintf("%s.pdf", fileKey)
if s.outputDir == "" {
// 未配置缓存目录,则每次都生成但不落盘
return s.GenerateReportPDF(ctx, orderId, orderNo)
}
fullPath := filepath.Join(s.outputDir, fileName)
// 如果文件已存在且非空,直接读取返回
if info, err := os.Stat(fullPath); err == nil && info.Size() > 0 {
data, readErr := os.ReadFile(fullPath)
if readErr == nil {
logx.WithContext(ctx).Infof("命中报告 PDF 缓存: %s", fullPath)
return data, nil
}
}
// 缓存未命中或读取失败,重新生成
pdfBytes, genErr := s.GenerateReportPDF(ctx, orderId, orderNo)
if genErr != nil {
return nil, genErr
}
// 尝试写入缓存(失败不影响主流程)
if mkErr := os.MkdirAll(s.outputDir, 0o755); mkErr == nil {
if writeErr := os.WriteFile(fullPath, pdfBytes, 0o644); writeErr != nil {
logx.WithContext(ctx).Errorf("写入报告 PDF 缓存失败: path=%s, err=%v", fullPath, writeErr)
} else {
logx.WithContext(ctx).Infof("生成并缓存报告 PDF 成功: %s", fullPath)
}
} else {
logx.WithContext(ctx).Errorf("创建报告 PDF 缓存目录失败: dir=%s, err=%v", s.outputDir, mkErr)
}
return pdfBytes, nil
}
func (s *ReportPDFService) buildReportURL(orderId, orderNo string) string {
// /in-webview 对外的 PC 报告路由,需与前端路由保持一致,例如 /report-pc
// 这里假设为: {baseReportURL}/report-pc?order_id=xxx&out_trade_no=xxx
// baseReportURL 通过配置注入,例如 https://your-domain/in-webview
query := ""
if orderId != "" {
query += "order_id=" + orderId
}
if orderNo != "" {
if query != "" {
query += "&"
}
query += "out_trade_no=" + orderNo
}
// 标记为 PDF 渲染模式,前端可据此调用免登录接口
if query != "" {
query += "&"
}
query += "pdf=1"
return fmt.Sprintf("%s/report-pc?%s", s.baseReportURL, query)
}

View File

@@ -0,0 +1,416 @@
package tianyuanapi
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
// API调用相关错误类型
var (
ErrQueryEmpty = errors.New("查询为空")
ErrSystem = errors.New("接口异常")
ErrDecryptFail = errors.New("解密失败")
ErrRequestParam = errors.New("请求参数结构不正确")
ErrInvalidParam = errors.New("参数校验不正确")
ErrInvalidIP = errors.New("未经授权的IP")
ErrMissingAccessId = errors.New("缺少Access-Id")
ErrInvalidAccessId = errors.New("未经授权的AccessId")
ErrFrozenAccount = errors.New("账户已冻结")
ErrArrears = errors.New("账户余额不足,无法请求")
ErrProductNotFound = errors.New("产品不存在")
ErrProductDisabled = errors.New("产品已停用")
ErrNotSubscribed = errors.New("未订阅此产品")
ErrBusiness = errors.New("业务失败")
)
// 错误码映射 - 严格按照用户要求
var ErrorCodeMap = map[error]int{
ErrQueryEmpty: 1000,
ErrSystem: 1001,
ErrDecryptFail: 1002,
ErrRequestParam: 1003,
ErrInvalidParam: 1003,
ErrInvalidIP: 1004,
ErrMissingAccessId: 1005,
ErrInvalidAccessId: 1006,
ErrFrozenAccount: 1007,
ErrArrears: 1007,
ErrProductNotFound: 1008,
ErrProductDisabled: 1008,
ErrNotSubscribed: 1008,
ErrBusiness: 2001,
}
// ApiCallOptions API调用选项
type ApiCallOptions struct {
Json bool `json:"json,omitempty"` // 是否返回JSON格式
}
// Client 天元API客户端
type Client struct {
accessID string
key string
baseURL string
timeout time.Duration
client *http.Client
}
// Config 客户端配置
type Config struct {
AccessID string // 访问ID
Key string // AES密钥16进制
BaseURL string // API基础URL
Timeout time.Duration // 超时时间
}
// Request 请求参数
type Request struct {
InterfaceName string `json:"interfaceName"` // 接口名称
Params map[string]interface{} `json:"params"` // 请求参数
Timeout int `json:"timeout"` // 超时时间(毫秒)
Options *ApiCallOptions `json:"options"` // 调用选项
}
// ApiResponse HTTP API响应
type ApiResponse struct {
Code int `json:"code"`
Message string `json:"message"`
TransactionID string `json:"transaction_id"` // 流水号
Data string `json:"data"` // 加密的数据
}
// Response Call方法的响应
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Success bool `json:"success"`
TransactionID string `json:"transaction_id"` // 流水号
Data interface{} `json:"data"` // 解密后的数据
Timeout int64 `json:"timeout"` // 请求耗时(毫秒)
Error string `json:"error,omitempty"`
}
// NewClient 创建新的客户端实例
func NewClient(config Config) (*Client, error) {
// 参数校验
if config.AccessID == "" {
return nil, fmt.Errorf("accessID不能为空")
}
if config.Key == "" {
return nil, fmt.Errorf("key不能为空")
}
if config.BaseURL == "" {
config.BaseURL = "http://127.0.0.1:8080"
}
if config.Timeout == 0 {
config.Timeout = 60 * time.Second
}
// 验证密钥格式
if _, err := hex.DecodeString(config.Key); err != nil {
return nil, fmt.Errorf("无效的密钥格式必须是16进制字符串: %v", err)
}
return &Client{
accessID: config.AccessID,
key: config.Key,
baseURL: config.BaseURL,
timeout: config.Timeout,
client: &http.Client{
Timeout: config.Timeout,
},
}, nil
}
// Call 调用API接口
func (c *Client) Call(req Request) (*Response, error) {
startTime := time.Now()
// 参数校验
if err := c.validateRequest(req); err != nil {
return nil, fmt.Errorf("请求参数校验失败: %v", err)
}
// 加密参数
jsonData, err := json.Marshal(req.Params)
if err != nil {
return nil, fmt.Errorf("参数序列化失败: %v", err)
}
encryptedData, err := c.encrypt(string(jsonData))
if err != nil {
return nil, fmt.Errorf("数据加密失败: %v", err)
}
// 构建请求体
requestBody := map[string]interface{}{
"data": encryptedData,
}
// 添加选项
if req.Options != nil {
requestBody["options"] = req.Options
} else {
// 默认选项
defaultOptions := &ApiCallOptions{
Json: true,
}
requestBody["options"] = defaultOptions
}
requestBodyBytes, err := json.Marshal(requestBody)
if err != nil {
return nil, fmt.Errorf("请求体序列化失败: %v", err)
}
// 创建HTTP请求
url := fmt.Sprintf("%s/api/v1/%s", c.baseURL, req.InterfaceName)
httpReq, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBodyBytes))
if err != nil {
return nil, fmt.Errorf("创建HTTP请求失败: %v", err)
}
// 设置请求头
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Access-Id", c.accessID)
httpReq.Header.Set("User-Agent", "TianyuanAPI-Go-SDK/1.0.0")
// 发送请求
resp, err := c.client.Do(httpReq)
if err != nil {
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
return &Response{
Success: false,
Message: "请求失败",
Error: err.Error(),
Timeout: requestTime,
}, nil
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
return &Response{
Success: false,
Message: "读取响应失败",
Error: err.Error(),
Timeout: requestTime,
}, nil
}
// 解析HTTP API响应
var apiResp ApiResponse
if err := json.Unmarshal(body, &apiResp); err != nil {
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
return &Response{
Success: false,
Message: "响应解析失败",
Error: err.Error(),
Timeout: requestTime,
}, nil
}
// 计算请求耗时
endTime := time.Now()
requestTime := endTime.Sub(startTime).Milliseconds()
// 构建Call方法的响应
response := &Response{
Code: apiResp.Code,
Message: apiResp.Message,
Success: apiResp.Code == 0,
TransactionID: apiResp.TransactionID,
Timeout: requestTime,
}
// 如果有加密数据,尝试解密
if apiResp.Data != "" {
decryptedData, err := c.decrypt(apiResp.Data)
if err == nil {
var decryptedMap interface{}
if json.Unmarshal([]byte(decryptedData), &decryptedMap) == nil {
response.Data = decryptedMap
}
}
}
// 根据响应码返回对应的错误
if apiResp.Code != 0 {
err := GetErrorByCode(apiResp.Code)
return nil, err
}
return response, nil
}
// CallInterface 简化接口调用方法
func (c *Client) CallInterface(interfaceName string, params map[string]interface{}, options ...*ApiCallOptions) (*Response, error) {
var opts *ApiCallOptions
if len(options) > 0 {
opts = options[0]
}
req := Request{
InterfaceName: interfaceName,
Params: params,
Timeout: 60000,
Options: opts,
}
return c.Call(req)
}
// validateRequest 校验请求参数
func (c *Client) validateRequest(req Request) error {
if req.InterfaceName == "" {
return fmt.Errorf("interfaceName不能为空")
}
if req.Params == nil {
return fmt.Errorf("params不能为空")
}
return nil
}
// encrypt AES CBC加密
func (c *Client) encrypt(plainText string) (string, error) {
keyBytes, err := hex.DecodeString(c.key)
if err != nil {
return "", err
}
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
// 生成随机IV
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
// 填充数据
paddedData := c.pkcs7Pad([]byte(plainText), aes.BlockSize)
// 加密
ciphertext := make([]byte, len(iv)+len(paddedData))
copy(ciphertext, iv)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[len(iv):], paddedData)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// decrypt AES CBC解密
func (c *Client) decrypt(encryptedText string) (string, error) {
keyBytes, err := hex.DecodeString(c.key)
if err != nil {
return "", err
}
ciphertext, err := base64.StdEncoding.DecodeString(encryptedText)
if err != nil {
return "", err
}
block, err := aes.NewCipher(keyBytes)
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
return "", fmt.Errorf("密文太短")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
if len(ciphertext)%aes.BlockSize != 0 {
return "", fmt.Errorf("密文长度不是块大小的倍数")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// 去除填充
unpaddedData, err := c.pkcs7Unpad(ciphertext)
if err != nil {
return "", err
}
return string(unpaddedData), nil
}
// pkcs7Pad PKCS7填充
func (c *Client) pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padtext...)
}
// pkcs7Unpad PKCS7去除填充
func (c *Client) pkcs7Unpad(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, fmt.Errorf("数据为空")
}
unpadding := int(data[length-1])
if unpadding > length {
return nil, fmt.Errorf("无效的填充")
}
return data[:length-unpadding], nil
}
// GetErrorByCode 根据错误码获取错误
func GetErrorByCode(code int) error {
// 对于有多个错误对应同一错误码的情况,返回第一个
switch code {
case 1000:
return ErrQueryEmpty
case 1001:
return ErrSystem
case 1002:
return ErrDecryptFail
case 1003:
return ErrRequestParam
case 1004:
return ErrInvalidIP
case 1005:
return ErrMissingAccessId
case 1006:
return ErrInvalidAccessId
case 1007:
return ErrFrozenAccount
case 1008:
return ErrProductNotFound
case 2001:
return ErrBusiness
default:
return fmt.Errorf("未知错误码: %d", code)
}
}
// GetCodeByError 根据错误获取错误码
func GetCodeByError(err error) int {
if code, exists := ErrorCodeMap[err]; exists {
return code
}
return -1
}

View File

@@ -0,0 +1,253 @@
package service
import (
"context"
"database/sql"
"in-server/app/main/api/internal/config"
"in-server/app/main/model"
"in-server/common/ctxdata"
jwtx "in-server/common/jwt"
"in-server/common/xerr"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type UserService struct {
Config *config.Config
userModel model.UserModel
userAuthModel model.UserAuthModel
}
// NewUserService 创建UserService实例
func NewUserService(config *config.Config, userModel model.UserModel, userAuthModel model.UserAuthModel) *UserService {
return &UserService{
Config: config,
userModel: userModel,
userAuthModel: userAuthModel,
}
}
// GenerateUUIDUserId 生成UUID用户ID
func (s *UserService) GenerateUUIDUserId(ctx context.Context) (string, error) {
id := uuid.NewString()
return id, nil
}
// RegisterUUIDUser 注册UUID用户返回用户ID
func (s *UserService) RegisterUUIDUser(ctx context.Context) (string, error) {
// 生成UUID
uuidStr, err := s.GenerateUUIDUserId(ctx)
if err != nil {
return "", err
}
var userId string
err = s.userModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
user := &model.User{Id: uuid.NewString()}
if _, userInsertErr := s.userModel.Insert(ctx, session, user); userInsertErr != nil {
return userInsertErr
}
userId = user.Id
userAuth := &model.UserAuth{Id: uuid.NewString(), UserId: userId, AuthType: model.UserAuthTypeUUID, AuthKey: uuidStr}
_, userAuthInsertErr := s.userAuthModel.Insert(ctx, session, userAuth)
return userAuthInsertErr
})
if err != nil {
return "", err
}
return userId, nil
}
// GetUserType 根据user.Mobile字段动态计算用户类型
// 如果有mobile则为正式用户(UserTypeNormal),否则为临时用户(UserTypeTemp)
func (s *UserService) GetUserType(ctx context.Context, userID string) (int64, error) {
user, err := s.userModel.FindOne(ctx, userID)
if err != nil {
return 0, err
}
if user.Mobile.Valid && user.Mobile.String != "" {
return model.UserTypeNormal, nil
}
return model.UserTypeTemp, nil
}
// GeneralUserToken 生成用户token动态计算userType
func (s *UserService) GeneralUserToken(ctx context.Context, userID string) (string, error) {
platform, err := ctxdata.GetPlatformFromCtx(ctx)
if err != nil {
return "", err
}
var authType string
var authKey string
// 获取用户信息根据mobile字段动态计算userType
user, err := s.userModel.FindOne(ctx, userID)
if err != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取用户信息失败: %v", err)
}
// 根据mobile判断用户类型
var userType int64
if user.Mobile.Valid && user.Mobile.String != "" {
userType = model.UserTypeNormal
} else {
userType = model.UserTypeTemp
}
platAuthType := s.getAuthTypeByPlatform(platform)
ua, err := s.userAuthModel.FindOneByUserIdAuthType(ctx, userID, platAuthType)
if err == nil && ua != nil {
authType = ua.AuthType
authKey = ua.AuthKey
}
token, generaErr := jwtx.GenerateJwtToken(jwtx.JwtClaims{
UserId: userID,
AgentId: "",
Platform: platform,
UserType: userType,
IsAgent: 0,
AuthType: authType,
AuthKey: authKey,
}, s.Config.JwtAuth.AccessSecret, s.Config.JwtAuth.AccessExpire)
if generaErr != nil {
return "", errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "更新token, 生成token失败 : %s", userID)
}
return token, nil
}
func (s *UserService) getAuthTypeByPlatform(platform string) string {
switch platform {
case model.PlatformWxMini:
return model.UserAuthTypeWxMiniOpenID
case model.PlatformWxH5:
return model.UserAuthTypeWxh5OpenID
case model.PlatformH5, model.PlatformApp:
return model.UserAuthTypeUUID
default:
return model.UserAuthTypeUUID
}
}
// RegisterUser 注册用户返回用户ID
// 只负责创建新用户(手机号不存在时),不处理合并逻辑
// 如果有临时用户claims会将临时用户的认证绑定到新用户
func (s *UserService) RegisterUser(ctx context.Context, mobile string) (string, error) {
// 检查手机号是否已存在
user, err := s.userModel.FindOneByMobile(ctx, sql.NullString{String: mobile, Valid: true})
if err != nil && !errors.Is(err, model.ErrNotFound) {
return "", err
}
if user != nil {
return "", errors.New("用户已注册")
}
// 获取当前登录态(可能为空)
claims, err := ctxdata.GetClaimsFromCtx(ctx)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return "", err
}
var userId string
err = s.userModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
// 创建新用户
user := &model.User{Id: uuid.NewString(), Mobile: sql.NullString{String: mobile, Valid: true}}
if _, userInsertErr := s.userModel.Insert(ctx, session, user); userInsertErr != nil {
return userInsertErr
}
userId = user.Id
// 创建 mobile 认证
_, userAuthInsertErr := s.userAuthModel.Insert(ctx, session, &model.UserAuth{
Id: uuid.NewString(),
UserId: userId,
AuthType: model.UserAuthTypeMobile,
AuthKey: mobile,
})
if userAuthInsertErr != nil {
return userAuthInsertErr
}
// 如果有临时用户,将临时用户的认证绑定到新用户
if claims != nil {
// 检查临时用户是否已有该认证类型
existingAuth, err := s.userAuthModel.FindOneByAuthTypeAuthKey(ctx, claims.AuthType, claims.AuthKey)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return err
}
// 如果认证不存在,创建新的认证绑定
if existingAuth == nil {
_, err = s.userAuthModel.Insert(ctx, session, &model.UserAuth{
Id: uuid.NewString(),
UserId: userId,
AuthType: claims.AuthType,
AuthKey: claims.AuthKey,
})
if err != nil {
return err
}
} else if existingAuth.UserId != userId {
// 如果认证已存在但属于其他用户,迁移到新用户
existingAuth.UserId = userId
if _, err := s.userAuthModel.Update(ctx, session, existingAuth); err != nil {
return err
}
}
}
return nil
})
if err != nil {
return "", err
}
return userId, nil
}
// TempUserBindUser 临时用户绑定用户添加mobile使其变为正式用户
func (s *UserService) TempUserBindUser(ctx context.Context, session sqlx.Session, normalUserID string) error {
claims, err := ctxdata.GetClaimsFromCtx(ctx)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return err
}
if claims == nil {
return errors.New("无临时用户")
}
// 检查当前用户是否已经绑定了mobile根据mobile判断而不是userType
tempUser, err := s.userModel.FindOne(ctx, claims.UserId)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return err
}
if tempUser != nil && tempUser.Mobile.Valid && tempUser.Mobile.String != "" {
return errors.New("临时用户已注册")
}
existingAuth, err := s.userAuthModel.FindOneByAuthTypeAuthKey(ctx, claims.AuthType, claims.AuthKey)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return err
}
if existingAuth != nil {
return errors.New("临时用户已注册")
}
if session == nil {
err := s.userAuthModel.Trans(ctx, func(ctx context.Context, session sqlx.Session) error {
_, err = s.userAuthModel.Insert(ctx, session, &model.UserAuth{Id: uuid.NewString(), UserId: normalUserID, AuthType: claims.AuthType, AuthKey: claims.AuthKey})
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
} else {
_, err = s.userAuthModel.Insert(ctx, session, &model.UserAuth{Id: uuid.NewString(), UserId: normalUserID, AuthType: claims.AuthType, AuthKey: claims.AuthKey})
if err != nil {
return err
}
return nil
}
}

View File

@@ -0,0 +1,208 @@
package service
import (
"context"
"encoding/json"
"fmt"
"io"
"in-server/app/main/api/internal/config"
tianyuanapi "in-server/app/main/api/internal/service/tianyuanapi_sdk"
"net/http"
"github.com/tidwall/gjson"
)
type VerificationService struct {
c config.Config
tianyuanapi *tianyuanapi.Client
apiRequestService *ApiRequestService
}
func NewVerificationService(c config.Config, tianyuanapi *tianyuanapi.Client, apiRequestService *ApiRequestService) *VerificationService {
return &VerificationService{
c: c,
tianyuanapi: tianyuanapi,
apiRequestService: apiRequestService,
}
}
// 二要素
type TwoFactorVerificationRequest struct {
Name string
IDCard string
}
type TwoFactorVerificationResp struct {
Msg string `json:"msg"`
Success bool `json:"success"`
Code int `json:"code"`
Data *TwoFactorVerificationData `json:"data"` //
}
type TwoFactorVerificationData struct {
Birthday string `json:"birthday"`
Result int `json:"result"`
Address string `json:"address"`
OrderNo string `json:"orderNo"`
Sex string `json:"sex"`
Desc string `json:"desc"`
}
// 三要素
type ThreeFactorVerificationRequest struct {
Name string
IDCard string
Mobile string
}
// VerificationResult 定义校验结果结构体
type VerificationResult struct {
Passed bool
Err error
}
// ValidationError 定义校验错误类型
type ValidationError struct {
Message string
}
func (e *ValidationError) Error() string {
return e.Message
}
func (r *VerificationService) TwoFactorVerification(request TwoFactorVerificationRequest) (*VerificationResult, error) {
resp, err := r.tianyuanapi.CallInterface("YYSYBE08", map[string]interface{}{
"name": request.Name,
"id_card": request.IDCard,
})
if err != nil {
return nil, fmt.Errorf("请求失败: %v", err)
}
respBytes, err := json.Marshal(resp.Data)
if err != nil {
return nil, fmt.Errorf("转换响应失败: %v", err)
}
// 使用gjson获取resultCode
resultCode := gjson.GetBytes(respBytes, "ctidRequest.ctidAuth.resultCode")
if !resultCode.Exists() {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "获取resultCode失败"},
}, nil
}
// 获取resultCode的第一个字符
resultCodeStr := resultCode.String()
if len(resultCodeStr) == 0 {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "resultCode为空"},
}, nil
}
firstChar := string(resultCodeStr[0])
if firstChar != "0" && firstChar != "5" {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "姓名与身份证不一致"},
}, nil
}
return &VerificationResult{Passed: true, Err: nil}, nil
}
func (r *VerificationService) ThreeFactorVerification(request ThreeFactorVerificationRequest) (*VerificationResult, error) {
resp, err := r.tianyuanapi.CallInterface("YYSY09CD", map[string]interface{}{
"name": request.Name,
"id_card": request.IDCard,
"mobile_no": request.Mobile,
})
if err != nil {
return nil, fmt.Errorf("请求失败: %v", err)
}
respBytes, err := json.Marshal(resp.Data)
if err != nil {
return nil, fmt.Errorf("转换响应失败: %v", err)
}
// 解析data.code
code := gjson.GetBytes(respBytes, "code")
if !code.Exists() {
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "身份信息异常"},
}, nil
}
codeStr := code.String()
switch codeStr {
case "1000":
// 一致
return &VerificationResult{Passed: true, Err: nil}, nil
case "1001":
// 不一致
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "姓名、证件号、手机号信息不一致"},
}, nil
default:
// 其他异常
return &VerificationResult{
Passed: false,
Err: &ValidationError{Message: "身份信息异常"},
}, nil
}
}
// GetWechatH5OpenID 通过code获取微信H5 OpenID
func (r *VerificationService) GetWechatH5OpenID(ctx context.Context, code string) (string, error) {
appID := r.c.WechatH5.AppID
appSecret := r.c.WechatH5.AppSecret
url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var data struct {
Openid string `json:"openid"`
}
if err := json.Unmarshal(body, &data); err != nil {
return "", err
}
if data.Openid == "" {
return "", fmt.Errorf("openid为空")
}
return data.Openid, nil
}
// GetWechatMiniOpenID 通过code获取微信小程序 OpenID
func (r *VerificationService) GetWechatMiniOpenID(ctx context.Context, code string) (string, error) {
appID := r.c.WechatMini.AppID
appSecret := r.c.WechatMini.AppSecret
url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appID, appSecret, code)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var data struct {
Openid string `json:"openid"`
}
if err := json.Unmarshal(body, &data); err != nil {
return "", err
}
if data.Openid == "" {
return "", fmt.Errorf("openid为空")
}
return data.Openid, nil
}