广告平台(总站长使用)
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

244 linhas
7.8 KiB

  1. package hdl
  2. import (
  3. "applet/app/cfg"
  4. "applet/app/e"
  5. "applet/app/lib/wechat"
  6. md2 "applet/app/lib/wechat/md"
  7. "applet/app/utils"
  8. "applet/app/utils/cache"
  9. db "code.fnuoos.com/zhimeng/model.git/src"
  10. "code.fnuoos.com/zhimeng/model.git/src/super/implement"
  11. "encoding/xml"
  12. "fmt"
  13. "github.com/gin-gonic/gin"
  14. "io/ioutil"
  15. "net/http"
  16. "net/url"
  17. )
  18. type OriginalWxMessage struct {
  19. AppID string `xml:"AppId"`
  20. Encrypt string `xml:"Encrypt"`
  21. }
  22. func SetTicket(c *gin.Context) {
  23. query := c.Request.URL.Query()
  24. var params = map[string]string{}
  25. for key, value := range query {
  26. fmt.Printf("Key: %s, Value: %s\n", key, value[0])
  27. params[key] = value[0]
  28. }
  29. utils.FilePutContents("SetTicket_Get", utils.SerializeStr(params))
  30. var originalWxMessage OriginalWxMessage
  31. // 读取请求体
  32. body, err := ioutil.ReadAll(c.Request.Body)
  33. if err != nil {
  34. c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read request body"})
  35. return
  36. }
  37. utils.FilePutContents("SetTicket_Post", string(body))
  38. err = xml.Unmarshal(body, &originalWxMessage)
  39. if err != nil {
  40. fmt.Println("setTicket>>>>>>>>", err.Error())
  41. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  42. return
  43. }
  44. //1、查找对应 wx_open_third_party_app_list 记录
  45. wxOpenThirdPartyAppListDb := implement.NewWxOpenThirdPartyAppListDb(db.Db)
  46. wxOpenThirdPartyAppList, err := wxOpenThirdPartyAppListDb.GetWxOpenThirdPartyAppListByAppId(originalWxMessage.AppID)
  47. if err != nil {
  48. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  49. return
  50. }
  51. if wxOpenThirdPartyAppList == nil {
  52. c.JSON(http.StatusBadRequest, gin.H{"error": "未查询到对应App记录"})
  53. return
  54. }
  55. //2、对消息体进行解密
  56. instance := wechat.NewWechatMsgCrypt(wxOpenThirdPartyAppList.Token, wxOpenThirdPartyAppList.AesKey, wxOpenThirdPartyAppList.Appid)
  57. eventRequest := wechat.EventEncryptRequest{
  58. XMLName: xml.Name{},
  59. Encrypt: originalWxMessage.Encrypt,
  60. Appid: originalWxMessage.AppID,
  61. }
  62. reqWxMessage := instance.WechatEventDecrypt(eventRequest, params["msg_signature"], params["timestamp"], params["nonce"])
  63. fmt.Println("解密结果:", reqWxMessage)
  64. utils.FilePutContents("SetTicket_XML", utils.SerializeStr(reqWxMessage))
  65. if reqWxMessage.InfoType == "component_verify_ticket" { //TODO::微信公众平台 验证票据
  66. cacheKey := fmt.Sprintf(md2.MasterComponentVerifyTicket, utils.AnyToString(wxOpenThirdPartyAppList.Uuid))
  67. cacheComponentVerifyTicket, _ := cache.GetString(cacheKey)
  68. if cacheComponentVerifyTicket == "" || cacheComponentVerifyTicket != reqWxMessage.ComponentVerifyTicket {
  69. cache.SetEx(cacheKey, reqWxMessage.ComponentVerifyTicket, 43140)
  70. wxOpenThirdPartyAppList.ComponentVerifyTicket = reqWxMessage.ComponentVerifyTicket
  71. _, err = wxOpenThirdPartyAppListDb.UpdateWxOpenThirdPartyAppList(wxOpenThirdPartyAppList, "component_verify_ticket")
  72. if err != nil {
  73. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  74. return
  75. }
  76. }
  77. }
  78. if reqWxMessage.InfoType == "unauthorized" { //TODO::微信公众平台 取消授权
  79. appid := reqWxMessage.AuthorizerAppid
  80. userWxAppletListDb := implement.NewUserWxAppletListDb(db.Db)
  81. userWxAppletList, err := userWxAppletListDb.GetUserWxAppletListByAppId(appid)
  82. if err != nil {
  83. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  84. return
  85. }
  86. if userWxAppletList == nil {
  87. c.JSON(http.StatusBadRequest, gin.H{"error": "未查询到对应小程序授权记录"})
  88. return
  89. }
  90. userWxAppletList.IsAuth = 0
  91. _, err = userWxAppletListDb.UpdateUserWxAppletList(userWxAppletList, "is_auth")
  92. if err != nil {
  93. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  94. return
  95. }
  96. }
  97. if reqWxMessage.InfoType == "unauthorized" || reqWxMessage.InfoType == "authorized" { //TODO::微信公众平台 授权 || 更新授权
  98. appid := reqWxMessage.AuthorizerAppid
  99. userWxAppletListDb := implement.NewUserWxAppletListDb(db.Db)
  100. userWxAppletList, err := userWxAppletListDb.GetUserWxAppletListByAppId(appid)
  101. if err != nil {
  102. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  103. return
  104. }
  105. if userWxAppletList == nil {
  106. c.JSON(http.StatusBadRequest, gin.H{"error": "未查询到对应小程序授权记录"})
  107. return
  108. }
  109. userWxAppletList.IsAuth = 1
  110. _, err = userWxAppletListDb.UpdateUserWxAppletList(userWxAppletList, "is_auth")
  111. if err != nil {
  112. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  113. return
  114. }
  115. }
  116. c.String(http.StatusOK, "success")
  117. return
  118. }
  119. func GetPreAuthCode(c *gin.Context) {
  120. masterId := c.DefaultQuery("master_id", "")
  121. wxOpenThirdPartyAppListDb := implement.NewWxOpenThirdPartyAppListDb(db.Db)
  122. wxOpenThirdPartyAppList, err := wxOpenThirdPartyAppListDb.GetWxOpenThirdPartyAppList(utils.StrToInt(masterId))
  123. if err != nil {
  124. e.OutErr(c, e.ERR, err.Error())
  125. return
  126. }
  127. if wxOpenThirdPartyAppList == nil {
  128. e.OutErr(c, e.ERR_NOT_FAN, "未查询到对应三方应用记录")
  129. return
  130. }
  131. wxApiService, err := wechat.NewWxApiService(masterId, wxOpenThirdPartyAppList.Appid, wxOpenThirdPartyAppList.AppSecret)
  132. if err != nil {
  133. e.OutErr(c, e.ERR, err.Error())
  134. return
  135. }
  136. preAuthCode, err := wxApiService.GetPreAuthCode()
  137. if err != nil {
  138. e.OutErr(c, e.ERR, err.Error())
  139. return
  140. }
  141. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  142. redirectURI := "http://super.advertisement.dengbiao.top/api/wxOpen/getAuthUrlCallBack?masterId=" + masterId
  143. if cfg.Prd {
  144. redirectURI = "http://ad.zhios.cn/api/wxOpen/getAuthUrlCallBack?masterId=" + masterId
  145. }
  146. // 对redirectURI进行URL编码
  147. //encodedRedirectURI := url.QueryEscape(redirectURI)
  148. // 构造微信登录页面的URL
  149. baseURL := "https://mp.weixin.qq.com/cgi-bin/componentloginpage"
  150. query := url.Values{}
  151. query.Add("component_appid", wxOpenThirdPartyAppList.Appid)
  152. query.Add("pre_auth_code", preAuthCode)
  153. query.Add("redirect_uri", redirectURI)
  154. query.Add("auth_type", "2")
  155. // 将查询参数附加到基础URL
  156. authURL := baseURL + "?" + query.Encode()
  157. // 设置JavaScript重定向
  158. c.Header("Content-Type", "text/html") //TODO::必须指定相应内容为 text/html, 否则浏览器不能正确解析
  159. c.String(200, `
  160. <script>
  161. window.onload = function () {
  162. window.location.href = '%s';
  163. };
  164. </script>`, authURL)
  165. }
  166. func GetAuthUrlCallBack(c *gin.Context) {
  167. authCode := c.DefaultQuery("auth_code", "")
  168. if authCode == "" {
  169. e.OutErr(c, e.ERR_NOT_FAN, "auth_code获取失败")
  170. return
  171. }
  172. fmt.Println("auth_code>>>>>>>>", authCode)
  173. masterId := c.DefaultQuery("masterId", "")
  174. wxOpenThirdPartyAppListDb := implement.NewWxOpenThirdPartyAppListDb(db.Db)
  175. wxOpenThirdPartyAppList, err := wxOpenThirdPartyAppListDb.GetWxOpenThirdPartyAppList(utils.StrToInt(masterId))
  176. if err != nil {
  177. return
  178. }
  179. if wxOpenThirdPartyAppList == nil {
  180. e.OutErr(c, e.ERR_NOT_FAN, "未查询到对应三方应用记录")
  181. return
  182. }
  183. wxApiService, err := wechat.NewWxApiService(masterId, wxOpenThirdPartyAppList.Appid, wxOpenThirdPartyAppList.AppSecret)
  184. if err != nil {
  185. e.OutErr(c, e.ERR, err.Error())
  186. return
  187. }
  188. resp, err := wxApiService.GetAuthorizerAccessTokenByAuthCode(authCode)
  189. if err != nil {
  190. e.OutErr(c, e.ERR, err.Error())
  191. return
  192. }
  193. userWxAppletListDb := implement.NewUserWxAppletListDb(db.Db)
  194. userWxAppletList, err := userWxAppletListDb.GetUserWxAppletListByAppId(resp.AuthorizationInfo.AuthorizerAppid)
  195. if err != nil {
  196. return
  197. }
  198. if userWxAppletList == nil {
  199. e.OutErr(c, e.ERR_NOT_FAN, "未查询到小程序应用记录")
  200. return
  201. }
  202. userWxAppletList.IsAuth = 1
  203. userWxAppletList.AuthorizerRefreshToken = resp.AuthorizationInfo.AuthorizerRefreshToken
  204. _, err = userWxAppletListDb.UpdateUserWxAppletList(userWxAppletList, "authorizer_refresh_token", "is_auth")
  205. if err != nil {
  206. e.OutErr(c, e.ERR_DB_ORM, err.Error())
  207. return
  208. }
  209. c.HTML(http.StatusOK, "success.html", gin.H{
  210. //"applet_name": "激活鸟",
  211. })
  212. return
  213. }
  214. func WechatMsgRecieve(c *gin.Context) {
  215. return
  216. }