Home > Software engineering >  Strapi v4 with stripe
Strapi v4 with stripe

Time:07-04

The problem I have is that I cannot create the order with that data, it does not register anything in strapi(BACKEND), if it goes to stripe but in strapi v4 it does not register the content-type order, so I want to know what I am doing wrong since strapi v4 is recent and I haven't found how to implement it with next and stripe; I also leave how I make the request from the client (front end) strapi:v4.2.0 node:v16.11.0 BACKEND

    path: order/controller/order.js
    const { createCoreController } = require("@strapi/strapi").factories;
    
    const stripe = require("stripe")(
      "sk_test_keyxxxxxxxxxxxxxxxx"
    );
    
    module.exports = createCoreController("api::order.order", ({ strapi }) => ({
      async create(ctx, { files } = {}) {
        
        
        
    
        const ctxData = ctx.request.body;
    
        
        const user = ctx.state.user;
    
        
        const {
          data: { token, game, idUser, addressShipping },
        } = ctxData;
    
        let Payment = 0;
        let gameId = 0;
        game.forEach((product) => {
          Payment =
            Payment  
            product.attributes.price -
            Math.floor(product.attributes.price * product.attributes?.discount) /
              100;
          gameId = product.id;
        });
    
        const totalPayment = Math.floor(Payment * 100);
        console.log(gameId);
        console.log(ctxData);
    
        const charge = await stripe.charges.create({
          amount: totalPayment,
          currency: "usd",
          source: token.id,
          description: `ID usuario: ${idUser}, Username:${
            user.username
          }, Nombre Completo:${" "   user.name   ","   user.lastname}`,
        });  const entity = await strapi.service("api::order.order").create({
          data: {
            game: gameId,
            user: user.id,
            totalPayment,
            idPayment: charge.id,
            addressShipping,
          },
        }); 
 
            const entry = await strapi.query("order").create(entity);
            const sanitizedEntity = await this.sanitizeOutput(entry, ctx);
            return this.transformResponse(sanitizedEntity);  },
}));

############################################################################################## From here I have the problem that the order is not created in strapi, I only register with stripe but with strapiv4 it does not create the order, so I would like to know what I am doing wrong greetings. ##############################################################################################

    const entity = await strapi.service("api::order.order").create({
          data: {
            game: gameId,
            user: user.id,
            totalPayment,
            idPayment: charge.id,
            addressShipping,
          },
        });  
         const entry = await strapi.query("order").create(entity);
         const sanitizedEntity = await this.sanitizeOutput(entry, ctx);
         return this.transformResponse(sanitizedEntity);  
},
}));

##############################################################################################

############################################################################################## FRONT END: Api Request ##############################################################################################

export async function paymentCardApi(token, products, idUser, address, logout) {
  try {
    const addressShipping = address.attributes;
    delete addressShipping.user;
    delete addressShipping.createdAt;

    const url = `${BASE_PATH}/api/orders`;
    const params = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },

      body: JSON.stringify({
        data: { token, game: products, user: idUser, addressShipping },
      }),
    };
    const result = await authFetch(url, params, logout);
    return result;
  } catch (error) {
    console.log(error);
  }
}

############################################################################################################################################################################################

I hope someone can guide me and tell me why I was wrong and a solution more than anything because I am a junior; in this and I'm starting in this world of full stack programming, thanks in advance ############################################################################################## ############################################################################################## enter image description here

CodePudding user response:

SOLVED: I had several errors, the first one was in question of the documentation since I wanted to implement it as if it were v3 when in v4 it is very different. I read the documentation and did several tests at the end, I will leave my pro code if someone works for him and I want to implement it in some project I could

################################################################################# ################################################################################# "use strict";

/**
 *  order controller
 */

################################################################################# #################################################################################

const { createCoreController } = require("@strapi/strapi").factories;

const stripe = require("stripe")(
  "sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);

module.exports = createCoreController("api::order.order", ({ strapi }) => ({
  async create(ctx, { files } = {}) {
    const ctxData = ctx.request.body;

    const dataUser = ctx.state.user;

    const {
      data: { token, game, user, addressShipping },
    } = ctxData;

    let Payment = 0;
    let gameId = 0;
    game.forEach((product) => {
      Payment =
        Payment  
        product.attributes.price -
        Math.floor(product.attributes.price * product.attributes?.discount) /
          100;
      gameId = product.id;
    });


    let gameData2 = game.map(function (products) {
      return `
      Nombre del Producto: ${products.attributes.title},
      Precio normal: ${products.attributes.price},  
      Descuento: %${products.attributes.discount}, 
      Precio final: ${
        products.attributes.price -
        (products.attributes.price * products.attributes.discount) / 100
      }; `;
    });

    const totalPayment = Math.floor(Payment * 100);

    const idusuario = JSON.stringify(ctxData.data.user);

    const charge = await stripe.charges.create({
      amount: totalPayment,
      currency: "usd",
      source: token.id,
      description: `ID usuario: ${idusuario}, Username: ${
        dataUser.username
      }, Nombre Completo: ${" "   dataUser.name   ","   dataUser.lastname}, 
      Orden:    
       ${gameData2}
      Precio Total de la orden: $ ${Payment.toFixed(2)} usd
      `,
    });


    let createOrder = [];
    for await (const product of game) {
      const datos = {
        data: {
          game: product.id,
          user: idusuario,
          totalPayment: Payment.toFixed(2),
          idPayment: charge.id,
          adressesShipping: addressShipping,
        },
      };

      const validData = await strapi.service("api::order.order").create(datos);
      createOrder.push(validData);
    }

    const sanitizedEntity = await this.sanitizeOutput(createOrder, ctx);

    return this.transformResponse(sanitizedEntity);
  },
}));
  • Related