security.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package security
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/silenceper/wechat/v2/miniprogram"
  7. "github.com/silenceper/wechat/v2/miniprogram/content"
  8. "github.com/silenceper/wechat/v2/util"
  9. )
  10. // 检查一段文本是否含有违法违规内容。
  11. // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html
  12. const SecurityMsgCheckUrl = "https://api.weixin.qq.com/wxa/msg_sec_check"
  13. type Security struct {
  14. *content.Content
  15. }
  16. type MyMiniprogram struct {
  17. *miniprogram.MiniProgram
  18. }
  19. func NewMyMiniprogram(miniprogram *miniprogram.MiniProgram) *MyMiniprogram {
  20. return &MyMiniprogram{miniprogram}
  21. }
  22. type BodyContent struct {
  23. Version int8 `json:"version"` // 接口版本号,2.0版本为固定值2
  24. Openid string `json:"openid"` // 用户的openid(用户需在近两小时访问过小程序)
  25. Scene int8 `json:"scene"` // 场景枚举值(1 资料;2 评论;3 论坛;4 社交日志)
  26. Content string `json:"content"` // 需检测的文本内容,文本字数的上限为2500字,需使用UTF-8编码
  27. Nickname string `json:"nickname"` // 用户昵称,需使用UTF-8编码
  28. Title string `json:"title"` // 文本标题,需使用UTF-8编码
  29. Signature string `json:"signature"` // 个性签名,该参数仅在资料类场景有效(scene=1),需使用UTF-8编码
  30. }
  31. func (s *MyMiniprogram) MsgSecCheckWithResult(bodyContent *BodyContent) (result Result, err error) {
  32. var accessToken string
  33. accessToken, err = s.GetContentSecurity().GetAccessToken()
  34. if err != nil {
  35. return
  36. }
  37. uri := fmt.Sprintf("%s?access_token=%s", SecurityMsgCheckUrl, accessToken)
  38. response, err := util.PostJSON(uri, bodyContent)
  39. if err != nil {
  40. return
  41. }
  42. return DecodeWithResult(response, "MsgSecCheck")
  43. }
  44. type Result struct {
  45. Result *ResultBody
  46. }
  47. type ResultBody struct {
  48. Suggest string //建议,有risky、pass、review三种值
  49. Label int //命中标签枚举值,100 正常;10001 广告;20001 时政;20002 色情;20003 辱骂;20006 违法犯罪;20008 欺诈;20012 低俗;20013 版权;21000 其他
  50. }
  51. func DecodeWithResult(response []byte, apiName string) (result Result, err error) {
  52. var commError util.CommonError
  53. err = json.Unmarshal(response, &commError)
  54. if err != nil {
  55. return
  56. }
  57. if commError.ErrCode != 0 {
  58. err = errors.New(fmt.Sprintf("%s Error , errcode=%d , errmsg=%s", apiName, commError.ErrCode, commError.ErrMsg))
  59. return
  60. }
  61. err = json.Unmarshal(response, &result)
  62. if err != nil {
  63. return
  64. }
  65. return
  66. }