github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mp/oauth2/oauth2.go (about) 1 package oauth2 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/url" 7 8 "github.com/chanxuehong/wechat/internal/debug/api" 9 "github.com/chanxuehong/wechat/oauth2" 10 "github.com/chanxuehong/wechat/util" 11 ) 12 13 // AuthCodeURL 生成网页授权地址. 14 // 15 // appId: 公众号的唯一标识 16 // redirectURI: 授权后重定向的回调链接地址 17 // scope: 应用授权作用域 18 // state: 重定向后会带上 state 参数, 开发者可以填写 a-zA-Z0-9 的参数值, 最多128字节 19 func AuthCodeURL(appId, redirectURI, scope, state string) string { 20 return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + url.QueryEscape(appId) + 21 "&redirect_uri=" + url.QueryEscape(redirectURI) + 22 "&response_type=code&scope=" + url.QueryEscape(scope) + 23 "&state=" + url.QueryEscape(state) + 24 "#wechat_redirect" 25 } 26 27 // Auth 检验授权凭证 access_token 是否有效. 28 // 29 // accessToken: 网页授权接口调用凭证 30 // openId: 用户的唯一标识 31 // httpClient: 如果不指定则默认为 util.DefaultHttpClient 32 func Auth(accessToken, openId string, httpClient *http.Client) (valid bool, err error) { 33 if httpClient == nil { 34 httpClient = util.DefaultHttpClient 35 } 36 37 _url := "https://api.weixin.qq.com/sns/auth?access_token=" + url.QueryEscape(accessToken) + 38 "&openid=" + url.QueryEscape(openId) 39 api.DebugPrintGetRequest(_url) 40 httpResp, err := httpClient.Get(_url) 41 if err != nil { 42 return 43 } 44 defer httpResp.Body.Close() 45 46 if httpResp.StatusCode != http.StatusOK { 47 err = fmt.Errorf("http.Status: %s", httpResp.Status) 48 return 49 } 50 51 var result oauth2.Error 52 if err = api.DecodeJSONHttpResponse(httpResp.Body, &result); err != nil { 53 return 54 } 55 56 switch result.ErrCode { 57 case oauth2.ErrCodeOK: 58 valid = true 59 return 60 case 42001, 40001, 40014, 40003: 61 valid = false 62 return 63 default: 64 err = &result 65 return 66 } 67 }