b1c4876ccc389acb9512da8b14ee728e1a9daa73.svn-base 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. )
  7. func GetOpenID(writer http.ResponseWriter, request *http.Request) {
  8. var codeMap map[string]string
  9. err := json.NewDecoder(request.Body).Decode(&codeMap)
  10. if err != nil {
  11. return
  12. }
  13. defer request.Body.Close()
  14. code := codeMap["code"]
  15. openid, err := SendWxAuthAPI(code)
  16. if err != nil {
  17. return
  18. }
  19. fmt.Println("my openid", openid)
  20. }
  21. const (
  22. code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
  23. appID = "wx99b5bd356930780f"
  24. appSecret = "8ec4db6a9277b845413b470fa6ff5679"
  25. )
  26. func SendWxAuthAPI(code string) (string, error) {
  27. url := fmt.Sprintf(code2sessionURL, appID, appSecret,code)
  28. resp, err := http.DefaultClient.Get(url)
  29. if err != nil {
  30. println("DefaultClient err ",err.Error())
  31. return "", err
  32. }
  33. var wxMap map[string]interface{}
  34. err = json.NewDecoder(resp.Body).Decode(&wxMap)
  35. if err != nil {
  36. println("NewDecoder err ",err.Error(),resp.Body)
  37. return "", err
  38. }
  39. if wxMap["openid"] == nil{
  40. fmt.Printf("%v+",wxMap)
  41. if wxMap["errmsg"] == nil {
  42. return "", errors.New("openid为空")
  43. }else {
  44. return "", errors.New(wxMap["errmsg"].(string))
  45. }
  46. }
  47. defer resp.Body.Close()
  48. return wxMap["openid"].(string), nil
  49. }