1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package util
- import (
- "errors"
- "fmt"
- "net/http"
- )
- 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
- }
|