예제 #1
0
def _get_access_token(appid, refresh=False):
    if not refresh:
        token = wechat_storage.get_access_token(appid)  # TODO: move this to redis
        if token:
            raise tornado.gen.Return({
                'err_code': 0,
                'data': {'access_token': token}
            })
    try:
        app_info = wechat_storage.get_app_info(appid=appid)
        resp = yield httputils.get_dict(
            url=url.wechat_basic_access_token,
            data={
                'grant_type': 'client_credential',
                'appid': appid,
                'secret': app_info['secret']
            })
    except tornado.httpclient.HTTPError:
        raise tornado.gen.Return({'err_code': 1001})
    result = _parse_wechat_resp(resp)
    if result['err_code'] != 0:
        raise tornado.gen.Return(result)
    else:
        result_data = result.get('data')
        wechat_storage.add_access_token(app_info['id'], appid, result_data.get('access_token'),
                                        result_data.get('expires_in'))
        raise tornado.gen.Return(result)
예제 #2
0
def _get_access_token(appid, refresh=False):
    if not refresh:
        token = wechat_storage.get_access_token(
            appid)  # TODO: move this to redis
        if token:
            raise tornado.gen.Return({
                'err_code': 0,
                'data': {
                    'access_token': token
                }
            })
    try:
        app_info = wechat_storage.get_app_info(appid=appid)
        resp = yield httputils.get_dict(url=url.wechat_basic_access_token,
                                        data={
                                            'grant_type': 'client_credential',
                                            'appid': appid,
                                            'secret': app_info['secret']
                                        })
    except tornado.httpclient.HTTPError:
        raise tornado.gen.Return({'err_code': 1001})
    result = _parse_wechat_resp(resp)
    if result['err_code'] != 0:
        raise tornado.gen.Return(result)
    else:
        result_data = result.get('data')
        wechat_storage.add_access_token(app_info['id'], appid,
                                        result_data.get('access_token'),
                                        result_data.get('expires_in'))
        raise tornado.gen.Return(result)
예제 #3
0
def _wechat_api_call(method, appid, fn_url, fn_data=None, retry=0):
    token_result = yield _get_access_token(appid, refresh=(retry != 0))
    if token_result['err_code'] != 0:
        raise tornado.gen.Return(token_result)
    token = token_result['data']['access_token']
    logging.info('access_token: %s', token)
    try:
        if method == 'GET':
            resp = yield httputils.get_dict(url=fn_url,
                                            data=dict(fn_data or {},
                                                      access_token=token))
        elif method == 'POST':
            resp = yield httputils.post_dict(url=build_url(
                fn_url, {'access_token': token}),
                                             data=fn_data,
                                             data_type='json')
        else:
            return
    except tornado.httpclient.HTTPError:
        raise tornado.gen.Return({'err_code': 1001})
    result = _parse_wechat_resp(resp)
    if result['err_code'] == 1004 and retry < 3:
        result = yield _wechat_api_call(appid, fn_url, fn_data, retry + 1)
        raise tornado.gen.Return(result)
    else:
        raise tornado.gen.Return(result)
예제 #4
0
def _wechat_api_call(method, appid, fn_url, fn_data=None, retry=0):
    token_result = yield _get_access_token(appid, refresh=(retry != 0))
    if token_result['err_code'] != 0:
        raise tornado.gen.Return(token_result)
    token = token_result['data']['access_token']
    logging.info('access_token: %s', token)
    try:
        if method == 'GET':
            resp = yield httputils.get_dict(
                url=fn_url,
                data=dict(fn_data or {}, access_token=token)
            )
        elif method == 'POST':
            resp = yield httputils.post_dict(
                url=build_url(fn_url, {
                    'access_token': token
                }),
                data=fn_data,
                data_type='json'
            )
        else:
            return
    except tornado.httpclient.HTTPError:
        raise tornado.gen.Return({'err_code': 1001})
    result = _parse_wechat_resp(resp)
    if result['err_code'] == 1004 and retry < 3:
        result = yield _wechat_api_call(appid, fn_url, fn_data, retry + 1)
        raise tornado.gen.Return(result)
    else:
        raise tornado.gen.Return(result)
예제 #5
0
def get_location(query):
    locres = yield httputils.get_dict(
        url="http://maps.googleapis.com/maps/api/geocode/json",
        data={
            'address': query,
            'sensor': 'false',
            'language': 'zh-CN'
        },
        proxy_host='192.110.165.49',
        proxy_port=8180)
    resp = None
    if locres.code == 200:
        try:
            report = json.loads(locres.body.decode('utf8'))
            if report['status'] == 'OK':
                result = report['results'][0]
                address = result['formatted_address']
                lng = result['geometry']['location']['lng']
                lat = result['geometry']['location']['lat']
                resp = {
                    'query': query,
                    'address': address,
                    'longitude': lng,
                    'latitude': lat
                }
        except KeyError:
            logging.warning('invalid resp from google geo api')
    raise tornado.gen.Return(resp)
예제 #6
0
 def _get(self, appid, get_url, data, **kwargs):
     headers = dict(_default_headers, **{
         'Referer': kwargs.get('referer', url.mp_base),
         'Cookie': self._build_cookies(appid),
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
     })
     resp = yield httputils.get_dict(url=get_url, data=data, headers=headers)
     if resp.code == 200:
         self._set_cookies(appid, resp.headers)
     raise tornado.gen.Return(resp)
예제 #7
0
    def post(self, siteid):
        appid = self.get_argument("appid")
        appinfo = self.storage.get_app_info(appid=appid)
        if not appinfo:
            self.send_response(err_code=3201)
            raise tornado.gen.Return()

        openid = self.get_argument("openid", "")
        if openid:
            res = yield wxclient.update_user_info(appid, openid)
            if res["err_code"] == 0:
                self.send_response(data=res["data"])
                raise tornado.gen.Return()

        code = self.get_argument("code", "")
        if code:
            req_data1 = {"code": code, "appid": appid, "secret": appinfo["secret"], "grant_type": "authorization_code"}
            try:
                resp1 = yield httputils.get_dict(url=url.wechat_oauth_access_token, data=req_data1)
            except tornado.httpclient.HTTPError:
                self.send_response(err_code=1001)
                raise tornado.gen.Return()

            resp_data1 = self.parse_oauth_resp(resp1)
            if resp_data1:
                openid = resp_data1["openid"]
                res = {"openid": openid, "appid": appid}
                # Get user info from wechat
                if "snsapi_userinfo" in [v.strip() for v in resp_data1["scope"].split(",")]:
                    req_data2 = {"access_token": resp_data1["access_token"], "openid": openid, "lang": "zh_CN"}
                    try:
                        resp2 = yield httputils.get_dict(url=url.wechat_oauth_userinfo, data=req_data2)
                    except tornado.httpclient.HTTPError:
                        self.send_response(err_code=1001)
                        raise tornado.gen.Return()
                    resp_data2 = self.parse_oauth_resp(resp2)
                    if resp_data2:
                        res.update(resp_data2)
                post_resp_data = dtools.transfer(res, copys=user_attrs, allow_empty=False)
                self.send_response(post_resp_data)
                self.storage.add_user_info(post_resp_data)
                raise tornado.gen.Return()
        self.send_response(err_code=1)
예제 #8
0
 def _get(self, appid, get_url, data, **kwargs):
     headers = dict(
         _default_headers, **{
             'Referer':
             kwargs.get('referer', url.mp_base),
             'Cookie':
             self._build_cookies(appid),
             'Accept':
             'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
         })
     resp = yield httputils.get_dict(url=get_url,
                                     data=data,
                                     headers=headers)
     if resp.code == 200:
         self._set_cookies(appid, resp.headers)
     raise tornado.gen.Return(resp)
예제 #9
0
def get_location(query):
    locres = yield httputils.get_dict(
        url="http://maps.googleapis.com/maps/api/geocode/json",
        data={'address': query, 'sensor': 'false', 'language': 'zh-CN'},
        proxy_host='192.110.165.49',
        proxy_port=8180)
    resp = None
    if locres.code == 200:
        try:
            report = json.loads(locres.body.decode('utf8'))
            if report['status'] == 'OK':
                result = report['results'][0]
                address = result['formatted_address']
                lng = result['geometry']['location']['lng']
                lat = result['geometry']['location']['lat']
                resp = {'query': query, 'address': address, 'longitude': lng, 'latitude': lat}
        except KeyError:
            logging.warning('invalid resp from google geo api')
    raise tornado.gen.Return(resp)
예제 #10
0
    def post(self, siteid):
        appid = self.get_argument('appid')
        appinfo = self.storage.get_app_info(appid=appid)
        if not appinfo:
            self.send_response(err_code=3201)
            raise tornado.gen.Return()

        openid = self.get_argument('openid', '')
        if openid:
            res = yield wxclient.update_user_info(appid, openid)
            if res['err_code'] == 0:
                self.send_response(data=res['data'])
                raise tornado.gen.Return()

        code = self.get_argument('code', '')
        if code:
            req_data1 = {
                'code': code,
                'appid': appid,
                'secret': appinfo['secret'],
                'grant_type': 'authorization_code',
            }
            try:
                resp1 = yield httputils.get_dict(
                    url=url.wechat_oauth_access_token, data=req_data1)
            except tornado.httpclient.HTTPError:
                self.send_response(err_code=1001)
                raise tornado.gen.Return()

            resp_data1 = self.parse_oauth_resp(resp1)
            if resp_data1:
                openid = resp_data1['openid']
                res = {
                    'openid': openid,
                    'appid': appid,
                }
                # Get user info from wechat
                if 'snsapi_userinfo' in [
                        v.strip() for v in resp_data1['scope'].split(',')
                ]:
                    req_data2 = {
                        'access_token': resp_data1['access_token'],
                        'openid': openid,
                        'lang': 'zh_CN'
                    }
                    try:
                        resp2 = yield httputils.get_dict(
                            url=url.wechat_oauth_userinfo, data=req_data2)
                    except tornado.httpclient.HTTPError:
                        self.send_response(err_code=1001)
                        raise tornado.gen.Return()
                    resp_data2 = self.parse_oauth_resp(resp2)
                    if resp_data2:
                        res.update(resp_data2)
                post_resp_data = dtools.transfer(res,
                                                 copys=user_attrs,
                                                 allow_empty=False)
                self.send_response(post_resp_data)
                self.storage.add_user_info(post_resp_data)
                raise tornado.gen.Return()
        self.send_response(err_code=1)