Django Rest Framework and Stripe, best practice?

I am struggling with philosophical issues in my DRF framework using the payament Stripe handler. I am selling a product with the django Product model through my DRF REST API. I am wondering if I should create a Product and then process the payment in my create view as follows:

 class ProductViewSet(viewsets.ModelViewSet): ... def create(self, request): serializer = ProductSerializer(data=request.data) serializer.is_valid(raise_exception=True) product = serializer.save() try: response = stripe.Charge.create( amount=product.cost, currency="usd", source=request.data["token"], # Done with Stripe.js description="Product" ) product.charge_id = response.charge_id ... 

or instead, if I have to process the payout in the Product serializer :

 class ProductSerializer(serializers.Serializer): ... def create(self, validated_data): product = Product.objects.create(**validated_data) # Will raise an Excetpion and stop the creation: response = stripe.Charge.create( amount=product.cost, currency="usd", source=validated_data["token"], # Done with Stripe.js description="Product" ) return product 

Which one is better? Or, will I completely miss the point and have to do it differently?

Secondly, is there a way to embed Stripe.js and the required form in the browser template for the create route so that I can test my REST without the need for any external interface?

thanks for the help

+5
source share
1 answer

In my opinion, the right approach is a combination of the two approaches provided, because you have to send the Stripe request to the ModelViewSet class, but save the Product object only after a successful service response.

Otherwise, if the service response fails, I will refuse every database operation (with Django 1.6+ you can do this using transaction.atomic() documented here ).

I don’t like your second approach, because, according to the DRF documentation about the create serializers.Serializer method, this method should only return a new Entity instance, taking into account the verified data, so I would not add another business logic.

As for the second question, I would structure the create method to use the injected layout object for the Stripe request, so you can check your code for any interaction with the external interface (obviously, this way you do not do this integration test, but unit test) .

+1
source

Source: https://habr.com/ru/post/1214224/


All Articles