wechat.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package dao
  2. import (
  3. "context"
  4. "net/url"
  5. "go-common/app/admin/ep/marthe/model"
  6. )
  7. const (
  8. _qyWechatURL = "https://qyapi.weixin.qq.com"
  9. _corpID = "wx0833ac9926284fa5" // 企业微信:Bilibili的企业ID
  10. _departmentID = "12" // 公司统一用部门ID
  11. _corpsecret = "WveODxk3xpT9box48wcxkmArx3mu6d4vJHdJkNy_iTk"
  12. _getToken = "/cgi-bin/gettoken"
  13. _userList = "/cgi-bin/user/list"
  14. )
  15. // WechatAccessToken query access token with the specified secret 企业微信api获取公司token
  16. func (d *Dao) WechatAccessToken(c context.Context) (token string, err error) {
  17. var (
  18. u string
  19. params = url.Values{}
  20. res struct {
  21. ErrCode int `json:"errcode"`
  22. ErrMsg string `json:"errmsg"`
  23. AccessToken string `json:"access_token"`
  24. ExpiresIn int32 `json:"expires_in"`
  25. }
  26. )
  27. u = _qyWechatURL + _getToken
  28. params.Set("corpid", _corpID)
  29. params.Set("corpsecret", _corpsecret)
  30. if err = d.httpClient.Get(c, u, "", params, &res); err != nil {
  31. return
  32. }
  33. if res.ErrCode != 0 {
  34. return
  35. }
  36. token = res.AccessToken
  37. return
  38. }
  39. // WechatContacts Wechat Contacts 获取用户信息列表
  40. func (d *Dao) WechatContacts(c context.Context) (contacts []*model.WechatContact, err error) {
  41. var (
  42. token string
  43. u string
  44. params = url.Values{}
  45. res struct {
  46. ErrCode int `json:"errcode"`
  47. ErrMsg string `json:"errmsg"`
  48. UserList []*model.WechatContact `json:"userlist"`
  49. }
  50. )
  51. //get token
  52. if token, err = d.WechatAccessToken(c); err != nil {
  53. return
  54. }
  55. u = _qyWechatURL + _userList
  56. params.Set("access_token", token)
  57. params.Set("department_id", _departmentID)
  58. params.Set("fetch_child", "1")
  59. if err = d.httpClient.Get(c, u, "", params, &res); err != nil {
  60. return
  61. }
  62. if res.ErrCode != 0 {
  63. return
  64. }
  65. contacts = res.UserList
  66. return
  67. }