API

The API is exposed via service wrappers, which provide convenient WeChat OAuth2 flow methods as well as session management.

Each service type has specialized Session objects, which may be used directly.

WeChat Service

class wechat_oauth2.WeChatService(appid, secret, name='wechat', access_token_url='https://api.weixin.qq.com/sns/oauth2/access_token', authorize_url='https://open.weixin.qq.com/connect/oauth2/authorize', base_url='https://api.weixin.qq.com/sns/', session_obj=None)

网站应用微信OAuth2.0登录服务

This class wraps an Ofly service i.e., Shutterfly. The process is similar to that of OAuth 1.0 but simplified.

You might intialize WeChatService something like this:

service = WeChatService(appid='123',
                        secret='456')

A signed authorize URL is then produced via calling service.get_authorize_url. Once this has been visited by the client and assuming the client authorizes the request.

Normal API calls can now be made using a session instance. Retrieve the authenticated session like so:

session = service.get_auth_session(code)

# now we can make regular Requests' calls
r = session.get('userinfo')
Parameters:
  • appid – 微信应用ID
  • secret – 应用密钥
  • name – The service name, defaults to wechat.
  • authorize_url – Authorize endpoint, defaults to ``.
  • base_url – A base URL from which to construct requests, defaults to None.
  • session_obj (rauth.Session) – Object used to construct sessions with, defaults to wechat_oauth2.WeChatSession
get_access_token(code, method='GET', **kwargs)

文档

正确的返回:

{
    "access_token":"ACCESS_TOKEN",
    "expires_in":7200,
    "refresh_token":"REFRESH_TOKEN",
    "openid":"OPENID",
    "scope":"SCOPE",
    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
参数 说明
access_token 接口调用凭证
expires_in access_token接口调用凭证超时时间,单位(秒)
refresh_token 用户刷新access_token
openid 授权用户唯一标识
scope 用户授权的作用域,使用逗号(,)分隔
unionid 当且仅当该网站应用已获得该用户的userinfo授权时, 才会出现该字段。

错误返回样例:

{"errcode":40029,"errmsg":"invalid code"}
Parameters:
  • code – 授权临时票据code
  • method (str) – A string representation of the HTTP method to be used, defaults to GET.
  • **kwargs (dict) – Optional arguments. Same as Requests.
get_auth_session(code, method='GET', **kwargs)

ets an access token, intializes a new authenticated session with the access token. Returns an instance of session_obj.

get_authorize_url(redirect_uri=None, scope='snsapi_base', **params)

Returns a formatted authorize URL.

get_session(access_token=None, openid=None)

If provided, the access_token and openid parameter is used to initialize an authenticated session, otherwise an unauthenticated session object is generated. Returns an instance of session_obj..

Parameters:
  • access_token – access_token with which to initilize the session.
  • openid – openid with which to initilize the session.

WeChat Session

class wechat_oauth2.WeChatSession(appid=None, secret=None, access_token=None, openid=None, service=None, access_token_key=None)
close()

Closes all adapters and as such the session

delete(url, **kwargs)

Sends a DELETE request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

get(url, **kwargs)

Sends a GET request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

get_adapter(url)

Returns the appropriate connection adapter for the given URL.

Return type:requests.adapters.BaseAdapter
get_redirect_target(resp)

Receives a Response. Returns a redirect URI or None

head(url, **kwargs)

Sends a HEAD request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

merge_environment_settings(url, proxies, stream, verify, cert)

Check the environment and merge it with some settings.

Return type:dict
mount(prefix, adapter)

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by prefix length.

options(url, **kwargs)

Sends a OPTIONS request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

patch(url, data=None, **kwargs)

Sends a PATCH request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

post(url, data=None, json=None, **kwargs)

Sends a POST request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
  • json – (optional) json to send in the body of the Request.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

prepare_request(request)

Constructs a PreparedRequest for transmission and returns it. The PreparedRequest has settings merged from the Request instance and those of the Session.

Parameters:requestRequest instance to prepare with this session’s settings.
Return type:requests.PreparedRequest
put(url, data=None, **kwargs)

Sends a PUT request. Returns Response object.

Parameters:
  • url – URL for the new Request object.
  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
  • **kwargs – Optional arguments that request takes.
Return type:

requests.Response

rebuild_auth(prepared_request, response)

When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.

rebuild_method(prepared_request, response)

When being redirected we may want to change the method of the request based on certain specs or browser behavior.

rebuild_proxies(prepared_request, proxies)

This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).

This method also replaces the Proxy-Authorization header where necessary.

Return type:dict
request(method, url, **req_kwargs)

A loose wrapper around Requests’ Session which injects OAuth 2.0 parameters. :param method: A string representation of the HTTP method to be used. :type method: str :param url: The resource to be requested. :type url: str :param **req_kwargs: Keyworded args to be passed down to Requests. :type **req_kwargs: dict

resolve_redirects(resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)

Receives a Response. Returns a generator of Responses or Requests.

send(request, **kwargs)

Send a given PreparedRequest.

Return type:requests.Response
should_strip_auth(old_url, new_url)

Decide whether Authorization header should be removed when redirecting