12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package util
- import (
- //"encoding/json"
- "fmt"
- "net/http"
- "github.com/pkg/errors"
- )
- func GetOpenID(writer http.ResponseWriter, request *http.Request) {
- var codeMap map[string]string
- err := json.NewDecoder(request.Body).Decode(&codeMap)
- if err != nil {
- return
- }
- defer request.Body.Close()
- code := codeMap["code"]
- openid, err := SendWxAuthAPI(code)
- if err != nil {
- return
- }
- fmt.Println("my openid", openid)
- }
- const (
- code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
- appID = "wx99b5bd356930780f"
- appSecret = "8ec4db6a9277b845413b470fa6ff5679"
- )
- func SendWxAuthAPI(code string) (string, error) {
- url := fmt.Sprintf(code2sessionURL, appID, appSecret, code)
- resp, err := http.DefaultClient.Get(url)
- if err != nil {
- println("DefaultClient err ", err.Error())
- return "", err
- }
- var wxMap map[string]interface{}
- err = json.NewDecoder(resp.Body).Decode(&wxMap)
- if err != nil {
- println("NewDecoder err ", err.Error(), resp.Body)
- return "", err
- }
- if wxMap["openid"] == nil {
- fmt.Printf("%v+", wxMap)
- if wxMap["errmsg"] == nil {
- return "", errors.New("openid为空")
- } else {
- return "", errors.New(wxMap["errmsg"].(string))
- }
- }
- defer resp.Body.Close()
- return wxMap["openid"].(string), nil
- }
|