Skip to content

Commit

Permalink
支持小程序登录
Browse files Browse the repository at this point in the history
  • Loading branch information
gusibi committed Nov 4, 2016
1 parent 57e1228 commit 13e2309
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 9 deletions.
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ python-weixin
-----
A Python client for the Weixin REST APIs

0.1.6 添加 模板消息处理
-----

0.1.5 添加 模板消息处理
-----
添加模板消息处理
Expand Down Expand Up @@ -58,7 +61,7 @@ Weixin API 使用 OAuth2 认证方式
### Using an access token
获取到access token 后,可以使用token 获取 用户信息等:

微信开放平台使用示例:
#### 微信开放平台使用示例:

``` python
from weixin.client import WeixinAPI
Expand All @@ -76,7 +79,7 @@ api = WeixinAPI(access_token=access_token)
user = api.user(openid="openid")
```

微信公众平台使用示例:
#### 微信公众平台使用示例:

``` python
from weixin.client import WeixinMpAPI
Expand All @@ -94,6 +97,17 @@ api = WeixinMpAPI(access_token=access_token)
user = api.user(openid="openid")
```

#### 微信小程序使用示例:

``` python
from weixin import WXAPPAPI

api = WXAPPAPI(appid=APP_ID,
app_secret=APP_SECRET)
session_info = api.exchange_code_for_session_key(code=code)
```



#### 创建自定义菜单

Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from setuptools import setup, find_packages

setup(name="python-weixin",
version="0.1.5",
description="Python Weixin API client",
version="0.1.6",
description="Python Weixin API client 支持小程序登录",
license="BSD",
install_requires=["simplejson", "requests", "six", "chardet"],
author="Zongxiao Cheng",
Expand Down
2 changes: 1 addition & 1 deletion weixin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@


from .bind import WeixinClientError, WeixinAPIError
from .client import WeixinAPI, WeixinMpAPI
from .client import WeixinAPI, WeixinMpAPI, WXAPPAPI
from .response import WXResponse
from .reply import WXReply
23 changes: 22 additions & 1 deletion weixin/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*-coding: utf-8 -*-
# !/usr/bin/env python
from __future__ import unicode_literals

"""
Expand Down Expand Up @@ -149,3 +148,25 @@ def validate_signature(self):
method='POST',
accepts_parameters=['json_body'],
response_type="entry")


class WXAPPAPI(oauth2.OAuth2API):

host = "api.weixin.qq.com"
base_path = ""
access_token_field = "access_token"
authorize_url = ""
access_token_url = "https://api.weixin.qq.com/sns/jscode2session"
refresh_token_url = ""
protocol = "https"
api_name = "Weixin"
x_ratelimit_remaining = None
x_ratelimit = None

def __init__(self, *args, **kwargs):
format = kwargs.get('format', '')
if format in SUPPORTED_FORMATS:
self.format = format
else:
raise Exception("Unsupported format")
super(WXAPPAPI, self).__init__(*args, **kwargs)
33 changes: 30 additions & 3 deletions weixin/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ def exchange_refresh_token_for_access_token(self, refresh_token):
req = OAuth2AuthExchangeRequest(self)
return req.exchange_for_access_token(refresh_token=refresh_token)

def exchange_code_for_session_key(self, code):
req = OAuth2AuthExchangeRequest(self)
return req.exchange_for_session_key(js_code=code)


class OAuth2AuthExchangeRequest(object):
def __init__(self, api):
Expand All @@ -118,7 +122,8 @@ def _url_for_authorize(self, scope=None, state=None):
url_params = url_encode(client_params, sort=True)
return "%s?%s" % (self.api.authorize_url, url_params)

def _data_for_exchange(self, code=None, refresh_token=None, scope=None):
def _data_for_exchange(self, code=None, js_code=None,
refresh_token=None, scope=None):
app_params = {
"appid": self.api.appid,
}
Expand All @@ -127,6 +132,10 @@ def _data_for_exchange(self, code=None, refresh_token=None, scope=None):
secret=self.api.app_secret,
redirect_uri=self.api.redirect_uri,
grant_type="authorization_code")
elif js_code:
app_params.update(js_code=js_code,
secret=self.api.app_secret,
grant_type="authorization_code")
elif refresh_token:
app_params.update(refresh_token=refresh_token,
grant_type="refresh_token")
Expand All @@ -141,6 +150,8 @@ def _data_for_exchange(self, code=None, refresh_token=None, scope=None):
url_params = urlencode(str_app_parmas)
if code:
return "%s?%s" % (self.api.access_token_url, url_params)
elif js_code:
return "%s?%s" % (self.api.access_token_url, url_params)
elif refresh_token:
return "%s?%s" % (self.api.refresh_token_url, url_params)
elif self.api.app_secret:
Expand Down Expand Up @@ -172,8 +183,24 @@ def get_authorize_login_url(self, scope=None, state=None):

def exchange_for_access_token(self, code=None,
refresh_token=None, scope=None):
access_token_url = self._data_for_exchange(code,
refresh_token, scope=scope)
access_token_url = self._data_for_exchange(
code, refresh_token, scope=scope)
try:
response = requests.get(access_token_url, timeout=TIMEOUT)
except (ConnectTimeout, ReadTimeout):
raise ConnectTimeoutError('timeout', 'Connect timeout')
except _ConnectionError:
raise ConnectionError('conntect_error',
'Failed to establish a new connection')
parsed_content = simplejson.loads(response.content.decode())
if parsed_content.get('errcode', 0):
raise OAuth2AuthExchangeError(
parsed_content.get("errcode", 0),
parsed_content.get("errmsg", ""))
return parsed_content

def exchange_for_session_key(self, js_code=None, scope=None):
access_token_url = self._data_for_exchange(js_code=js_code, scope=scope)
try:
response = requests.get(access_token_url, timeout=TIMEOUT)
except (ConnectTimeout, ReadTimeout):
Expand Down

0 comments on commit 13e2309

Please sign in to comment.