first commit

This commit is contained in:
Yangtao
2025-11-18 17:48:20 +08:00
commit 6e56cab848
196 changed files with 65809 additions and 0 deletions

View File

@ -0,0 +1,132 @@
package Netease
import (
"servicebase/pkg/common/HyTools"
"encoding/json"
"net/url"
"time"
Netease "servicebase/pkg/common/netease"
"github.com/anxpp/beego"
"github.com/anxpp/beego/logs"
)
const (
// ChatRoomManagerUserId 聊天室消息管理员ID
ChatRoomManagerUserId = "34cc7185d0b60eacf38f616b8aad8c51"
SystemNoticeUserId = "x94b992dbb4e4dfca9c971200d797a02"
P2pMessagesTypeSystemNotice = "104"
TimeDefaultFormat = "Y-m-d H:i:s"
)
type ImService struct {
}
// ImMsgBodyAttach IM消息 body对象
type ImMsgBodyAttach struct {
TypeCode string `json:"TypeCode"`
BizData interface{} `json:"BizData"`
Msg string `json:"msg,omitempty"`
}
// ChatRoomMsgAttach 聊天室自定义消息
type ChatRoomMsgAttach struct {
TypeCode string `json:"TypeCode"`
BizData interface{} `json:"BizData"`
}
// SendCustomMsgToChatroomByChatroomManager 向聊天室发消息
func (s *ImService) SendCustomMsgToChatroomByChatroomManager(messageRoomId string, attachData ChatRoomMsgAttach) error {
msgParameter := make(map[string]string)
msgParameter["roomid"] = messageRoomId
msgParameter["msgId"] = HyTools.GetUUID()
msgParameter["fromAccid"] = ChatRoomManagerUserId
msgParameter["msgType"] = "100" //自定义消息
msgParameter["resendFlag"] = "0"
bodyBytes, _ := json.Marshal(attachData)
msgParameter["ext"] = ""
msgParameter["attach"] = string(bodyBytes)
imClient := Netease.NewImClient()
return imClient.SendChatroomMsg(msgParameter)
}
// SendCustomerMsgFromAToB 发IM点对点自定义消息 系统通知 用户关系变化
func (s *ImService) SendCustomerMsgFromAToB(fromAccid, toAccid, pushContent, payloadJson string, bodyModel ImMsgBodyAttach, optionMap map[string]string) error {
msgParameter := make(map[string]string)
msgParameter["from"] = fromAccid
msgParameter["ope"] = "0" //0=p2p 1=群消息
msgParameter["to"] = toAccid
msgParameter["type"] = "100" //0 表示文本消息, 1 表示图片, 2 表示语音, 3 表示视频, 4 表示地理位置信息, 6 表示文件, 100 自定义消息类型
bodyBytes, _ := json.Marshal(bodyModel)
msgParameter["body"] = string(bodyBytes) //最大长度5000字符为一个JSON串
msgParameter["antispam"] = "false" //对于对接了易盾反垃圾功能的应用,本消息是否需要指定经由易盾检测的内容 只对消息类型为100 自定义消息类型 的消息生效。
optionBytes, _ := json.Marshal(optionMap)
msgParameter["option"] = string(optionBytes) //发消息时特殊指定的行为选项,JSON格式可用于指定消息的漫游存云端历史发送方多端同步推送消息抄送等特殊行为
//需要推送
if optionMap["push"] == "true" {
if len(pushContent) > 0 {
msgParameter["pushcontent"] = pushContent // ios推送内容不超过150字符option选项中允许推送push=true此字段可以指定推送内容
}
if len(payloadJson) > 0 {
msgParameter["payload"] = payloadJson // ios 推送对应的payload,必须是JSON,不能超过2k字符
}
}
imClient := Netease.NewImClient()
return imClient.SendMsg(msgParameter)
}
// SendSystemNoticeToUser 给用户发系统消息
// _ = messageService.SendSystemNoticeToUser(userId, "厅补贴到账通知", msgContent, "", "")
func (s *ImService) SendSystemNoticeToUser(toAccid, msgTitle, msgText, schemeUrl, imageUrl string) {
option := GetDefaultMsgOption()
fromUserId := SystemNoticeUserId
logs.Info("SendSystemNoticeToUser from " + fromUserId + "to " + toAccid)
pushContent := ""
payloadJson := ""
bizData := make(map[string]string, 0)
bizData["Title"] = url.QueryEscape(msgTitle)
bizData["Content"] = url.QueryEscape(msgText)
bizData["Scheme"] = schemeUrl
bizData["ImageUrl"] = imageUrl
bizData["CreateTime"] = beego.Date(time.Now(), TimeDefaultFormat)
//body的业务数据
var bodyAttach ImMsgBodyAttach
bodyAttach.TypeCode = P2pMessagesTypeSystemNotice
bodyAttach.BizData = bizData
bodyAttach.Msg = msgTitle
err := s.SendCustomerMsgFromAToB(fromUserId, toAccid, pushContent, payloadJson, bodyAttach, option)
if nil != err {
logs.Error("通知发送失败!!!!")
logs.Info(err.Error())
}
}
// GetDefaultMsgOption 发送消息默认的配置
func GetDefaultMsgOption() map[string]string {
/*
1. roam: 该消息是否需要漫游默认true需要app开通漫游消息功能
2. history: 该消息是否存云端历史默认true
3. sendersync: 该消息是否需要发送方多端同步默认true
4. push: 该消息是否需要APNS推送或安卓系统通知栏推送默认true
5. route: 该消息是否需要抄送第三方默认true (需要app开通消息抄送功能);
6. badge:该消息是否需要计入到未读计数中默认true;
7. needPushNick: 推送文案是否需要带上昵称不设置该参数时默认true;
8. persistent: 是否需要存离线消息不设置该参数时默认true。
*/
result := make(map[string]string)
result["roam"] = "true"
result["history"] = "true"
result["sendersync"] = "false"
result["push"] = "true"
result["route"] = "true"
result["badge"] = "true"
result["needPushNick"] = "false"
result["persistent"] = "true"
return result
}

View File

@ -0,0 +1,104 @@
package Netease
const (
// ChatroomCustomMessageTypePresentActivityMsg 聊天室打赏活动物品消息
ChatroomCustomMessageTypePresentActivityMsg = "380"
// ChatroomCustomMessageTypeFullScreenNoticeMsg 聊天室 全服通知动效
ChatroomCustomMessageTypeFullScreenNoticeMsg = "381"
)
const (
//聊天室字体颜色 - 黄色
CHATROOM_SYSTEM_MSG_COLOR_YELLOW = "#FFD700"
//聊天室字体颜色 - 绿色
CHATROOM_SYSTEM_MSG_COLOR_GREEN = "#8ADE4D"
//聊天室字体颜色 - 系统栏
CHATROOM_SYSTEM_MSG_COLOR_SYSTEM_BLUE = "#43EAE1"
//聊天室字体颜色 - 紫色
CHATROOM_SYSTEM_MSG_COLOR_PURPLE = "#E031FE"
// 默认等级的背景颜色
SKILL_LEVEL_DEFAULT_BG_COLOR = "#FFD700"
//聊天室字体颜色 - 蓝色
CHATROOM_SYSTEM_MSG_COLOR_BLUE = "#25C6FD"
//聊天室字体颜色 - 青色
CHATROOM_SYSTEM_MSG_COLOR_QING = "#00FFCC"
//聊天室字体颜色 - 白色
CHATROOM_SYSTEM_MSG_COLOR_WHITE = "#FFFFFF"
)
type MessageService struct {
}
type TextAndColor struct {
Text string
Color string
}
// ChatroomFullScreenNoticeMsgBizData 聊天室活动全服飘屏通知
type ChatroomFullScreenNoticeMsgBizData struct {
ChatroomId string
ContentIcon string
ContentText string
ContentTextColor string //内容字体颜色
ContentBgColor string //背景颜色
AnimationApngUrl string //加入播放礼物动效队列
BgImgUrl string //背景图
TextList []TextAndColor //文字颜色列表
StayTime string //停留时长(秒)
}
// ChatroomPresentActivityMsgBizData 聊天室打赏活动消息data数据结构
type ChatroomPresentActivityMsgBizData struct {
ChatroomId string
FromUserId string
FromNickName string
FromAvatar string
FromNickNameColor string //打赏人昵称颜色
ActionText string //动作文本 :赠送一个盲盒给
ActionTextColor string //动作文本颜色
ToNickName string
ToNickNameColor string //被打赏人昵称颜色
PresentCount string //物品个数
PresentGoodsName string
PresentGoodsIcon string
PresentGoodsNameColor string
ResultGoodsIcon string
ComboHitCount string //连击次数
AnimationApngUrl string //加入播放礼物动效队列 有的话显示播放动画
AnimationFormat string //动画格式 SVGA APNG
FillMode string //填充模式 1=左右 2=上下
IsViewFlyView string //是否显示飘屏view 有的话显示连击信息
//显示到信息流
TextList []TextAndColor //信息流文字颜色列表
}
// SendChatroomSystemMsgV2 发送聊天室系统消息 V2
func (s *MessageService) SendChatroomSystemMsgV2(messageRoomId string, msgData ChatroomPresentActivityMsgBizData) (err error) {
// 发打赏消息
var service ImService
attachModel := ChatRoomMsgAttach{}
//消息类型
typeCode := ChatroomCustomMessageTypePresentActivityMsg
attachModel.TypeCode = typeCode
attachModel.BizData = msgData
err = service.SendCustomMsgToChatroomByChatroomManager(messageRoomId, attachModel)
return
}
// SendChatroomPresentActivityFullServiceMsg 发送聊天室活动全服
func (s *MessageService) SendChatroomPresentActivityFullServiceMsg(messageRoomId string, msgData ChatroomFullScreenNoticeMsgBizData) (err error) {
// 发打赏消息
var service ImService
attachModel := ChatRoomMsgAttach{}
//消息类型
typeCode := ChatroomCustomMessageTypeFullScreenNoticeMsg
attachModel.TypeCode = typeCode
attachModel.BizData = msgData
err = service.SendCustomMsgToChatroomByChatroomManager(messageRoomId, attachModel)
return
}

View File

@ -0,0 +1,43 @@
package Netease
import (
"servicebase/pkg/log"
"encoding/json"
"github.com/pkg/errors"
"github.com/spf13/viper"
captcha "github.com/yidun/yidun-golang-sdk/yidun/service/captcha"
)
var (
CaptchaId = "28a052c000324d2e992e9e184291c92d"
)
// CaptchaSecondVerify 验证码二次校验请求
func CaptchaSecondVerify(captchaId, validate string) (bool, error) {
request := captcha.NewCaptchaVerifyRequest()
var user string = ""
request.SetCaptchaId(captchaId).SetValidate(validate).SetUser(user)
secretId := viper.GetString("netease.captcha.secretId")
secretKey := viper.GetString("netease.captcha.secretKey")
captchaClient := captcha.NewCaptchaVerifyClientWithAccessKey(secretId, secretKey)
response, err := captchaClient.Verify(request)
if err != nil {
log.ErrorF("CaptchaSecondVerify err: %+v", err)
return false, err
}
if response == nil {
log.ErrorF("CaptchaSecondVerify response is nil")
return false, errors.Errorf("CaptchaSecondVerify response is nil")
}
respBody, err := json.Marshal(response)
if err != nil {
return false, err
}
log.InfoF("CaptchaSecondVerify response is : %s", string(respBody))
if response.Result == nil {
log.ErrorF("CaptchaSecondVerify response.Result is nil")
return false, errors.Errorf("CaptchaSecondVerify response.Result is nil")
}
return *response.Result, nil
}

View File

@ -0,0 +1,196 @@
package Netease
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"servicebase/pkg/log"
"sort"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/tjfoc/gmsm/sm3"
)
const (
apiURL = "https://verify.dun.163.com/v1/face/liveness/h5/auth"
recheckTokenUrl = "https://verify.dun.163.com/v1/face/liveness/h5/recheck"
version = "v1"
)
type ApplyInfoReq struct {
Name string
CardNo string
RedirectUrl string
CallBackUrl string
DataId string
CallbackValidate string
EncryptType string
}
type BaseRsp[T any] struct {
Code int `json:"code"`
Msg string `json:"msg"`
Result T `json:"result"`
}
type H5ApplyLivePersonRsp struct {
AuthUrl string `json:"authUrl"`
AuthToken string `json:"authToken"`
}
type H5ReCheckLivePersonTokenRsp struct {
TaskId string `json:"taskId"`
PicType int64 `json:"picType"`
Avatar string `json:"avatar"`
Status int64 `json:"status"`
ReasonType int `json:"reasonType"`
IsPayed int64 `json:"isPayed"`
SimilarityScore float64 `json:"similarityScore"`
FaceMatched int64 `json:"faceMatched"`
FaceAttributeInfo interface{} `json:"faceAttributeInfo"`
ExtInfo ExtInfoEntity `json:"extInfo"`
}
type ExtInfoEntity struct {
SuspectedNonageFlag bool `json:"suspectedNonageFlag"`
}
// H5ApplyLivePerson 请求易盾生成h5人身验证h5 url 和 authToken
func H5ApplyLivePerson(ctx context.Context, req *ApplyInfoReq) (*H5ApplyLivePersonRsp, error) {
params := url.Values{
"name": []string{req.Name},
"cardNo": []string{req.CardNo},
"redirectUrl": []string{req.RedirectUrl},
}
rsp, err := apply(params)
if err != nil {
return nil, err
}
return rsp, nil
}
// H5ReCheckLivePersonToken 根据authToken二次验证并获取相关信息如正面拍照的活体图片
func H5ReCheckLivePersonToken(ctx context.Context, token string) (*H5ReCheckLivePersonTokenRsp, error) {
params := url.Values{
"authToken": []string{token},
}
rsp, err := checkToken(params)
if err != nil {
return nil, err
}
return rsp, nil
}
// 生成签名信息
func genSignature(params url.Values) string {
var paramStr string
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
paramStr += key + params[key][0]
}
paramStr += viper.GetString("netease.captcha.secretKey")
if params["signatureMethod"] != nil && params["signatureMethod"][0] == "SM3" {
sm3Reader := sm3.New()
sm3Reader.Write([]byte(paramStr))
return hex.EncodeToString(sm3Reader.Sum(nil))
}
md5Reader := md5.New()
md5Reader.Write([]byte(paramStr))
return hex.EncodeToString(md5Reader.Sum(nil))
}
// 请求易盾接口
func apply(params url.Values) (*H5ApplyLivePersonRsp, error) {
params["secretId"] = []string{viper.GetString("netease.captcha.secretId")}
params["businessId"] = []string{viper.GetString("netease.captcha.businessId")}
params["version"] = []string{version}
params["timestamp"] = []string{strconv.FormatInt(time.Now().UnixNano()/1000000, 10)}
params["nonce"] = []string{strconv.FormatInt(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(10000000000), 10)}
params["signature"] = []string{genSignature(params)}
resp, err := http.Post(apiURL, "application/x-www-form-urlencoded", strings.NewReader(params.Encode()))
if err != nil {
return nil, errors.WithStack(err)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("请求网易易盾获取h5人身验证失败状态码为%d", resp.StatusCode)
}
defer resp.Body.Close()
contents, _ := io.ReadAll(resp.Body)
log.InfoF("请求网易易盾获取h5人身验证响应: %s", string(contents))
var rsp BaseRsp[*H5ApplyLivePersonRsp]
err = json.Unmarshal(contents, &rsp)
if err != nil {
return nil, errors.WithStack(err)
}
if rsp.Code != 200 {
return nil, errors.Errorf("响应体状态码不是200(%d),信息: %s", rsp.Code, rsp.Msg)
}
return rsp.Result, nil
}
func checkToken(params url.Values) (*H5ReCheckLivePersonTokenRsp, error) {
params["secretId"] = []string{viper.GetString("netease.captcha.secretId")}
params["businessId"] = []string{viper.GetString("netease.captcha.businessId")}
params["version"] = []string{version}
params["timestamp"] = []string{strconv.FormatInt(time.Now().UnixNano()/1000000, 10)}
params["nonce"] = []string{strconv.FormatInt(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(10000000000), 10)}
params["signature"] = []string{genSignature(params)}
resp, err := http.Post(recheckTokenUrl, "application/x-www-form-urlencoded", strings.NewReader(params.Encode()))
if err != nil {
return nil, errors.WithStack(err)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("请求网易易盾获取h5人身验证失败状态码为%d", resp.StatusCode)
}
defer resp.Body.Close()
contents, _ := io.ReadAll(resp.Body)
log.InfoF("请求网易云盾获取人身核验二次验证token响应: %s", string(contents))
var rsp BaseRsp[*H5ReCheckLivePersonTokenRsp]
err = json.Unmarshal(contents, &rsp)
if err != nil {
return nil, errors.WithStack(err)
}
if rsp.Code != 200 {
return nil, errors.Errorf("响应体状态码不是200(%d),信息: %s", rsp.Code, rsp.Msg)
}
return rsp.Result, nil
}
var livePersonAndIdCheckFailReason = map[int]string{
2: "活体通过,姓名身份证号一致,人脸比对非同一人",
3: "活体通过,姓名身份证号不一致",
4: "活体不通过",
5: "活体检测超时或出现异常",
6: "活体通过,查无此身份证",
7: "活体通过,库中无此身份证照片",
8: "活体通过,人脸照过大",
9: "活体通过,权威数据源出现异常",
10: "疑似攻击,建议拦截",
11: "检测对象为未成年人",
}
func GetLivePersonAndIdCheckFailReason(code int) string {
r, ok := livePersonAndIdCheckFailReason[code]
if !ok {
return fmt.Sprintf("其他原因ReasonType==%d", code)
}
return r
}

View File

@ -0,0 +1,78 @@
package Netease
import (
"servicebase/pkg/common/HyTools"
"servicebase/pkg/log"
"servicebase/pkg/partner/qiniu"
"context"
"github.com/spf13/viper"
"io"
"net/http"
"testing"
)
func TestApplyH5LivePerson(t *testing.T) {
log.Init()
rst, err := H5ApplyLivePerson(context.Background(), &ApplyInfoReq{
Name: "xxx", // 姓名
CardNo: "xxxxxxx", // 身份证号码x需要变成大写X
RedirectUrl: "https://www.baidu.com",
CallBackUrl: "",
DataId: "",
CallbackValidate: "",
EncryptType: "",
})
if err != nil {
t.Error(err)
}
println(rst.AuthToken)
println(rst.AuthUrl)
}
func TestH5ReCheckLivePersonToken(t *testing.T) {
log.Init()
_, err := H5ReCheckLivePersonToken(context.Background(), "6ZgHU-x9XsRVF8aS7PIFppBho28QEUAR")
if err != nil {
t.Error(err)
}
}
func TestB(t *testing.T) {
log.Init()
// key: CwGN8XGmbEZr7qqJl-y-QodcUYREz8ph_glVKCqp
// secret: KbZKt8WwQcZ6II0tygMLsO3KWpm50aMz737VaMV0
viper.Set("qiniu.key", "CwGN8XGmbEZr7qqJl-y-QodcUYREz8ph_glVKCqp")
viper.Set("qiniu.secret", "KbZKt8WwQcZ6II0tygMLsO3KWpm50aMz737VaMV0")
viper.Set("qiniu.bucket.photo", "ddphoto")
key := func() string {
resp, err := http.Get("xxx")
if err != nil {
log.ErrorF("获取人脸核身正面照图片错误:%+v", err)
return ""
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.ErrorF("获取人脸核身正面照图片错误 http code为%d", resp.StatusCode)
return ""
}
imageData, err := io.ReadAll(resp.Body)
if err != nil {
log.ErrorF("")
return ""
}
key := "upload/" + HyTools.GetUUID() + ".jpg"
//上传文件
newKey := qiniu.UploadFile(context.Background(), viper.GetString("qiniu.bucket.photo"), imageData, key)
if len(newKey) == 0 {
log.ErrorF("获取人脸核身正面照图片上传到七牛oss失败")
return ""
}
return key
}()
println(key)
}