20791151329eaae1a0fc883362a17639139059d2.svn-base 1.3 KB

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