wechat.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/medivhzhan/weapp/v2"
  6. "hongze/hongze_mfyx/models"
  7. "hongze/hongze_mfyx/models/order"
  8. "hongze/hongze_mfyx/services"
  9. "hongze/hongze_mfyx/utils"
  10. "strconv"
  11. "time"
  12. )
  13. type WechatController struct {
  14. BaseAuthController
  15. }
  16. type WechatCommonController struct {
  17. BaseCommonController
  18. }
  19. // @Title 微信登录接口
  20. // @Description 微信登录接口
  21. // @Param Code query string true "微信唯一编码code"
  22. // @Success 200 {object} models.WxLoginResp
  23. // @router /login [get]
  24. func (this *WechatCommonController) WechatLogin() {
  25. br := new(models.BaseResponse).Init()
  26. defer func() {
  27. this.Data["json"] = br
  28. this.ServeJSON()
  29. }()
  30. code := this.GetString("Code")
  31. if code == "" {
  32. br.Msg = "参数错误"
  33. br.ErrMsg = "Code 为空"
  34. return
  35. }
  36. wxInfo, err := weapp.Login(utils.WxAppId, utils.WxAppSecret, code)
  37. if err != nil {
  38. br.Msg = "获取用户信息失败"
  39. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  40. return
  41. }
  42. if err = wxInfo.GetResponseError(); err != nil {
  43. br.Msg = "获取用户信息失败"
  44. br.ErrMsg = "获取用户信息失败,code:" + strconv.Itoa(wxInfo.ErrCode) + ",msg:" + wxInfo.ErrMSG
  45. return
  46. }
  47. wxUserInfo := new(services.WxUserInfo)
  48. wxUserInfo.Unionid = wxInfo.UnionID
  49. wxUserInfo.Openid = wxInfo.OpenID
  50. wxUserInfo.Errcode = wxInfo.ErrCode
  51. wxUserInfo.Errmsg = wxInfo.ErrMSG
  52. wxUserInfo.SessionKey = wxInfo.SessionKey
  53. token, userId, firstLogin, _, err := services.WxLogin(code, wxInfo.OpenID, wxInfo.UnionID, wxUserInfo)
  54. if err != nil && err.Error() != utils.ErrNoRow() {
  55. br.Msg = "微信登录失败"
  56. br.ErrMsg = "微信登录失败,err:" + err.Error()
  57. return
  58. }
  59. if token == "" {
  60. br.Msg = "微信登录失败"
  61. br.ErrMsg = "token:" + token + "" + code + " " + wxInfo.OpenID + " " + wxInfo.UnionID
  62. return
  63. }
  64. //新增登录日志
  65. {
  66. loginLog := new(models.WxUserLog)
  67. loginLog.UserId = userId
  68. loginLog.OpenId = wxInfo.OpenID
  69. loginLog.UnionId = wxInfo.UnionID
  70. loginLog.CreateTime = time.Now()
  71. loginLog.Handle = "wechat_login_mfyx"
  72. loginLog.Remark = token
  73. go models.AddWxUserLog(loginLog)
  74. }
  75. {
  76. codeLog := new(models.WxUserCode)
  77. codeLog.WxCode = code
  78. codeLog.UserId = userId
  79. codeLog.Code = 0
  80. codeLog.FirstLogin = firstLogin
  81. codeLog.Authorization = token
  82. codeLog.UserPermission = 1
  83. codeLog.CreateTime = time.Now()
  84. models.AddWxUserCode(codeLog)
  85. }
  86. resp := new(models.WxLoginResp)
  87. resp.UserId = userId
  88. resp.FirstLogin = firstLogin
  89. resp.Authorization = token
  90. br.Ret = 200
  91. br.Success = true
  92. br.Msg = "登录成功"
  93. br.Data = resp
  94. }
  95. // @Title 小程序获取用户信息
  96. // @Description 小程序获取用户信息接口(需要登录)
  97. // @Param request body models.WxGetUserInfoReq true "type json string"
  98. // @Success 200 {object} models.WxGetUserInfoResp
  99. // @router /getUserInfo [post]
  100. func (this *WechatController) GetUserInfo() {
  101. br := new(models.BaseResponse).Init()
  102. defer func() {
  103. this.Data["json"] = br
  104. this.ServeJSON()
  105. }()
  106. var req models.WxGetUserInfoReq
  107. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  108. if err != nil {
  109. br.Msg = "参数解析异常!"
  110. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  111. return
  112. }
  113. if req.RawData == "" || req.EncryptedData == "" || req.Signature == "" || req.Iv == "" {
  114. br.Msg = "参数错误"
  115. return
  116. }
  117. user := this.User
  118. if user == nil {
  119. br.Msg = "请登陆"
  120. br.Ret = 408
  121. return
  122. }
  123. userId := user.UserId
  124. sessionKey := user.SessionKey
  125. fmt.Println("sessionKey:", sessionKey)
  126. fmt.Println(sessionKey, req.RawData, req.EncryptedData, req.Signature, req.Iv)
  127. userInfo, err := weapp.DecryptUserInfo(sessionKey, req.RawData, req.EncryptedData, req.Signature, req.Iv)
  128. fmt.Println("weapp.DecryptUserInfo ", err)
  129. if err != nil {
  130. br.Msg = "解析用户信息失败"
  131. br.ErrMsg = "解析用户信息失败,DecryptUserInfo Err:" + err.Error()
  132. return
  133. }
  134. //修改用户微信信息
  135. err = models.ModifyUserRecordByDetail(userInfo.OpenID, userInfo.UnionID, userInfo.Nickname, userInfo.Avatar, userInfo.City, userInfo.Province, userInfo.Country, userInfo.Gender, userId)
  136. if err != nil {
  137. br.Msg = "授权失败"
  138. br.ErrMsg = "授权失败,修改用户信息失败:" + err.Error()
  139. return
  140. }
  141. var token string
  142. tokenItem, err := models.GetTokenByOpenId(userInfo.OpenID)
  143. if err != nil && err.Error() != utils.ErrNoRow() {
  144. br.Msg = "授权失败"
  145. br.ErrMsg = "授权失败,获取token失败:" + err.Error()
  146. return
  147. }
  148. if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  149. timeUnix := time.Now().Unix()
  150. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  151. token = utils.MD5(userInfo.OpenID) + utils.MD5(timeUnixStr)
  152. //新增session
  153. {
  154. session := new(models.CygxSession)
  155. session.OpenId = userInfo.OpenID
  156. session.UnionId = userInfo.UnionID
  157. session.UserId = userId
  158. session.CreatedTime = time.Now()
  159. session.LastUpdatedTime = time.Now()
  160. session.ExpireTime = time.Now().AddDate(0, 3, 0)
  161. session.AccessToken = token
  162. err = models.AddSession(session)
  163. if err != nil {
  164. br.Msg = "授权失败"
  165. br.ErrMsg = "授权失败,新增用户session信息失败:" + err.Error()
  166. return
  167. }
  168. }
  169. } else {
  170. token = tokenItem.AccessToken
  171. }
  172. resp := new(models.WxGetUserInfoResp)
  173. resp.Authorization = token
  174. br.Msg = "获取成功!"
  175. br.Ret = 200
  176. br.Success = true
  177. }
  178. // @Title 小程序获取用户绑定手机号
  179. // @Description 小程序获取用户绑定手机号接口(需要登录)
  180. // @Param request body models.WxGetPhoneNumberReq true "type json string"
  181. // @Success 200 {object} models.WxGetPhoneNumberResp
  182. // @router /getPhoneNumber [post]
  183. func (this *WechatController) GetPhoneNumber() {
  184. br := new(models.BaseResponse).Init()
  185. defer func() {
  186. this.Data["json"] = br
  187. this.ServeJSON()
  188. }()
  189. var req models.WxGetPhoneNumberReq
  190. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  191. if err != nil {
  192. br.Msg = "参数解析异常!"
  193. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  194. return
  195. }
  196. if req.EncryptedData == "" || req.Iv == "" {
  197. br.Msg = "参数错误"
  198. return
  199. }
  200. user := this.User
  201. if user == nil {
  202. br.Msg = "请登陆"
  203. br.Ret = 408
  204. return
  205. }
  206. sessionKey := user.SessionKey
  207. wxMobile, err := weapp.DecryptMobile(sessionKey, req.EncryptedData, req.Iv)
  208. if err != nil {
  209. br.Msg = "解析用户手机号信息失败"
  210. br.ErrMsg = "解析用户手机号信息失败,Err:" + err.Error()
  211. return
  212. }
  213. err = models.ModifyUsersMobile(user.UserId, wxMobile.PurePhoneNumber)
  214. if err != nil {
  215. br.Msg = "获取失败"
  216. br.ErrMsg = "获取失败,Err:" + err.Error()
  217. return
  218. }
  219. resp := new(models.WxGetPhoneNumberResp)
  220. resp.PhoneNumber = wxMobile.PhoneNumber
  221. resp.PurePhoneNumber = wxMobile.PurePhoneNumber
  222. resp.CountryCode = wxMobile.CountryCode
  223. br.Msg = "获取成功!"
  224. br.Ret = 200
  225. br.Success = true
  226. br.Data = resp
  227. }
  228. // @Title 获取短信验证码
  229. // @Description 获取短信验证码接口
  230. // @Param Mobile query string true "手机号码"
  231. // @Param AreaNum query string true "地区编码"
  232. // @Success Ret=200 获取成功
  233. // @router /getSmsCode [get]
  234. func (this *WechatController) GetSmsCode() {
  235. br := new(models.BaseResponse).Init()
  236. defer func() {
  237. this.Data["json"] = br
  238. this.ServeJSON()
  239. }()
  240. mobile := this.GetString("Mobile")
  241. if mobile == "" {
  242. br.Msg = "请输入手机号"
  243. return
  244. }
  245. areaNum := this.GetString("AreaNum")
  246. msgCode := utils.GetRandDigit(4)
  247. var result bool
  248. if areaNum == "86" || areaNum == "" || areaNum == "0" {
  249. result = services.SendSmsCode(mobile, msgCode)
  250. } else {
  251. result = services.SendSmsCodeGj(mobile, msgCode, areaNum)
  252. }
  253. //发送成功
  254. if result {
  255. item := new(models.MsgCode)
  256. item.OpenId = ""
  257. item.Code = msgCode
  258. item.Mobile = mobile
  259. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  260. item.Enabled = 1
  261. item.CreatedTime = time.Now()
  262. err := models.AddMsgCode(item)
  263. if err != nil {
  264. br.Msg = "发送失败"
  265. br.ErrMsg = "发送失败,Err:" + err.Error()
  266. return
  267. }
  268. br.Msg = "发送成功"
  269. } else {
  270. br.Msg = "发送失败"
  271. }
  272. br.Ret = 200
  273. br.Success = true
  274. }
  275. // @Title 获取邮件验证码
  276. // @Description 获取邮件验证码接口
  277. // @Param Email query string true "邮箱"
  278. // @Success Ret=200 获取成功
  279. // @router /getEmailCode [get]
  280. func (this *WechatController) GetEmailCode() {
  281. br := new(models.BaseResponse).Init()
  282. defer func() {
  283. this.Data["json"] = br
  284. this.ServeJSON()
  285. }()
  286. email := this.GetString("Email")
  287. if email == "" {
  288. br.Msg = "请输入邮箱地址"
  289. return
  290. }
  291. if !utils.ValidateEmailFormatat(email) {
  292. br.Msg = "邮箱格式错误,请重新输入"
  293. return
  294. }
  295. msgCode := utils.GetRandDigit(4)
  296. content := "尊敬的用户:</br>您好,感谢您使用买方研选,您正在进行邮箱验证,本次请求的验证码为:" + msgCode + "(为了保障您账号的安全性,请在15分钟内完成验证。)</br>买方研选团队 </br>2019年05月11日"
  297. title := "买方研选登陆验证"
  298. //发送邮件
  299. result, err := utils.SendEmailByHz(title, content, email)
  300. if err != nil {
  301. br.Msg = "发送失败"
  302. br.ErrMsg = "发送失败,Err:" + err.Error()
  303. return
  304. }
  305. if result {
  306. item := new(models.MsgCode)
  307. item.OpenId = ""
  308. item.Code = msgCode
  309. item.Mobile = email
  310. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  311. item.Enabled = 1
  312. item.CreatedTime = time.Now()
  313. err := models.AddMsgCode(item)
  314. if err != nil {
  315. br.Msg = "发送失败"
  316. br.ErrMsg = "发送失败,Err:" + err.Error()
  317. return
  318. }
  319. br.Msg = "发送成功"
  320. } else {
  321. br.Msg = "发送失败"
  322. }
  323. br.Ret = 200
  324. br.Success = true
  325. }
  326. // @Title 获取短信验证码(无需token)
  327. // @Description 获取短信验证码接口(无需token)
  328. // @Param Mobile query string true "手机号码"
  329. // @Param AreaNum query string true "地区编码"
  330. // @Success Ret=200 获取成功
  331. // @router /getSmsCodePublic [get]
  332. func (this *WechatCommonController) GetSmsCode() {
  333. br := new(models.BaseResponse).Init()
  334. defer func() {
  335. this.Data["json"] = br
  336. this.ServeJSON()
  337. }()
  338. mobile := this.GetString("Mobile")
  339. if mobile == "" {
  340. br.Msg = "请输入手机号"
  341. return
  342. }
  343. areaNum := this.GetString("AreaNum")
  344. msgCode := utils.GetRandDigit(4)
  345. var result bool
  346. if areaNum == "86" || areaNum == "" || areaNum == "0" {
  347. result = services.SendSmsCode(mobile, msgCode)
  348. } else {
  349. result = services.SendSmsCodeGj(mobile, msgCode, areaNum)
  350. }
  351. //发送成功
  352. if result {
  353. item := new(models.MsgCode)
  354. item.OpenId = ""
  355. item.Code = msgCode
  356. item.Mobile = mobile
  357. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  358. item.Enabled = 1
  359. item.CreatedTime = time.Now()
  360. err := models.AddMsgCode(item)
  361. if err != nil {
  362. br.Msg = "发送失败"
  363. br.ErrMsg = "发送失败,Err:" + err.Error()
  364. return
  365. }
  366. br.Msg = "发送成功"
  367. } else {
  368. br.Msg = "发送失败"
  369. }
  370. br.Ret = 200
  371. br.Success = true
  372. }
  373. // @Title 微信获取用户绑定的手机号
  374. // @Description 微信获取用户绑定的手机号接口
  375. // @Param Code query string true "微信唯一编码code"
  376. // @Param InviteShareCode query string false "销售账号邀请码"
  377. // @Success 200 {object} models.WxLoginResp
  378. // @router /getuserphonenumber [get]
  379. func (this *WechatController) Getuserphonenumber() {
  380. br := new(models.BaseResponse).Init()
  381. defer func() {
  382. this.Data["json"] = br
  383. this.ServeJSON()
  384. }()
  385. user := this.User
  386. if user == nil {
  387. br.Msg = "请登录"
  388. br.ErrMsg = "请登录"
  389. br.Ret = 408
  390. return
  391. }
  392. code := this.GetString("Code")
  393. if code == "" {
  394. br.Msg = "参数错误"
  395. br.ErrMsg = "Code 为空"
  396. return
  397. }
  398. inviteShareCode := this.GetString("InviteShareCode")
  399. wxitem, err := services.Getuserphonenumber(code)
  400. if err != nil {
  401. br.Msg = "微信登录失败"
  402. br.ErrMsg = "微信登录失败,err:" + err.Error()
  403. return
  404. }
  405. var mobile string
  406. var countryCode string
  407. openId := this.User.OpenId
  408. mobile = wxitem.PhoneInfo.PhoneNumber
  409. countryCode = wxitem.PhoneInfo.CountryCode
  410. if mobile == "" {
  411. br.Msg = "微信登录失败"
  412. br.ErrMsg = "微信登录失败,手机号为空"
  413. return
  414. }
  415. user, err = services.BindWxUser(openId, mobile, "", countryCode, inviteShareCode)
  416. if err != nil {
  417. br.Msg = "登录失败"
  418. br.ErrMsg = "绑定手机号失败:" + err.Error()
  419. return
  420. }
  421. br.Ret = 200
  422. br.Success = true
  423. br.Msg = "登录成功"
  424. //br.Data = resp
  425. }
  426. // @Title 微信付款回调接口
  427. // @Description 微信付款回调接口
  428. // @Success 200 {object} models.WxLoginResp
  429. // @router /wxpay/notify [post]
  430. func (this *WechatCommonController) WxpayNotify() {
  431. br := new(models.BaseResponse).Init()
  432. defer func() {
  433. this.Data["json"] = br
  434. this.ServeJSON()
  435. }()
  436. body := this.Ctx.Input.RequestBody
  437. resp := new(order.WechatPayNotifyUrlJson)
  438. //utils.FileLog.Info("wechat notify:" + string(body))
  439. item := new(models.CygxShanghaiCompanyLog)
  440. item.CreateTime = time.Now()
  441. //item.Body = jsonCompany
  442. item.Result = string(body)
  443. go models.AddCygxShanghaiCompanyLog(item)
  444. itemNotify := services.WxDecodeNotify(body)
  445. if itemNotify == nil {
  446. resp.Code = "FAIL"
  447. resp.Message = "失败"
  448. br.Ret = 400
  449. return
  450. }
  451. if itemNotify.OutTradeNo != "" {
  452. go services.HandleOrderByWechatPay(itemNotify)
  453. item.Url = itemNotify.OutTradeNo // 记录一下同一笔订单微信推送了几次
  454. go models.AddCygxShanghaiCompanyLog(item)
  455. }
  456. resp.Code = "SUCCESS"
  457. br.Data = resp
  458. br.Ret = 200
  459. br.Success = true
  460. }
  461. // @Title 微信退款回调接口
  462. // @Description 微信退款回调接口
  463. // @Success 200 {object} models.WxLoginResp
  464. // @router /wxpay/refunds/notify [post]
  465. func (this *WechatCommonController) WxpayRefundsNotify() {
  466. br := new(models.BaseResponse).Init()
  467. defer func() {
  468. this.Data["json"] = br
  469. this.ServeJSON()
  470. }()
  471. body := this.Ctx.Input.RequestBody
  472. resp := new(order.WechatPayNotifyUrlJson)
  473. //utils.FileLog.Info("wechat notify:" + string(body))
  474. item := new(models.CygxShanghaiCompanyLog)
  475. item.CreateTime = time.Now()
  476. //item.Body = jsonCompany
  477. item.Result = string(body)
  478. itemNotify := services.WxDecodeNotify(body)
  479. if itemNotify == nil {
  480. resp.Code = "FAIL"
  481. resp.Message = "失败"
  482. br.Ret = 400
  483. return
  484. }
  485. if itemNotify.OutTradeNo != "" {
  486. go services.HandleOrderRefundByWechatPay(itemNotify)
  487. outTradeNo := itemNotify.OutTradeNo
  488. orderDetail, err := order.GetCygxOrderDetailByOutTradeNo(outTradeNo)
  489. if err != nil {
  490. return
  491. }
  492. //修改过状态的不再二次处理
  493. if orderDetail.OrderStatus != 3 {
  494. go models.AddCygxShanghaiCompanyLog(item)
  495. }
  496. }
  497. br.Data = resp
  498. br.Ret = 200
  499. br.Success = true
  500. }