def put(self, request):
        request_data = request.data
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        logger_info.info(request_data)
        # AUthorization check
        try:
            open_id = request.META['HTTP_OPEN_ID']
            access_token = str(request.META['HTTP_AUTHORIZATION']).split(' ')[1]

            url = urlmapper.get_url('TOKEN_VALIDATE')
            headers = {'open-id': open_id, 'authorization': 'bearer ' + access_token}
            response = requests.get(url, headers=headers)

            if response.status_code != 200:
                raise Exception
        except Exception as e:
            print(e)
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED, get_msg(code.ARIES_401_UNAUTHORIZED))
            return Response(result.get_response(), result.get_code())

        # Request data parsing
        try:
            # Check selective review object
            product_id = request_data['product_id']
            comment = request_data['comment']
            if len(comment) <= 0:
                request_data['visible'] = False
            else:
                request_data['visible'] = True

        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid')
            return Response(result.get_response(), result.get_code())

        review = CustomerReview.objects.get(open_id=open_id, product_id=product_id)
        serializer = CustomerReviewSerializer(review, data=request_data, partial=True)

        if serializer.is_valid():
            serializer.save()

            # Statics information apply
            payload = {'menu_id': review.menu, 'prev_rate': review.menu_rate,
                       'menu_rate': request_data['menu_rate']}
            statics_result = requests.put(urlmapper.get_url('MENU_STATICS'), json=payload)
            logger_info.info(statics_result.text)
        else:
            logger_info.info(serializer.errors)
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid')
            return Response(result.get_response(), result.get_code())

        return Response(result.get_response(), result.get_code())
def get_purchases_data(open_id, access_token, accept_lang):
    headers = {
        'open-id': str(open_id),
        'Content-Type': 'application/json',
        'Accept-Language': accept_lang,
        'Authorization': 'bearer ' + access_token
    }
    response = requests.get(urlmapper.get_url('COUPON_LIST'), headers=headers)

    if response.status_code == code.ARIES_200_SUCCESS:
        response_json = response.json()
        coupon_json = response_json['coupons']
        primary_json = response_json['primary_coupons']
        additional_json = response_json['additional_coupons']
    else:
        coupon_json = []
        primary_json = []
        additional_json = []

    purchase_map = {
        'coupons': coupon_json,
        'primary_coupons': primary_json,
        'additional_coupons': additional_json
    }

    return purchase_map
def referral_sign_up_push(message):
    payload = {
        'code': 200, 'message': 'success', 'type': 1,
        'title': message
    }
    url = urlmapper.get_url('HUB_MESSAGE_ANDROID')
    response = requests.post(url, json=payload)
def get_admin_token_validate_v2(access_token):
    url = urlmapper.get_url('ADMIN_VALIDATE')
    payload = {'access_token': access_token}
    response = requests.post(url, json=payload)

    if response.status_code != code.ARIES_200_SUCCESS:
        raise AuthInfoError('Authentication error')
    def get_payment_params(self, payment_params):
        if settings.DEBUG:
            debug = True
        elif settings.STAGE:
            debug = True
        else:
            debug = False

        alipay = AliPay(
            debug=debug,
            appid=resources.get_alipay_app_id(),
            app_notify_url=urlmapper.get_url('ALIPAY_CALLBACK_URL'),
            app_private_key_path=resources.get_viastelle_pri_key(),
            alipay_public_key_path=resources.get_viastelle_pub_key(),
            sign_type="RSA2"
        )

        payment_order = alipay.api_alipay_trade_app_pay(
            out_trade_no=payment_params['order_id'],
            total_amount=payment_params['total_price'],
            subject=payment_params['product_title'],
        )
        self.logger_info.info(payment_order)
        param_result = {'alipay_order': payment_order}

        return param_result
예제 #6
0
    def post(self, request):
        request_data = request.data
        logger_info.info(request_data)

        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        # Operation check
        try:
            access_token = str(
                request.META['HTTP_AUTHORIZATION']).split(' ')[1]

            url = urlmapper.get_url('ADMIN_VALIDATE')
            payload = {'access_token': access_token}
            response = requests.post(url, json=payload)

            if response.status_code != code.ARIES_200_SUCCESS:
                result = ResultResponse(code.ARIES_401_UNAUTHORIZED,
                                        'Token or user not found')
                return Response(result.get_response(), result.get_code())

        except Exception as e:
            print(e)
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED,
                                    'Error : ' + str(e))
            return Response(result.get_response(), result.get_code())

        try:
            open_id = request_data['open_id']
            news_type = request_data['type']
            title = request_data['title']
            title_cn = request_data['title_cn']
            content = request_data['content']
            content_cn = request_data['content_cn']
            detail = request_data['detail']
            detail_cn = request_data['detail_cn']

            user = User.objects.get(open_id=open_id)

            UserNews.objects.create(user=user,
                                    type=news_type,
                                    title=title,
                                    title_cn=title_cn,
                                    content=content,
                                    content_cn=content_cn,
                                    has_read=False,
                                    detail=detail,
                                    detail_cn=detail_cn)

            user_notify_info = UserNotifyInfo.objects.get(user=user)
            user_notify_info.has_news = True
            user_notify_info.news_count = F('news_count') + 1
            user_notify_info.save()
        except Exception as e:
            logger_error.error(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'Error : ' + str(e))
            return Response(result.get_response(), result.get_code())

        return Response(result.get_response(), result.get_code())
예제 #7
0
    def get(self, request, user_id):
        # Response object
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        # Get access token
        try:
            open_id = request.META['HTTP_OPEN_ID']
            access_token = str(
                request.META['HTTP_AUTHORIZATION']).split(' ')[1]
            logger_info.info(open_id + ':' + access_token)
        except Exception as e:
            logger_error.error(str(e))
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED,
                                    'Token or user not found')
            return Response(result.get_response(), result.get_code())

        # Get User object
        try:
            # User data
            user = User.objects.get(id=user_id)
            serializer = UserSerializer(user)

            user_data = serializer.data
            user_data['connection_account'] = json.loads(
                user_data['connection_account'])

            user_open_id = user.open_id

            addresses = UserAddressInfo.objects.filter(user=user)
            serializer = UserAddressInformationSerializer(addresses, many=True)
            address_data = serializer.data
            address_list = list()

            for address in address_data:
                address_list.append(address)

            headers = {'open-id': user_open_id}
            response = requests.get(urlmapper.get_url('COUPON_LIST'),
                                    headers=headers)

            if response.status_code == code.ARIES_200_SUCCESS:
                response_json = response.json()
                coupons = response_json['coupons']
            else:
                coupons = []

            result.set('user', user_data)
            result.set('addresses', address_list)
            result.set('coupons', coupons)
        except ObjectDoesNotExist:
            logger_info.info('User not found')
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'User not found')
        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'Request data error')

        return Response(result.get_response(), result.get_code())
예제 #8
0
    def get(self, request, open_id):
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        # This open id is not open id
        mdn = open_id

        cn_header = False

        # Popup header check
        try:
            accept_lang = request.META['HTTP_ACCEPT_LANGUAGE']
            if 'zh' in accept_lang:
                cn_header = True
        except Exception as e:
            print(e)

        response = requests.get(
            urlmapper.get_url('USER_SMS_VERIFICATION') + open_id)
        if response.status_code != code.ARIES_200_SUCCESS:
            logger_info.info(response.text)
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'Verification info is not found')
            return Response(result.get_response(), result.get_code())

        try:
            user_login_info_count = UserLoginInfo.objects.filter(
                login_type=0, login_key=mdn).count()

            if user_login_info_count == 1:
                user_login_info = UserLoginInfo.objects.get(login_type=0,
                                                            login_key=mdn)
                password = user_login_info.login_value
                masked_password = password[:3] + (len(password) - 3) * '*'
                result.set('password', masked_password)
                result.set('guide_message',
                           'Your password is ' + masked_password)
            else:
                user_count = User.objects.filter(mdn=mdn).count()

                if user_count >= 1:
                    result.set(
                        'password',
                        get_msg(code.ERROR_1301_MDN_ALREADY_EXIST, cn_header))
                    result.set(
                        'guide_message',
                        get_msg(code.ERROR_1301_MDN_ALREADY_EXIST, cn_header))
                else:
                    result.set(
                        'password',
                        get_msg(code.ERROR_1302_MDN_INFO_NOT_FOUND, cn_header))
                    result.set(
                        'guide_message',
                        get_msg(code.ERROR_1302_MDN_INFO_NOT_FOUND, cn_header))
            return Response(result.get_response(), result.get_code())
        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'Member info is not found')
            return Response(result.get_response(), result.get_code())
예제 #9
0
def sms_authentication(login_key, login_value):
    url = urlmapper.get_url('USER_SMS_VERIFICATION')
    payload = {'mdn': login_key, 'verification_code': login_value}
    response = requests.post(url, json=payload)

    if response.status_code != 200:
        raise AuthInfoError

    return True
def read_upcoming_order(open_id, access_token):
    headers = {
        'open-id': open_id,
        'authorization': 'bearer ' + access_token
    }
    payload = {
        'has_upcoming_order': False
    }
    requests.put(urlmapper.get_url('USER_NOTIFICATION'), headers=headers, json=payload)
    def set_delivery_detail(self, cn_header):
        # Shipping method
        self.request_data['shipping_method'] = 1
        if 'delivery_on_site' in self.request_data:
            delivery_on_site = self.request_data['delivery_on_site']
        else:
            delivery_on_site = False
            self.request_data['delivery_on_site'] = False

        if delivery_on_site:
            delivery_type = 2
            self.request_data['shipping_method'] = 2
            self.request_data['shipping_cost'] = 0.0
            self.request_data['delivery_as_fast'] = False
        else:
            self.request_data['shipping_cost'] = 8.0
            delivery_type = self.request_data['shipping_method']

        # add shipping name
        delivery_name = hub_data.get_delivery_service_str(cn_header, delivery_type)
        self.request_data['shipping_name'] = delivery_name

        delivery_price = self.request_data['shipping_cost']

        # Check delivery price
        if float(hub_data.get_shipping_cost(delivery_type)) != float(delivery_price):
            self.logger_info.info('Some cost is incorrect')
            raise DataValidationError('Some costs are incorrect')

        delivery_detail_json = {'delivery_title': hub_data.get_delivery_str(cn_header, delivery_type),
                                'price': delivery_price}
        self.order_details['delivery_detail'] = delivery_detail_json

        delivery_date = self.request_data['delivery_date'].replace('.', '-')
        self.request_data['delivery_date'] = delivery_date

        time_table_delivery_type = delivery_type
        if delivery_on_site:
            time_table_delivery_type = 1

        time_table_address = '{}/{}/{}/{}/{}'.format(
            urlmapper.get_url('TIMETABLE_LIST'), str(self.request_data['hub_id']), delivery_date,
            str(self.request_data['delivery_schedule']), str(time_table_delivery_type)
        )

        response = requests.get(time_table_address)
        response_json = response.json()

        if response.status_code != code.ARIES_200_SUCCESS:
            self.logger_error.error(code.ERROR_3007_DELIVERY_SCHEDULE_INVALID)
            raise BusinessLogicError(message_mapper.get(3007, cn_header), 3007, None)

        self.logger_info.info(response_json)
        self.request_data['shipping_detail'] = json.dumps(response_json['shipping_detail'])
        self.request_data['delivery_start_time'] = response_json['delivery_start_time']
        self.request_data['delivery_end_time'] = response_json['delivery_end_time']
예제 #12
0
def request_create_coupon(open_id, coupon_id):
    request_body = {'open_id': open_id, 'coupon_id': coupon_id}
    response = requests.post(url=urlmapper.get_url('ROULETTE_COUPON'), json=request_body)

    if response.status_code != 200:
        result = False
    else:
        result = True

    return result
def get_admin_token_validate(access_token):
    url = urlmapper.get_url('ADMIN_VALIDATE')
    payload = {'access_token': access_token}
    response = requests.post(url, json=payload)

    if response.status_code != code.ARIES_200_SUCCESS:
        result = False
    else:
        result = True

    return result
예제 #14
0
def get_qq_account_information(login_sns_open_id):
    payload = {'grant_type': 'authorization_code', 'client_id': '1106290901',
               'client_secret': 'WbcNyj80WeBvgoSs', 'code': login_sns_open_id,
               'redirect_uri': 'https://api.viastelle.com/users/signin/callback'}
    response = requests.get(urlmapper.get_url('QQ_ACCESS_TOKEN'), params=payload)
    response_json = response.json()

    if not response_json.get('access_token'):
        raise AuthInfoError

    return response_json
def get_referral_info(user_open_id):
    url = urlmapper.get_url('USER_REFERRAL_INFO')
    body = {'open_id': user_open_id}
    response = requests.post(url=url, json=body)

    if response.status_code == 200:
        response_json = response.json()
    else:
        raise Exception('Request failed')

    return response_json
def get_time_table(hub_id, sales_time):
    query = product_util.get_timetable_query(sales_time)
    url = urlmapper.get_url('TIMETABLE_LIST') + '/' + str(hub_id) + '?' + query
    response = requests.get(url)

    if response.status_code == code.ARIES_200_SUCCESS:
        response_json = response.json()
        result = response_json['timetable']
    else:
        result = []
    return result
예제 #17
0
def check_auth_info_v2(open_id, access_token):
    if open_id is None or access_token is None:
        raise AuthInfoError('Authentication Failed')

    payload = {'open_id': open_id, 'access_token': access_token}
    url = urlmapper.get_url('USER_VALIDATION')

    response = requests.post(url, json=payload)

    if response.status_code != code.ARIES_200_SUCCESS:
        raise AuthInfoError('Authentication Failed')
    def delete(self, request):
        request_data = request.data
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        logger_info.info(request_data)

        # AUthorization check
        try:
            open_id = request.META['HTTP_OPEN_ID']
            access_token = str(request.META['HTTP_AUTHORIZATION']).split(' ')[1]

            url = urlmapper.get_url('TOKEN_VALIDATE')
            headers = {'open-id': open_id, 'authorization': 'bearer ' + access_token}
            response = requests.get(url, headers=headers)

            if response.status_code != 200:
                raise Exception
        except Exception as e:
            print(e)
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED, get_msg(code.ARIES_401_UNAUTHORIZED))
            return Response(result.get_response(), result.get_code())

        # Request data parsing
        try:
            product_id = request_data['product_id']
            order_id = request_data['order_id']

            review = CustomerReview.objects.get(open_id=open_id, product_id=product_id, order_id=order_id)

            # Statics information apply
            payload = {'menu_id': review.menu, 'prev_rate': review.menu_rate}
            statics_result = requests.delete(urlmapper.get_url('MENU_STATICS'), json=payload)
            logger_info.info(statics_result.text)

            review.delete()
            return Response(result.get_response(), result.get_code())

        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid')
            return Response(result.get_response(), result.get_code())
예제 #19
0
def dada_message_to_operation(dada_message):
    ts = calendar.timegm(time.gmtime())
    message = {
        'type': 'notification',
        'domain': 'dada_callback',
        'timestamp': str(ts),
        'payload': json.dumps({'shipping_order_detail': dada_message})
    }

    url = urlmapper.get_url('OPERATION_MESSAGE')

    requests.post(url, json=message)
def update_coupon_count_no_log(open_id, access_token, op, count):
    url = urlmapper.get_url('USER_NOTIFICATION_UPDATE').format(
        'coupon', str(op), str(count))
    headers = {'open-id': open_id, 'Authorization': 'bearer ' + access_token}
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        result = True
    else:
        result = False

    return result
예제 #21
0
    def post(self, request):
        request_data = request.data
        logger_info.info(request_data)

        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        # Operation check
        try:
            access_token = request_data['access_token']

            url = urlmapper.get_url('ADMIN_VALIDATE')
            payload = {'access_token': access_token}
            response = requests.post(url, json=payload)

            if response.status_code != code.ARIES_200_SUCCESS:
                result = ResultResponse(code.ARIES_401_UNAUTHORIZED,
                                        'Token or user not found')
                return Response(result.get_response(), result.get_code())

        except Exception as e:
            logger_error.error(str(e))
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED,
                                    'Error : ' + str(e))
            return Response(result.get_response(), result.get_code())

        try:
            open_id = request_data['open_id']
            address_id = request_data['address_id']

            user = User.objects.get(open_id=open_id)
            serializer = UserSerializer(user)
            user_data = serializer.data

            user_info = UserInfo.objects.get(user=user)
            serializer = UserInfoSerializer(user_info)
            user_info_data = serializer.data

            address_manager = AddressManagerV2(logger_info, logger_error)
            user_address = address_manager.get_address(open_id, address_id)

            if user_address is None:
                user_address = ''

            result.set('user', user_data)
            result.set('user_info', user_info_data)
            result.set('user_address', user_address)

            return Response(result.get_response(), result.get_code())
        except Exception as e:
            logger_error.error(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'Error : ' + str(e))
            return Response(result.get_response(), result.get_code())
예제 #22
0
def get_qq_open_id(qq_access_token):
    payload = {'access_token': qq_access_token}
    response = requests.get(urlmapper.get_url('QQ_OPEN_ID'), params=payload)

    res_text = response.text
    split_res = res_text.split(' ')
    json_result = json.loads(split_res[1])
    response_openid = json_result['openid']

    if not json_result.get('openid'):
        raise AuthInfoError

    return response_openid
예제 #23
0
def request_share_id_validation(share_id):
    url = urlmapper.get_url('SHARE_ID_VALIDATION')
    body = {'share_id': share_id}

    response = requests.post(url, json=body)

    open_id = None

    if response.status_code == 200:
        res_json = response.json()
        open_id = res_json['open_id']

    return open_id
def get_user_information(open_id, access_token):
    payload = {'open_id': open_id, 'access_token': access_token}
    url = urlmapper.get_url('USER_VALIDATION')

    response = requests.post(url, json=payload)

    if response.status_code == code.ARIES_200_SUCCESS:
        response_json = response.json()
        result = (True, response_json)
    else:
        result = (False, None)

    return result
    def delivery_time_validation(self, product_list, accept_lang, os_type, hub_id):
        headers = {'accept-language': accept_lang}
        payload = {'product_list': product_list, 'delivery_schedule': self.request_data['delivery_schedule'],
                   'os_type': os_type, 'hub_id': hub_id}
        response = requests.post(urlmapper.get_url('PRODUCT_VALIDATION'), headers=headers, json=payload)
        response_json = response.json()

        # If quantity of product to purchase quantity is not valid or delivery schedule invalid
        if response.status_code != code.ARIES_200_SUCCESS:
            self.logger_error.error(response_json['error_code'])
            raise BusinessLogicError(response_json['error_message'], None, None)

        return response_json
예제 #26
0
def get_product_info_from_menu(hub_id, menu_id_list, cn_header, os_type):
    target_db = 'aries_cn' if cn_header else 'default'

    url = urlmapper.get_url('PRODUCT_WITH_MENU').format(str(hub_id))
    headers = {'os-type': str(os_type)}
    body = {'target_db': target_db, 'menu_id_list': menu_id_list}

    response = requests.post(url, headers=headers, json=body)

    if response.status_code == 200:
        result = response.json()
    else:
        result = None

    return result
예제 #27
0
def get_time_bomb_info_from_menu(hub_id, accept_lang, os_type):
    url = urlmapper.get_url('TIME_BOMB_INFO').format(str(hub_id))
    headers = {'Accept-Language': accept_lang, 'os-type': str(os_type)}

    result = None

    try:
        response = requests.get(url, headers=headers, timeout=2)
    except Exception as e:
        print(e)
    else:
        if response.status_code == 200:
            result = response.json()

    return result
예제 #28
0
    def update_notification_info(self, open_id, access_token, notify_info):
        url = urlmapper.get_url('NOTIFICATION_COUNT')
        headers = {
            'open-id': open_id,
            'authorization': 'bearer ' + access_token
        }

        notification_response = requests.get(url, headers=headers)

        if notification_response.status_code == code.ARIES_200_SUCCESS:
            notification_json_res = notification_response.json()
            notify_info.coupon_count = notification_json_res['coupon_count']
            notify_info.upcoming_order_count = notification_json_res[
                'upcoming_order_count']
            notify_info.save()
예제 #29
0
    def get_token(self):
        payload = {
            'user_open_id': self.user.open_id,
            'user_account': self.login_account_info
        }
        response = requests.post(urlmapper.get_url('PLATFORM_SERVER'),
                                 json=payload)

        if response.status_code == code.ARIES_200_SUCCESS:
            response_json = response.json()
            token = response_json['token']
            result = (True, token)
        else:
            result = (False, None)

        return result
예제 #30
0
def check_has_event(open_id, access_token):
    headers = {'open-id': open_id, 'Authorization': 'bearer ' + access_token}
    url = urlmapper.get_url('HAS_EVENT')
    try:
        response = requests.get(url, headers=headers, timeout=3)
    except Exception as e:
        print(e)
        return False

    if response.status_code == 200:
        response_json = response.json()
        result = response_json['event_result']
    else:
        result = False

    return result