#!/usr/bin/env python
# -*- coding: utf-8 -*-


import aiohttp
import async_timeout
from sanic.response import json
from sanic import Blueprint


APPID = ''
SECRET = ''


wx = Blueprint('wx', url_prefix='wx')


async def get_session_key(JSCODE):
    url = 'https://api.weixin.qq.com/sns/jscode2session'
    params = {
        'appid': APPID,
        'secret': SECRET,
        'js_code': JSCODE,
        'grant_type': 'authorization_code',
    }
    async with aiohttp.ClientSession() as session:
        with async_timeout.timeout(10):
            async with session.get(url, params=params) as response:
                return await response.text()


@wx.get('/login')
async def wx_login(request):
    url_params = request.raw_args
    rv_json = await get_session_key(url_params.get('code'))
    print('rv_json', rv_json)
    return json(rv_json)
