wechat.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/medivhzhan/weapp/v2"
  6. "hongze/hongze_cygx/models"
  7. "hongze/hongze_cygx/services"
  8. "hongze/hongze_cygx/utils"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "os"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. type WechatController struct {
  18. BaseAuthController
  19. }
  20. type WechatCommonController struct {
  21. BaseCommonController
  22. }
  23. // @Title 微信登录接口
  24. // @Description 微信登录接口
  25. // @Param Code query string true "微信唯一编码code"
  26. // @Success 200 {object} models.WxLoginResp
  27. // @router /login [get]
  28. func (this *WechatCommonController) WechatLogin() {
  29. br := new(models.BaseResponse).Init()
  30. defer func() {
  31. this.Data["json"] = br
  32. this.ServeJSON()
  33. }()
  34. code := this.GetString("Code")
  35. if code == "" {
  36. br.Msg = "参数错误"
  37. br.ErrMsg = "Code 为空"
  38. return
  39. }
  40. wxInfo, err := weapp.Login(utils.WxAppId, utils.WxAppSecret, code)
  41. if err != nil {
  42. br.Msg = "获取用户信息失败"
  43. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  44. return
  45. }
  46. if err = wxInfo.GetResponseError(); err != nil {
  47. br.Msg = "获取用户信息失败"
  48. br.ErrMsg = "获取用户信息失败,code:" + strconv.Itoa(wxInfo.ErrCode) + ",msg:" + wxInfo.ErrMSG
  49. return
  50. }
  51. wxUserInfo := new(services.WxUserInfo)
  52. wxUserInfo.Unionid = wxInfo.UnionID
  53. wxUserInfo.Openid = wxInfo.OpenID
  54. wxUserInfo.Errcode = wxInfo.ErrCode
  55. wxUserInfo.Errmsg = wxInfo.ErrMSG
  56. wxUserInfo.SessionKey = wxInfo.SessionKey
  57. token, userId, firstLogin, _, err := services.WxLogin(code, wxInfo.OpenID, wxInfo.UnionID, wxUserInfo)
  58. if err != nil && err.Error() != utils.ErrNoRow() {
  59. br.Msg = "微信登录失败"
  60. br.ErrMsg = "微信登录失败,err:" + err.Error()
  61. return
  62. }
  63. if token == "" {
  64. br.Msg = "微信登录失败"
  65. br.ErrMsg = "token:" + token + "" + code + " " + wxInfo.OpenID + " " + wxInfo.UnionID
  66. return
  67. }
  68. //新增登录日志
  69. {
  70. loginLog := new(models.WxUserLog)
  71. loginLog.UserId = userId
  72. loginLog.OpenId = wxInfo.OpenID
  73. loginLog.UnionId = wxInfo.UnionID
  74. loginLog.CreateTime = time.Now()
  75. loginLog.Handle = "wechat_login_cygx"
  76. loginLog.Remark = token
  77. go models.AddWxUserLog(loginLog)
  78. }
  79. {
  80. codeLog := new(models.WxUserCode)
  81. codeLog.WxCode = code
  82. codeLog.UserId = userId
  83. codeLog.Code = 0
  84. codeLog.FirstLogin = firstLogin
  85. codeLog.Authorization = token
  86. codeLog.UserPermission = 1
  87. codeLog.CreateTime = time.Now()
  88. models.AddWxUserCode(codeLog)
  89. }
  90. resp := new(models.WxLoginResp)
  91. resp.UserId = userId
  92. resp.FirstLogin = firstLogin
  93. resp.Authorization = token
  94. br.Ret = 200
  95. br.Success = true
  96. br.Msg = "登录成功"
  97. br.Data = resp
  98. }
  99. // @Title 小程序获取用户信息
  100. // @Description 小程序获取用户信息接口(需要登录)
  101. // @Param request body models.WxGetUserInfoReq true "type json string"
  102. // @Success 200 {object} models.WxGetUserInfoResp
  103. // @router /getUserInfo [post]
  104. func (this *WechatController) GetUserInfo() {
  105. br := new(models.BaseResponse).Init()
  106. defer func() {
  107. this.Data["json"] = br
  108. this.ServeJSON()
  109. }()
  110. var req models.WxGetUserInfoReq
  111. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  112. if err != nil {
  113. br.Msg = "参数解析异常!"
  114. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  115. return
  116. }
  117. if req.RawData == "" || req.EncryptedData == "" || req.Signature == "" || req.Iv == "" {
  118. br.Msg = "参数错误"
  119. return
  120. }
  121. user := this.User
  122. if user == nil {
  123. br.Msg = "请登陆"
  124. br.Ret = 408
  125. return
  126. }
  127. userId := user.UserId
  128. sessionKey := user.SessionKey
  129. fmt.Println("sessionKey:", sessionKey)
  130. fmt.Println(sessionKey, req.RawData, req.EncryptedData, req.Signature, req.Iv)
  131. userInfo, err := weapp.DecryptUserInfo(sessionKey, req.RawData, req.EncryptedData, req.Signature, req.Iv)
  132. fmt.Println("weapp.DecryptUserInfo ", err)
  133. if err != nil {
  134. br.Msg = "解析用户信息失败"
  135. br.ErrMsg = "解析用户信息失败,DecryptUserInfo Err:" + err.Error()
  136. return
  137. }
  138. //修改用户微信信息
  139. err = models.ModifyUserRecordByDetail(userInfo.OpenID, userInfo.UnionID, userInfo.Nickname, userInfo.Avatar, userInfo.City, userInfo.Province, userInfo.Country, userInfo.Gender, userId)
  140. if err != nil {
  141. br.Msg = "授权失败"
  142. br.ErrMsg = "授权失败,修改用户信息失败:" + err.Error()
  143. return
  144. }
  145. var token string
  146. tokenItem, err := models.GetTokenByOpenId(userInfo.OpenID)
  147. if err != nil && err.Error() != utils.ErrNoRow() {
  148. br.Msg = "授权失败"
  149. br.ErrMsg = "授权失败,获取token失败:" + err.Error()
  150. return
  151. }
  152. if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  153. timeUnix := time.Now().Unix()
  154. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  155. token = utils.MD5(userInfo.OpenID) + utils.MD5(timeUnixStr)
  156. //新增session
  157. {
  158. session := new(models.CygxSession)
  159. session.OpenId = userInfo.OpenID
  160. session.UnionId = userInfo.UnionID
  161. session.UserId = userId
  162. session.CreatedTime = time.Now()
  163. session.LastUpdatedTime = time.Now()
  164. session.ExpireTime = time.Now().AddDate(0, 3, 0)
  165. session.AccessToken = token
  166. err = models.AddSession(session)
  167. if err != nil {
  168. br.Msg = "授权失败"
  169. br.ErrMsg = "授权失败,新增用户session信息失败:" + err.Error()
  170. return
  171. }
  172. }
  173. } else {
  174. token = tokenItem.AccessToken
  175. }
  176. resp := new(models.WxGetUserInfoResp)
  177. resp.Authorization = token
  178. br.Msg = "获取成功!"
  179. br.Ret = 200
  180. br.Success = true
  181. }
  182. // @Title 小程序获取用户绑定手机号
  183. // @Description 小程序获取用户绑定手机号接口(需要登录)
  184. // @Param request body models.WxGetPhoneNumberReq true "type json string"
  185. // @Success 200 {object} models.WxGetPhoneNumberResp
  186. // @router /getPhoneNumber [post]
  187. func (this *WechatController) GetPhoneNumber() {
  188. br := new(models.BaseResponse).Init()
  189. defer func() {
  190. this.Data["json"] = br
  191. this.ServeJSON()
  192. }()
  193. var req models.WxGetPhoneNumberReq
  194. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  195. if err != nil {
  196. br.Msg = "参数解析异常!"
  197. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  198. return
  199. }
  200. if req.EncryptedData == "" || req.Iv == "" {
  201. br.Msg = "参数错误"
  202. return
  203. }
  204. user := this.User
  205. if user == nil {
  206. br.Msg = "请登陆"
  207. br.Ret = 408
  208. return
  209. }
  210. sessionKey := user.SessionKey
  211. wxMobile, err := weapp.DecryptMobile(sessionKey, req.EncryptedData, req.Iv)
  212. if err != nil {
  213. br.Msg = "解析用户手机号信息失败"
  214. br.ErrMsg = "解析用户手机号信息失败,Err:" + err.Error()
  215. return
  216. }
  217. err = models.ModifyUsersMobile(user.UserId, wxMobile.PurePhoneNumber)
  218. if err != nil {
  219. br.Msg = "获取失败"
  220. br.ErrMsg = "获取失败,Err:" + err.Error()
  221. return
  222. }
  223. resp := new(models.WxGetPhoneNumberResp)
  224. resp.PhoneNumber = wxMobile.PhoneNumber
  225. resp.PurePhoneNumber = wxMobile.PurePhoneNumber
  226. resp.CountryCode = wxMobile.CountryCode
  227. br.Msg = "获取成功!"
  228. br.Ret = 200
  229. br.Success = true
  230. br.Data = resp
  231. }
  232. // @Title 获取短信验证码
  233. // @Description 获取短信验证码接口
  234. // @Param Mobile query string true "手机号码"
  235. // @Param AreaNum query string true "地区编码"
  236. // @Success Ret=200 获取成功
  237. // @router /getSmsCode [get]
  238. func (this *WechatController) GetSmsCode() {
  239. br := new(models.BaseResponse).Init()
  240. defer func() {
  241. this.Data["json"] = br
  242. this.ServeJSON()
  243. }()
  244. mobile := this.GetString("Mobile")
  245. if mobile == "" {
  246. br.Msg = "请输入手机号"
  247. return
  248. }
  249. areaNum := this.GetString("AreaNum")
  250. msgCode := utils.GetRandDigit(4)
  251. var result bool
  252. if areaNum == "86" || areaNum == "" || areaNum == "0" {
  253. result = services.SendSmsCode(mobile, msgCode)
  254. } else {
  255. result = services.SendSmsCodeGj(mobile, msgCode, areaNum)
  256. }
  257. //发送成功
  258. if result {
  259. item := new(models.MsgCode)
  260. item.OpenId = ""
  261. item.Code = msgCode
  262. item.Mobile = mobile
  263. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  264. item.Enabled = 1
  265. item.CreatedTime = time.Now()
  266. err := models.AddMsgCode(item)
  267. if err != nil {
  268. br.Msg = "发送失败"
  269. br.ErrMsg = "发送失败,Err:" + err.Error()
  270. return
  271. }
  272. br.Msg = "发送成功"
  273. } else {
  274. br.Msg = "发送失败"
  275. }
  276. br.Ret = 200
  277. br.Success = true
  278. }
  279. // @Title 获取邮件验证码
  280. // @Description 获取邮件验证码接口
  281. // @Param Email query string true "邮箱"
  282. // @Success Ret=200 获取成功
  283. // @router /getEmailCode [get]
  284. func (this *WechatController) GetEmailCode() {
  285. br := new(models.BaseResponse).Init()
  286. defer func() {
  287. this.Data["json"] = br
  288. this.ServeJSON()
  289. }()
  290. email := this.GetString("Email")
  291. if email == "" {
  292. br.Msg = "请输入邮箱地址"
  293. return
  294. }
  295. if !utils.ValidateEmailFormatat(email) {
  296. br.Msg = "邮箱格式错误,请重新输入"
  297. return
  298. }
  299. msgCode := utils.GetRandDigit(4)
  300. content := "尊敬的用户:</br>您好,感谢您使用弘则研究,您正在进行邮箱验证,本次请求的验证码为:" + msgCode + "(为了保障您账号的安全性,请在15分钟内完成验证。)</br>弘则研究团队 </br>2019年05月11日"
  301. title := "弘则研究登陆验证"
  302. //发送邮件
  303. result, err := utils.SendEmailByHz(title, content, email)
  304. if err != nil {
  305. br.Msg = "发送失败"
  306. br.ErrMsg = "发送失败,Err:" + err.Error()
  307. return
  308. }
  309. if result {
  310. item := new(models.MsgCode)
  311. item.OpenId = ""
  312. item.Code = msgCode
  313. item.Mobile = email
  314. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  315. item.Enabled = 1
  316. item.CreatedTime = time.Now()
  317. err := models.AddMsgCode(item)
  318. if err != nil {
  319. br.Msg = "发送失败"
  320. br.ErrMsg = "发送失败,Err:" + err.Error()
  321. return
  322. }
  323. br.Msg = "发送成功"
  324. } else {
  325. br.Msg = "发送失败"
  326. }
  327. br.Ret = 200
  328. br.Success = true
  329. }
  330. // @Title 更新微信token
  331. // @Description 更新微信token
  332. // @Success Ret=200 更新成功
  333. // @router /updateWxAccesstoken [get]
  334. func (this *WechatController) UpdateWxAccesstoken() {
  335. br := new(models.BaseResponse).Init()
  336. defer func() {
  337. this.Data["json"] = br
  338. this.ServeJSON()
  339. }()
  340. accessToken, err := models.GetWxAccessToken()
  341. if err != nil {
  342. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  343. return
  344. }
  345. br.Data = accessToken
  346. br.Ret = 200
  347. br.Success = true
  348. }
  349. // @Title 微信登录小助手接口
  350. // @Description 微信登录小助手接口
  351. // @Param Code query string true "微信唯一编码code"
  352. // @Success 200 {object} models.WxLoginResp
  353. // @router /loginByxzs [get]
  354. func (this *WechatCommonController) WechatLoginByxzs() {
  355. br := new(models.BaseResponse).Init()
  356. defer func() {
  357. this.Data["json"] = br
  358. this.ServeJSON()
  359. }()
  360. code := this.GetString("Code")
  361. if code == "" {
  362. br.Msg = "参数错误"
  363. br.ErrMsg = "Code 为空"
  364. return
  365. }
  366. item, err := services.WxGetUserOpenIdByCodeXzs(code)
  367. if err != nil {
  368. br.Msg = "获取用户信息失败"
  369. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  370. return
  371. }
  372. if item.Errcode != 0 {
  373. br.Msg = "获取用户信息失败"
  374. br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
  375. return
  376. }
  377. openId := item.Openid
  378. if openId == "" {
  379. br.Msg = "获取用户信息失败"
  380. br.ErrMsg = "获取openid失败,openid:" + item.Openid
  381. return
  382. }
  383. unionId := item.Unionid
  384. if unionId == "" {
  385. br.Msg = "获取用户信息失败"
  386. br.ErrMsg = "获取unionid失败,unionid:" + item.Openid
  387. return
  388. }
  389. total, err := models.GetCygxUserRecordCount(openId)
  390. if err != nil {
  391. br.Msg = "获取用户信息失败"
  392. br.ErrMsg = "查询数量失败,Err:" + err.Error()
  393. return
  394. }
  395. if total == 0 {
  396. items := new(models.CygxUserRecord)
  397. items.OpenId = openId
  398. items.UnionId = unionId
  399. items.CreateTime = time.Now()
  400. _, err = models.AddCygxUserRecord(items)
  401. if err != nil {
  402. br.Msg = "获取用户信息失败"
  403. br.ErrMsg = "添加openid失败,Err:" + err.Error()
  404. return
  405. }
  406. }
  407. br.Ret = 200
  408. br.Success = true
  409. br.Msg = "获取成功"
  410. br.Data = item
  411. }
  412. // @Title 获取小程序分享二维码
  413. // @Description 获取小程序分享二维码
  414. // @Success 200 {object} models.ArticleDetailFileLink
  415. // @router /shareImage [post]
  416. func (this *WechatController) ShareImage() {
  417. br := new(models.BaseResponse).Init()
  418. defer func() {
  419. this.Data["json"] = br
  420. this.ServeJSON()
  421. }()
  422. user := this.User
  423. if user == nil {
  424. br.Msg = "请登录"
  425. br.ErrMsg = "请登录,用户信息为空"
  426. br.Ret = 408
  427. return
  428. }
  429. uid := user.UserId
  430. itemToken, err := services.WxGetToken()
  431. if err != nil {
  432. br.Msg = "分享失败"
  433. br.ErrMsg = "获取itemToken失败,Err:" + err.Error()
  434. return
  435. }
  436. if itemToken.AccessToken == "" {
  437. br.Msg = "accessToken is empty"
  438. return
  439. }
  440. var envVersion string
  441. var resourceUrl string
  442. if utils.RunMode == "release" {
  443. envVersion = "release"
  444. } else {
  445. envVersion = "develop"
  446. }
  447. url := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + itemToken.AccessToken
  448. method := "POST"
  449. payload := strings.NewReader(`{
  450. "page":"pageMy/excessivePages/excessivePages",
  451. "scene":"` + strconv.Itoa(uid) + `",
  452. "env_version":"` + envVersion + `",
  453. "check_path":false,
  454. "auto_color":true
  455. }`)
  456. client := &http.Client{}
  457. req, err := http.NewRequest(method, url, payload)
  458. if err != nil {
  459. br.Msg = "分享失败"
  460. br.ErrMsg = "获取微信二维码失败,Err:" + err.Error()
  461. return
  462. }
  463. req.Header.Add("Content-Type", "application/json")
  464. postBody, err := client.Do(req)
  465. if err != nil {
  466. br.Msg = "分享失败"
  467. br.ErrMsg = "获取微信二维码失败,Err:" + err.Error()
  468. return
  469. }
  470. defer postBody.Body.Close()
  471. uploadDir := "static/img/share/"
  472. uuid := utils.GetRandStringNoSpecialChar(28)
  473. if !utils.FileIsExist(uploadDir) {
  474. err = os.MkdirAll(uploadDir, 0755)
  475. if err != nil {
  476. br.Msg = "分享失败"
  477. br.ErrMsg = "生成文件夹失败,Err:" + err.Error()
  478. return
  479. }
  480. }
  481. imagePath := uploadDir + uuid + ".jpg"
  482. switch header := postBody.Header.Get("Content-Type"); {
  483. case strings.HasPrefix(header, "application/json"):
  484. tokenResp := models.ReturnBodyRule{}
  485. decoder := json.NewDecoder(postBody.Body)
  486. if decodeErr := decoder.Decode(&tokenResp); decodeErr != nil {
  487. br.Msg = "分享失败"
  488. br.ErrMsg = "获取微信二维码失败,Err:" + decodeErr.Error()
  489. return
  490. }
  491. case strings.HasPrefix(header, "image"):
  492. reply, err := ioutil.ReadAll(postBody.Body)
  493. if err != nil {
  494. br.Msg = "分享失败"
  495. br.ErrMsg = "获取微信二维码失败,Err:" + err.Error()
  496. return
  497. }
  498. imageContent, createErr := os.Create(imagePath)
  499. if createErr != nil {
  500. br.Msg = "分享失败"
  501. br.ErrMsg = "获取微信二维码失败,Err:" + createErr.Error()
  502. return
  503. }
  504. writeStringRes, writeStringErr := io.WriteString(imageContent, string(reply))
  505. if writeStringErr != nil {
  506. fmt.Println(writeStringRes)
  507. br.Msg = "分享失败"
  508. br.ErrMsg = "获取微信二维码失败,Err:" + writeStringErr.Error()
  509. return
  510. }
  511. closeErr := imageContent.Close()
  512. if closeErr != nil {
  513. br.Msg = "分享失败"
  514. br.ErrMsg = "获取微信二维码失败,Err:" + closeErr.Error()
  515. return
  516. }
  517. randStr := utils.GetRandStringNoSpecialChar(28)
  518. fileName := randStr + ".jpg"
  519. savePath := uploadDir + time.Now().Format("200601/20060102/")
  520. savePath += fileName
  521. //上传到阿里云
  522. err = services.UploadFileToAliyun(fileName, imagePath, savePath)
  523. if err != nil {
  524. fmt.Println("文件上传失败,Err:" + err.Error())
  525. return
  526. }
  527. fileHost := "https://hzstatic.hzinsights.com/"
  528. resourceUrl = fileHost + savePath
  529. defer func() {
  530. os.Remove(imagePath)
  531. }()
  532. default:
  533. br.Msg = "分享失败"
  534. br.ErrMsg = "没有获取到分享二维码"
  535. return
  536. }
  537. resp := new(models.ArticleDetailFileLink)
  538. resp.FileLink = resourceUrl
  539. resp.Scene = strconv.Itoa(uid)
  540. br.Ret = 200
  541. br.Data = resp
  542. br.Success = true
  543. br.Msg = "提交成功"
  544. }
  545. // @Title 获取短信验证码(无需token)
  546. // @Description 获取短信验证码接口(无需token)
  547. // @Param Mobile query string true "手机号码"
  548. // @Param AreaNum query string true "地区编码"
  549. // @Success Ret=200 获取成功
  550. // @router /getSmsCodePublic [get]
  551. func (this *WechatCommonController) GetSmsCode() {
  552. br := new(models.BaseResponse).Init()
  553. defer func() {
  554. this.Data["json"] = br
  555. this.ServeJSON()
  556. }()
  557. mobile := this.GetString("Mobile")
  558. if mobile == "" {
  559. br.Msg = "请输入手机号"
  560. return
  561. }
  562. areaNum := this.GetString("AreaNum")
  563. msgCode := utils.GetRandDigit(4)
  564. var result bool
  565. if areaNum == "86" || areaNum == "" || areaNum == "0" {
  566. result = services.SendSmsCode(mobile, msgCode)
  567. } else {
  568. result = services.SendSmsCodeGj(mobile, msgCode, areaNum)
  569. }
  570. //发送成功
  571. if result {
  572. item := new(models.MsgCode)
  573. item.OpenId = ""
  574. item.Code = msgCode
  575. item.Mobile = mobile
  576. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  577. item.Enabled = 1
  578. item.CreatedTime = time.Now()
  579. err := models.AddMsgCode(item)
  580. if err != nil {
  581. br.Msg = "发送失败"
  582. br.ErrMsg = "发送失败,Err:" + err.Error()
  583. return
  584. }
  585. br.Msg = "发送成功"
  586. } else {
  587. br.Msg = "发送失败"
  588. }
  589. br.Ret = 200
  590. br.Success = true
  591. }