oauth2

package
v0.0.0-...-f5adc6c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2014 License: Apache-2.0 Imports: 8 Imported by: 0

README

简介

这个 package 封装了微信公众平台的网页授权获取用户信息功能。

示例

package main

import (
	"github.com/chanxuehong/wechat/oauth2"
	"net/http"
)

// 一个应用只用一个全局变量(实际应用中根据自己的参数填写)
var oauth2Config = oauth2.NewOAuth2Config("appid", "appsecret", "redirectURL", "scope0", "scope1")

// 在需要用户授权的时候引导用户到授权页面
func SomeHandler(w http.ResponseWriter, r *http.Request) {
	var hasAuth bool // 判断是否授权
	// TODO: 判断 session 里是否有 openid 字段,如果有则表明已经授权,没有则没有授权

	if hasAuth {
		var info *oauth2.OAuth2Info
		// TODO: 根据 openid 字段 找到 info(type == *oauth2.OAuth2Info)

		client := oauth2.Client{
			OAuth2Config: oauth2Config,
			OAuth2Info:   info,
		}

		// 可以根据这个 info 做相应的操作,比如下面的获取用户信息
		userinfo, err := client.UserInfo("zh_CN")
		if err != nil {
			// TODO: ...
			return
		}

		// 处理 userinfo
		_ = userinfo // NOTE: 实际开发中可不是这样的

	} else {
		var state = "state" // NOTE: 实际上是一串不可预测的随机数

		// TODO: state 做相应处理,好识别下次跳转回来的 state 参数

		http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusFound)
	}
}

// 跳转后的页面请求处理.
// redirectURL?code=CODE&state=STATE // 授权
// redirectURL?state=STATE           // 不授权
func RedirectURLHandler(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		// TODO: 处理 error
		return
	}

	state := r.FormValue("state")

	// TODO: 处理这个 state 参数, 判断是否是有效的

	_ = state // NOTE: 实际开发中不要有这个

	// 假定 state 有效

	if code := r.FormValue("code"); code != "" { // 授权

		client := oauth2.Client{
			OAuth2Config: oauth2Config,
		}
		info, err := client.Exchange(code)
		if err != nil {
			// TODO: ...
			return
		}

		// TODO: 这里把 info 根据 info.OpenId 缓存起来,以后可以直接用
		// 做相应的 session 处理。
		_ = info // NOTE: 示例代码

	} else { // 不授权
		// TODO: 不授权的相应代码
	}
}

func main() {
	// TODO: 为 http 添加路由处理,然后在运行 http service
}

Documentation

Overview

封装网页授权获取用户基本信息的支持.

Index

Constants

View Source
const (
	Language_zh_CN = "zh_CN" // 简体中文
	Language_zh_TW = "zh_TW" // 繁体中文
	Language_en    = "en"    // 英文
)
View Source
const (
	SEX_UNKNOWN = 0 // 未知
	SEX_MALE    = 1 // 男性
	SEX_FEMALE  = 2 // 女性
)

Variables

This section is empty.

Functions

func HeadImageSize

func HeadImageSize(headImageURL string) (size int, err error)

获取用户图像的大小

@headImageURL: 用户头像URL,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像)
NOTE: 请确保 headImageURL 不为空

Types

type Client

type Client struct {
	*OAuth2Config

	// 下面两个字段必须指定其中一个(通过code换取网页授权access_token 时除外)
	// 如果指定 OAuth2Token 则表示手动管理 OAuth2Token, 需要手动更新 OAuth2Token
	// 如果指定 TokenCache 则表示自动管理 OAuth2Token, 程序会自动更新 OAuth2Token
	*OAuth2Token
	TokenCache TokenCache

	//  如果 httpClient == nil 则默认用 http.DefaultClient,
	//  see ../CommonHttpClient 和 ../MediaHttpClient.
	HttpClient *http.Client
}

func (*Client) CheckAccessTokenValid

func (c *Client) CheckAccessTokenValid() (valid bool, err error)

检查 access_token 是否有效

func (*Client) Exchange

func (c *Client) Exchange(code string) (token *OAuth2Token, err error)

通过code换取网页授权 access_token

NOTE: 如果成功 c.OAuth2Token 字段也会得到更新,
      如果指定了 TokenCache, TokenCache.PutToken 也会被调用

func (*Client) TokenRefresh

func (c *Client) TokenRefresh() (token *OAuth2Token, err error)

刷新access_token(如果需要)

NOTE: 如果成功 c.OAuth2Token 字段也会得到更新,
      如果指定了 TokenCache, TokenCache.PutToken 也会被调用

func (*Client) UserInfo

func (c *Client) UserInfo(lang string) (info *UserInfo, err error)

获取用户信息(需scope为 snsapi_userinfo).

lang 可能的取值是 zh_CN, zh_TW, en; 如果留空 "" 则默认为 zh_CN.

type Error

type Error struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

微信服务器返回的错误都是这个格式

func (*Error) Error

func (e *Error) Error() string

type OAuth2Config

type OAuth2Config struct {
	AppId     string
	AppSecret string

	// 应用授权作用域,拥有多个作用域用逗号(,)分隔;
	// 目前有 snsapi_base, snsapi_userinfo.
	Scope string

	// 用户授权后跳转的目的地址
	// 用户授权后跳转到 RedirectURL?code=CODE&state=STATE
	// 用户禁止授权跳转到 RedirectURL?state=STATE
	RedirectURL string
}

oauth2 相关配置 ( 一般全局只用保存一个变量 )

func NewOAuth2Config

func NewOAuth2Config(appid, appsecret, redirectURL string, scope ...string) *OAuth2Config

func (*OAuth2Config) AuthCodeURL

func (cfg *OAuth2Config) AuthCodeURL(state string) string

请求用户授权时跳转的地址.

type OAuth2Token

type OAuth2Token struct {
	AccessToken  string
	RefreshToken string
	ExpiresAt    int64 // unixtime

	OpenId string
	Scopes []string // 用户授权的作用域
}

用户相关的 oauth2 token 信息

NOTE: 每个用户对应一个这样的结构, 应该缓存起来, 一般缓存在 session 中.

type TokenCache

type TokenCache interface {
	Token() (*OAuth2Token, error)
	PutToken(*OAuth2Token) error
}

OAuth2Token 缓存接口

type UserInfo

type UserInfo struct {
	OpenId   string `json:"openid"`     // 用户的唯一标识
	Nickname string `json:"nickname"`   // 用户昵称
	Sex      int    `json:"sex,string"` // 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
	City     string `json:"city"`       // 普通用户个人资料填写的城市
	Province string `json:"province"`   // 用户个人资料填写的省份
	Country  string `json:"country"`    // 国家,如中国为CN

	// 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),
	// 用户没有头像时该项为空
	HeadImageURL string `json:"headimgurl,omitempty"`

	// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
	Privilege []string `json:"privilege"`

	// 用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。
	UnionId string `json:"unionid"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL