router.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package router
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/frame/g"
  5. "github.com/gogf/gf/net/ghttp"
  6. "github.com/gogf/gf/os/gtime"
  7. douyinOauth "github.com/lin-jim-leon/douyin/open/oauth"
  8. douyinUser "github.com/lin-jim-leon/douyin/open/user"
  9. _ "github.com/lin-jim-leon/kuaishou/open/merchant"
  10. "github.com/lin-jim-leon/kuaishou/open/oauth"
  11. _ "github.com/lin-jim-leon/kuaishou/open/oauth"
  12. "github.com/lin-jim-leon/kuaishou/open/user"
  13. _ "github.com/lin-jim-leon/kuaishou/open/user"
  14. youngeetalentapi "youngmini_server/app/api/youngee_talent_api"
  15. "youngmini_server/app/model/youngee_talent_model"
  16. "youngmini_server/app/service/youngee_talent_service"
  17. "youngmini_server/app/system/assignment"
  18. "youngmini_server/app/system/sectask"
  19. "youngmini_server/app/system/wxpay"
  20. "youngmini_server/middleware"
  21. )
  22. // MiddlewareCORS 允许跨域请求中间件 所有的路由都会经过这个中间件
  23. func MiddlewareCORS(r *ghttp.Request) {
  24. corsOptions := r.Response.DefaultCORSOptions()
  25. corsOptions.AllowHeaders = "Authorization,Content-Length,X-CSRF-Token,Token,session,X_Requested_With,Accept,Origin,Host,Connection,Accept-Encoding,Accept-Language,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Pragma"
  26. corsOptions.ExposeHeaders = "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Language,Expires,Last-Modified,Pragma,FooBar"
  27. corsOptions.MaxAge = 1728000
  28. //corsOptions := ghttp.CORSOptions{
  29. //AllowOrigin: "*",
  30. //AllowMethods: "POST,GET,OPTIONS,PUT,DELETE,UPDATE",
  31. //AllowCredentials: "false",
  32. //MaxAge: 1728000,
  33. //AllowHeaders: "Authorization,Content-Length,X-CSRF-Token,Token,session,X_Requested_With,Accept,Origin,Host,Connection,Accept-Encoding,Accept-Language,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Pragma",
  34. //ExposeHeaders: "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Language,Expires,Last-Modified,Pragma,FooBar",
  35. //}
  36. //corsOptions.AllowDomain = []string{"goframe.org", "johng.cn"}
  37. //corsOptions.AllowHeaders = "Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,X-Forwarded-*,Pragma,Cache-Control,If-Modified-Since,userToken,appid"
  38. r.Response.CORS(corsOptions)
  39. r.Middleware.Next()
  40. }
  41. // MiddlewareAuth 用户认证中间件
  42. //
  43. // func MiddlewareAuth(r *ghttp.Request) {
  44. // //排除路径
  45. // array := garray.NewFrom(g.Slice{"/admin/account"})
  46. // if array.Contains(r.RequestURI) == false {
  47. // userData, err := backstage_service.Token.AuthorizationGetUserData(r)
  48. // if err != nil {
  49. // r.Response.WriteStatus(http.StatusForbidden)
  50. // response.JsonExit(r, http.StatusForbidden, err.Error())
  51. // }
  52. // if userData == nil {
  53. // r.Response.WriteStatus(http.StatusUnauthorized)
  54. // response.JsonExit(r, http.StatusForbidden, "用户不存在")
  55. // }
  56. // }
  57. // // 中间件处理逻辑
  58. // r.Middleware.Next()
  59. // }
  60. //
  61. // 用于存数据库的验证信息
  62. // json用于序列化和反序列化
  63. // MiddlewareSuperAuth 超级管理员可以操作的登录接口
  64. //
  65. // func MiddlewareSuperAuth(r *ghttp.Request) {
  66. // // 排除路径
  67. // userData, _ := backstage_service.Token.AuthorizationGetUserData(r)
  68. // if userData.User != "10000000" {
  69. // r.Response.WriteStatus(http.StatusPaymentRequired)
  70. // response.JsonExit(r, http.StatusPaymentRequired, "没有权限操作")
  71. // }
  72. // // 中间件处理逻辑
  73. // r.Middleware.Next()
  74. // }
  75. func init() {
  76. s := g.Server()
  77. // 解决跨域
  78. s.BindMiddleware("/*", MiddlewareCORS)
  79. // v2小程序端接口
  80. s.Group("/youngee/c", func(group *ghttp.RouterGroup) {
  81. group.Middleware(middleware.ErrorHandler)
  82. //用于接口测试
  83. s.BindHandler("/apitest", func(r *ghttp.Request) {
  84. r.Response.WriteJson("成功访问服务端")
  85. })
  86. //扫码之后---用于快手电商:nignx转发含code的请求到此处
  87. s.BindHandler("/kuaishouauth", func(r *ghttp.Request) {
  88. fmt.Println("****进入rounter中的/kuaishouauth*******")
  89. ClientKey := "ks651333097154138217"
  90. ClientSecret := "dBt0rVRhTpUqcrOYGGpv0A"
  91. code := r.GetString("code")
  92. state := r.GetString("state")
  93. //来自管理后台的用户,state是手机号码
  94. if len(state) == 11 {
  95. r.Response.WriteJson("进入商家端快手授权")
  96. //发起请求,将数据存在record中
  97. m_res_auth, _ := oauth.GetAccessToken(ClientKey, ClientSecret, code)
  98. r.Response.WriteJson("m_res_auth")
  99. r.Response.WriteJson(m_res_auth)
  100. AccessToken := m_res_auth.AccessToken
  101. //获取基本信息
  102. m_res_info, _ := user.GetUserinfo(ClientKey, AccessToken)
  103. r.Response.WriteJson("m_res_info")
  104. r.Response.WriteJson(m_res_info)
  105. //存在数据则更新
  106. _, err := g.DB().Model("youngee_m_kuaishou_userinfo").
  107. Where("phone_number = ?", state).
  108. Data(g.Map{
  109. "access_token": AccessToken,
  110. "nickname": m_res_info.Data.Name,
  111. "code": code,
  112. "refresh_token": m_res_auth.RefreshToken,
  113. "open_id": m_res_auth.OpenId,
  114. "create_time": gtime.Now(),
  115. "update_time": gtime.Now(),
  116. "expired": 0,
  117. "is_delete": 0,
  118. "phone_number": state,
  119. }).
  120. Save() // 如果存在则更新,不存在则插入
  121. if err != nil {
  122. r.Response.WriteJson("youngee_m_kuaishou_userinfo save failed")
  123. }
  124. return
  125. }
  126. //来自达人授权,获取accesstoken
  127. res_auth, _ := oauth.GetAccessToken(ClientKey, ClientSecret, code)
  128. r.Response.WriteJson("后端:快手电商:输出用户授权信息")
  129. r.Response.WriteJson(res_auth)
  130. //防止一个快手账号重复绑定
  131. userInfo := youngee_talent_model.KuaishouUserInfo{}
  132. //这个openid存在(如果对应到两条数据,只保留一条) 且对应的达人不是我,
  133. err := g.DB().Model("platform_kuaishou_user_info").Where("open_id = ? ", res_auth.OpenId).Order("platform_id DESC").Scan(&userInfo)
  134. if err != nil {
  135. r.Response.WriteJson(err)
  136. fmt.Println("查询数据库失败:", err)
  137. }
  138. //快手电商账号重复绑定,提示前端
  139. //此openId在表中有对应数据,且对应的达人不是当前达人
  140. if userInfo.TalentId != "" && userInfo.TalentId != state {
  141. redisKsBindStatusKey := fmt.Sprintf("Bind:%s", state)
  142. //redis设置绑定状态为
  143. _, err := g.Redis().Do("SETEX", redisKsBindStatusKey, 10, "bound_to_other")
  144. if err != nil {
  145. fmt.Println("redis出错")
  146. fmt.Println("err---->", err.Error())
  147. }
  148. return
  149. }
  150. //如果该快手账号(openID)已经有数据了,更新数据。没有数据则插入数据。
  151. _, err = g.DB().Model("platform_kuaishou_user_info").
  152. Where("open_id = ? AND platform_id = ?", res_auth.OpenId, 4).
  153. Delete()
  154. if err != nil {
  155. r.Response.WriteJson("platform_kuaishou_user_info delete failed")
  156. }
  157. AccessToken := res_auth.AccessToken
  158. //获取基本信息
  159. res_info, err := user.GetUserinfo(ClientKey, AccessToken)
  160. r.Response.WriteJson("输出用户基本信息")
  161. r.Response.WriteJson(res_info)
  162. //30天销量不在扫码时获取。
  163. err_auth := r.Response.WriteJson(res_auth)
  164. err_info := r.Response.WriteJson(res_info)
  165. if err_auth != nil {
  166. panic("write auth_response error")
  167. }
  168. if err_info != nil {
  169. panic("write auth_response error")
  170. }
  171. if res_auth.Result != 1 {
  172. panic("授权结果出错了")
  173. }
  174. if res_info.Result != 1 {
  175. panic("获取用户信息出错了")
  176. }
  177. //auth中含有最终信息
  178. authInfo := &youngee_talent_model.KuaishouUserInfo{
  179. Code: code,
  180. TalentId: state,
  181. AccessToken: AccessToken,
  182. OpenId: res_auth.OpenId,
  183. PlatformId: 4, //快手电商
  184. RefreshToken: res_auth.RefreshToken,
  185. HeadUri: res_info.Data.Head,
  186. NickName: res_info.Data.Name,
  187. Fan: res_info.Data.Fan,
  188. City: res_info.Data.City,
  189. Gender: res_info.Data.Sex,
  190. UpdateTime: gtime.Now(),
  191. CreateTime: gtime.Now(),
  192. }
  193. if _, err := g.DB().Model("platform_kuaishou_user_info").Save(authInfo); err != nil {
  194. r.Response.WriteJson(g.Map{
  195. "error": err.Error(),
  196. })
  197. return
  198. }
  199. })
  200. //用于快手平台:nignx转发含code的请求到此处
  201. s.BindHandler("/kuaishouVideo", func(r *ghttp.Request) {
  202. fmt.Println("****进入rounter中的/kuaishouVideo*******")
  203. ClientKey := "ks671599294546520767"
  204. ClientSecret := "8VSrp3O09nunjLMXR1uotg"
  205. //SignSecret := "bf6393dce0a2b669ee348bebb837b0da"
  206. code := r.GetString("code")
  207. state := r.GetString("state")
  208. //获取accesstoken
  209. res_auth, _ := oauth.GetAccessToken(ClientKey, ClientSecret, code)
  210. userInfo := youngee_talent_model.KuaishouUserInfo{}
  211. //这个openid存在 且对应的达人不是我
  212. err := g.DB().Model("platform_kuaishou_user_info").Where("open_id = ? ", userInfo.OpenId).Scan(&userInfo)
  213. if err != nil {
  214. fmt.Println("查询数据库失败")
  215. }
  216. //抖音账号重复绑定,提示前端
  217. //此openId在表中有对应数据,且对应的达人不是当前达人,
  218. if userInfo.TalentId != "" && userInfo.TalentId != state {
  219. redisKsBindStatusKey := fmt.Sprintf("Bind:%s", state)
  220. //redis设置绑定状态为
  221. _, err := g.Redis().Do("SETEX", 10, redisKsBindStatusKey, "bound_to_other")
  222. if err != nil {
  223. fmt.Println("redis出错")
  224. }
  225. return
  226. }
  227. //如果该快手账号(openID)已经有数据了,删除。模拟在快手刷新授权 没有数据则空操作
  228. _, err = g.DB().Model("platform_kuaishou_user_info").
  229. Where("open_id = ? AND platform_id = ?", res_auth.OpenId, 8).
  230. Delete()
  231. if err != nil {
  232. r.Response.WriteJson("platform_kuaishou_user_info delete failed")
  233. }
  234. AccessToken := res_auth.AccessToken
  235. //获取基本信息
  236. res_info, _ := user.GetUserinfo(ClientKey, AccessToken)
  237. //视频数据
  238. videoCount, err := youngee_talent_service.GetVideoCount(ClientKey, AccessToken)
  239. likeCount, err := youngee_talent_service.GetLikeCount(ClientKey, AccessToken)
  240. //用户进入主页获取,并存入数据库中
  241. err_auth := r.Response.WriteJson(res_auth)
  242. err_info := r.Response.WriteJson(res_info)
  243. if err_auth != nil {
  244. panic("write auth_response error")
  245. }
  246. if err_info != nil {
  247. panic("write auth_response error")
  248. }
  249. if res_auth.Result != 1 {
  250. panic("授权结果出错了")
  251. }
  252. if res_info.Result != 1 {
  253. panic("获取用户信息出错了")
  254. }
  255. //auth中含有最终信息
  256. authInfo := &youngee_talent_model.KuaishouUserInfo{
  257. Code: code,
  258. TalentId: state,
  259. AccessToken: AccessToken,
  260. OpenId: res_auth.OpenId,
  261. PlatformId: 8, //快手平台
  262. RefreshToken: res_auth.RefreshToken,
  263. HeadUri: res_info.Data.Head,
  264. NickName: res_info.Data.Name,
  265. Fan: res_info.Data.Fan,
  266. LikeNum: likeCount, //点赞数
  267. VideoNum: videoCount.PublicCount, //作品数目
  268. UpdateTime: gtime.Now(),
  269. CreateTime: gtime.Now(),
  270. City: res_info.Data.City,
  271. Gender: res_info.Data.Sex,
  272. }
  273. if _, err := g.DB().Model("platform_kuaishou_user_info").Save(authInfo); err != nil {
  274. r.Response.WriteJson(g.Map{
  275. "error": err.Error(),
  276. })
  277. return
  278. }
  279. })
  280. //用于抖音平台:nignx转发含code的请求到此处
  281. s.BindHandler("/douyinauth", func(r *ghttp.Request) {
  282. ClientKey := "awi77xl5kpl16hmi"
  283. ClientSecret := "7ce6d2531bd4489122d89658063fd76e"
  284. code := r.GetString("code")
  285. state := r.GetString("state")
  286. //获取accesstoken
  287. res_auth, _ := douyinOauth.GetAccessToken(ClientKey, ClientSecret, code)
  288. douyinOpenId := res_auth.Data.OpenId
  289. userInfo := youngee_talent_model.KuaishouUserInfo{}
  290. //这个openid存在 且对应的达人不是我,
  291. err := g.DB().Model("platform_kuaishou_user_info").Where("open_id = ? and platform_id = ? ", douyinOpenId, 2).Scan(&userInfo)
  292. if err != nil {
  293. fmt.Println("查询数据库失败")
  294. }
  295. //抖音账号重复绑定,提示前端
  296. //此openId在表中有对应数据,且对应的达人不是当前达人,
  297. if userInfo.TalentId != "" && userInfo.TalentId != state {
  298. redisDyBindStatusKey := fmt.Sprintf("Bind:%s", state)
  299. //redis设置绑定状态为 10s过期
  300. _, err := g.Redis().Do("SETEX", 10, redisDyBindStatusKey, "bound_to_other")
  301. if err != nil {
  302. fmt.Println("redis出错")
  303. }
  304. return
  305. }
  306. //如果达人已经有抖音数据了,删除。模拟在抖音刷新授权 没有数据则空操作
  307. _, err = g.DB().Model("platform_kuaishou_user_info").
  308. Where("open_id = ? AND platform_id = ? AND talent_id = ?", douyinOpenId, 2, state).
  309. Delete()
  310. if err != nil {
  311. r.Response.WriteJson("抖音账号覆盖失败")
  312. }
  313. AccessToken := res_auth.Data.AccessToken
  314. //获取基本信息
  315. res_info, _ := douyinUser.GetUserInfo(res_auth.Data.OpenId, AccessToken)
  316. //获取用户粉丝数 千粉以上
  317. //res_fans, _ := douyinUser.GetUserFans(AccessToken, "7", douyinOpenId) //近7天,返回一个列表每天都有总粉丝数
  318. //errCode := res_fans.Data.ErrorCode
  319. //var fansNumStr string
  320. //if errCode == 0 { // 满足千粉以上
  321. // fansNumStr = res_fans.Data.ResultList[0].TotalFans
  322. //} else {
  323. // fansNumStr = "0"
  324. //}
  325. //fansNum, err := strconv.Atoi(fansNumStr)
  326. //if err != nil {
  327. // fmt.Println("Error converting string to int:", err)
  328. // // 可以在这里添加错误处理逻辑
  329. //}
  330. //获取抖音作品数目和点赞数目
  331. VideoInfo, _ := youngee_talent_service.GetDyVideoInfo(douyinOpenId, AccessToken)
  332. //用户进入主页获取,并存入数据库中
  333. err_auth := r.Response.WriteJson(res_auth)
  334. err_info := r.Response.WriteJson(res_info)
  335. if err_auth != nil {
  336. panic("write auth_response error")
  337. }
  338. if err_info != nil {
  339. panic("write auth_response error")
  340. }
  341. if res_auth.Data.ErrorCode != 0 {
  342. panic("抖音授权结果出错了")
  343. }
  344. if res_info.Data.ErrorCode != 0 {
  345. panic("抖音获取用户信息出错了")
  346. }
  347. //auth中含有最终信息
  348. authInfo := &youngee_talent_model.KuaishouUserInfo{
  349. Code: code,
  350. TalentId: state,
  351. AccessToken: AccessToken,
  352. OpenId: douyinOpenId,
  353. PlatformId: 2, //抖音平台
  354. RefreshToken: res_auth.Data.RefreshToken,
  355. HeadUri: res_info.Data.Avatar,
  356. NickName: res_info.Data.Nickname,
  357. //Fan: fansNum, //专门获取粉丝数的接口,默认为0。
  358. VideoNum: VideoInfo.VideoCount,
  359. LikeNum: VideoInfo.LikeCount,
  360. UpdateTime: gtime.Now(),
  361. CreateTime: gtime.Now(),
  362. }
  363. //sava,有数据则更新,没有数据则插入
  364. if _, err := g.DB().Model("platform_kuaishou_user_info").Save(authInfo); err != nil {
  365. r.Response.WriteJson(g.Map{
  366. "error": err.Error(),
  367. })
  368. return
  369. }
  370. })
  371. //微信支付的回调,被nginx重定向到此
  372. s.BindHandler("/WxPayCallBack", func(r *ghttp.Request) {
  373. //微信响应回来的请求头和请求体中有 是否支付成功的内容
  374. //if 支付成功
  375. //1. 构造生产者的消息
  376. //2. 发送消息给MQ的指定topic 消费者监听这个topic进行订单表、支付表、用户表的更新操作【异步 , 解耦 】
  377. //3. 返回给前端支付成功的标识
  378. //else 支付失败
  379. //响应支付失败
  380. })
  381. // 达人不需要鉴权的接口
  382. group.GET("/g", youngeetalentapi.TalentGetApi)
  383. group.POST("/p", youngeetalentapi.TalentPostApi)
  384. // 达人需要鉴权的接口
  385. group.Group("/t", func(group *ghttp.RouterGroup) {
  386. group.Middleware(middleware.DuplicateVerify, middleware.WxAuth)
  387. group.GET("/g", youngeetalentapi.TalentAuthGetApi)
  388. group.POST("/p", youngeetalentapi.TalentAuthPostApi)
  389. })
  390. })
  391. // v2小程序端接口
  392. s.Group("/youngee/c/api", func(group *ghttp.RouterGroup) {
  393. group.Middleware(middleware.ErrorHandler)
  394. //// 达人不需要鉴权的接口
  395. //group.GET("/g", youngeetalentapi.TalentGetApi)
  396. //group.POST("/p", youngeetalentapi.TalentPostApi)
  397. group.Group("/selection", func(group *ghttp.RouterGroup) {
  398. group.GET("/list", sectask.SecTask.List)
  399. })
  400. // 达人需要鉴权的接口
  401. group.Group("/t", func(group *ghttp.RouterGroup) {
  402. group.Middleware(middleware.DuplicateVerify, middleware.WxAuth)
  403. group.Group("/secTask", func(group *ghttp.RouterGroup) {
  404. group.GET("/list", sectask.SecTask.List)
  405. group.GET("/list-tab", sectask.SecTask.ListTab)
  406. group.GET("/logistics/detail", sectask.SecTask.ShowLogisticsDetail)
  407. })
  408. group.Group("/assignment", func(group *ghttp.RouterGroup) {
  409. group.GET("/list", assignment.Assignment.List)
  410. group.POST("/add", assignment.Assignment.Add)
  411. })
  412. group.Group("/wxpay", func(group *ghttp.RouterGroup) {
  413. group.POST("/pay", wxpay.WxPay.WxPay)
  414. })
  415. })
  416. })
  417. }