wechat.go 13 KB

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