Exemple #1
0
    def post(self, request):
        # input validation
        input_serializer = LoginSerializer(data=request.data)
        input_serializer.is_valid(raise_exception=True)
        channel = input_serializer.validated_data['channel']
        code = input_serializer.validated_data['code']

        if channel == config.PAY_CHANNELS.WECHAT:
            try:
                result = client.UseCase.wechat_login(code,
                                                     request.token_session)
            except LoginError:
                raise raise_with_code(
                    WeixinLoginUnavailable(),
                    error_codes.service_unavailable_weixin_login)  # 503
        elif channel == config.PAY_CHANNELS.ALIPAY:
            try:
                result = client.UseCase.alipay_login(code,
                                                     request.token_session)
            except LoginError:
                raise raise_with_code(
                    AlipayLoginUnavailable(),
                    error_codes.service_unavailable_alipay_login)  # 503
        else:
            raise raise_with_code(InvalidParameter(),
                                  error_codes.invalid_payment_channel)

        output_serializer = LoginSerializer({
            'access_token': result['token'],
            'client': result['client']
        })

        return Response(output_serializer.data)
Exemple #2
0
    def post(self, request):
        input_serializer = PaymentCancelRequestSerializer(data=request.data)
        input_serializer.is_valid(raise_exception=True)

        payment_serial_number = input_serializer.validated_data[
            'payment_serial_number']
        try:
            payment = Payment.objects.get(serial_number=payment_serial_number)
        except Payment.DoesNotExist:
            raise raise_with_code(DataNotFound(),
                                  error_codes.payment_not_found)

        if payment.client_id != request.user.id:
            raise raise_with_code(DataNotFound(),
                                  error_codes.payment_not_found)

        if payment.status != config.PAYMENT_STATUS.UNPAID:
            raise raise_with_code(InvalidStatus(),
                                  error_codes.invalid_payment_status)

        new_coupon = None
        if input_serializer.validated_data[
                'pay_channel'] == config.PAY_CHANNELS.WECHAT:
            new_coupon = self.wechat_usecases().cancel_order(payment)
        elif input_serializer.validated_data[
                'pay_channel'] == config.PAY_CHANNELS.ALIPAY:
            new_coupon = self.alipay_usecases().cancel_order(payment)

        if new_coupon:
            output_serializer = CouponSerializer(new_coupon)
            return Response({'new_coupon': output_serializer.data})
        else:
            return Response({'new_coupon': None})
Exemple #3
0
    def post(self, request):
        input_serializer = PaymentPollResultRequestSerializer(data=request.data)
        input_serializer.is_valid(raise_exception=True)

        payment_serial_number = input_serializer.validated_data['payment_serial_number']
        try:
            payment = Payment.objects.get(serial_number=payment_serial_number)
        except Payment.DoesNotExist:
            raise raise_with_code(DataNotFound(), error_codes.payment_not_found)

        if payment.client_id != request.user.id:
            raise raise_with_code(DataNotFound(), error_codes.payment_not_found)

        if payment.status == config.PAYMENT_STATUS.UNPAID:
            return Response({
                'payment': {
                    'status': config.PAYMENT_STATUS.UNPAID
                }
            })

        if payment.status != config.PAYMENT_STATUS.FROZEN:
            raise raise_with_code(InvalidStatus(), error_codes.invalid_payment_status)

        longitude = input_serializer.validated_data.get('longitude', None)
        latitude = input_serializer.validated_data.get('latitude', None)
        accuracy = input_serializer.validated_data.get('accuracy', None)

        coupons = PaymentBaseUseCases.grant_coupons(payment, longitude, latitude, accuracy)

        output_serializer = PaymentResultSerializer(dict(payment=payment, coupons=coupons))
        return Response(output_serializer.data)
Exemple #4
0
    def authenticate(self, request):
        token_session = request.token_session
        token_session.set_namespace(consts.token_namespace)

        if request._request.method == 'OPTIONS':
            return '', ''

        if token_session.is_empty():  # token没有上报
            raise_with_code(exceptions.NotAuthenticated(),
                            error_codes.auth_failed_token_missing)  # 401

        client = self.get_client(token_session)

        return client, token_session.token
Exemple #5
0
    def post(self, request):
        input_data = dict(**request.data, client_id=request.user.id)
        input_serializer = PlaceOrderRequestSerializer(data=input_data)
        input_serializer.is_valid(raise_exception=True)

        client = input_serializer.validated_data['client']
        merchant = input_serializer.validated_data['merchant']
        order_price = input_serializer.validated_data['order_price']
        coupon = input_serializer.validated_data.get('coupon', None)
        channel = input_serializer.validated_data['channel']

        if channel == config.PAY_CHANNELS.ALIPAY:
            try:
                result = self.alipay_usecases().place_order(
                    client=client,
                    merchant=merchant,
                    coupon=coupon,
                    order_price=order_price,
                    notify_url=request.build_absolute_uri('/').strip("/") +
                    reverse('alipay_payment_callback'))
            except (db.DatabaseError, ApiRequestError, ApiReturnedError) as e:
                logger.error('Placing alipay order error:{}'.format(repr(e)))
                raise raise_with_code(
                    PlaceOrderError(),
                    error_codes.service_error_when_placing_order)
            else:
                return Response(data=result)
        elif channel == config.PAY_CHANNELS.WECHAT:
            client_ip, _ = get_client_ip(request._request)
            try:
                result = self.wechat_usecases().place_order(
                    client=client,
                    merchant=merchant,
                    coupon=coupon,
                    order_price=order_price,
                    client_ip=client_ip,
                    notify_url=request.build_absolute_uri('/').strip("/") +
                    reverse('wechat_payment_callback'))
            except (db.DatabaseError, ApiRequestError, ApiReturnedError) as e:
                logger.error('Placing wechat order error:{}'.format(repr(e)))
                raise raise_with_code(
                    PlaceOrderError(),
                    error_codes.service_error_when_placing_order)
            else:
                return Response(data=result)
Exemple #6
0
    def get_client(self, token_session, empty_allowed=False):
        try:
            client_id = token_session[consts.client_session_key]
        except KeyError:  # token过期已从cache中删除
            if empty_allowed:
                return None
            else:
                raise_with_code(exceptions.AuthenticationFailed(),
                                error_codes.auth_failed_token_expired)

        try:
            client = Client.objects.get(pk=client_id)
        except Client.DoesNotExist:  # token无效
            token_session.delete()
            raise_with_code(exceptions.AuthenticationFailed(),
                            error_codes.auth_failed_token_invalid)

        return client
Exemple #7
0
    def get(self, request):
        input_serializer = GetMerchantInfoRequestSerializer(
            data=request._request.GET)
        input_serializer.is_valid(raise_exception=True)

        uuid = input_serializer.validated_data['uuid']
        try:
            qr_code = PaymentQRCode.objects.prefetch_related('merchant').get(
                uuid=uuid)
            merchant = qr_code.merchant
        except PaymentQRCode.DoesNotExist:
            raise raise_with_code(DataNotFound(),
                                  error_codes.payment_uuid_not_found)
        except Exception:  # TODO catch specific exception
            raise raise_with_code(DataNotFound(),
                                  error_codes.no_merchant_bind_with_uuid)

        output_serializer = MerchantSerializer(merchant)
        return Response(output_serializer.data)