├── setup.py ├── LICENSE ├── .gitignore ├── flask_wxapp └── __init__.py └── README.rst /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup, find_packages 3 | 4 | 5 | with open('README.rst') as f: 6 | readme = f.read() 7 | 8 | setup( 9 | name='Flask-WXApp', 10 | version='0.1.3', 11 | description='Flask Extension for WeChat App.', 12 | long_description=readme, 13 | author='codeif', 14 | author_email='me@codeif.com', 15 | url='https://github.com/codeif/Flask-WXApp', 16 | license='MIT', 17 | install_requires=['requests', 'pycryptodome'], 18 | packages=find_packages(), 19 | ) 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 codeif 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /flask_wxapp/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import binascii 4 | import base64 5 | import json 6 | import requests 7 | from Crypto.Cipher import AES 8 | 9 | 10 | class WXApp(object): 11 | 12 | def __init__(self, app=None): 13 | if app is not None: 14 | self.init_app(app) 15 | 16 | def init_app(self, app): 17 | self.appid = app.config['WX_APPID'] 18 | self.secret = app.config['WX_SECRET'] 19 | 20 | def jscode2session(self, js_code): 21 | url = ('https://api.weixin.qq.com/sns/jscode2session?' 22 | 'appid={}&secret={}&js_code={}&grant_type=authorization_code' 23 | ).format(self.appid, self.secret, js_code) 24 | r = requests.get(url) 25 | return r.json() 26 | 27 | def decrypt(self, session_key, encrypted_data, iv): 28 | # base64 decode 29 | session_key = base64.b64decode(session_key) 30 | encrypted_data = base64.b64decode(encrypted_data) 31 | iv = base64.b64decode(iv) 32 | 33 | cipher = AES.new(session_key, AES.MODE_CBC, iv) 34 | 35 | decrypt_data = self._unpad(cipher.decrypt(encrypted_data)) 36 | decrypted = json.loads(decrypt_data.decode()) 37 | 38 | if decrypted['watermark']['appid'] != self.appid: 39 | raise Exception('Invalid Buffer') 40 | 41 | return decrypted 42 | 43 | def _unpad(self, s): 44 | return s[:-ord(s[len(s)-1:])] 45 | 46 | 47 | def gen_3rd_session_key(): 48 | """生成长度为32位的hex字符串,用于第三方session的key""" 49 | return binascii.hexlify(os.urandom(16)).decode() 50 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 微信小程序Flask扩展 2 | =================== 3 | 4 | - `微信文档 `_ 5 | 6 | Installation 7 | ------------ 8 | 9 | .. code:: 10 | 11 | pip install Flask-WXApp 12 | 13 | Configuration 14 | ------------- 15 | 16 | Your configuration should be declared within your Flask config. 17 | 18 | .. code:: python 19 | 20 | WX_APPID = 'your appid' 21 | WX_SECRET = 'your app secret' 22 | 23 | Create instance within your application 24 | 25 | .. code:: python 26 | 27 | from flask import Flask 28 | from flask_wxapp import WXApp 29 | 30 | wxapp = WXApp() 31 | 32 | def create_app(): 33 | app = Flask(__name__) 34 | wxapp.init_app(app) 35 | return app 36 | 37 | Usage 38 | ----- 39 | 40 | - 通过code换取openid和session_key 41 | 42 | 接口:: 43 | 44 | wxapp.jscode2session(js_code) 45 | 46 | 返回json(dict): 47 | 48 | ============ ============= 49 | 参数 说明 50 | ============ ============= 51 | openid 用户唯一标识 52 | session_key 会话密钥 53 | ============ ============= 54 | 55 | 56 | - 加密数据解密 57 | 58 | 接口:: 59 | 60 | wxapp.decrypt(session_key, encrypted_data, iv) 61 | 62 | 返回数据如下:: 63 | 64 | { 65 | 'avatarUrl': 'http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0', 66 | 'city': 'Guangzhou', 67 | 'country': 'CN', 68 | 'gender': 1, 69 | 'language': 'zh_CN', 70 | 'nickName': 'Band', 71 | 'openId': 'oGZUI0egBJY1zhBYw2KhdUfwVJJE', 72 | 'province': 'Guangdong', 73 | 'unionId': 'ocMvos6NjeKLIBqg5Mr9QjxrP1FA', 74 | 'watermark': {'appid': 'wx4f4bc4dec97d474b', 'timestamp': 1477314187} 75 | } 76 | 77 | - 生成3rd_session的key 78 | 79 | .. code:: python 80 | 81 | wx.gen_3rd_session_key() 82 | 83 | 返回32位长度的16进止字符串,例如:: 84 | 85 | 8e4792ee728926443147bb5703aa50a7 86 | --------------------------------------------------------------------------------