简体   繁体   English

如何使用 Strapi GraphQL 退回 Stripe 优惠券

[英]How to return Stripe coupons using Strapi GraphQL

I've got a Nuxt app with a Checkout page, and on the backend I'm using Strapi GraphQL.我有一个带有结帐页面的 Nuxt 应用程序,在后端我使用的是 Strapi GraphQL。 I created several coupons in Stripe, and I want to be able to verify the coupons from the Checkout page, but I'm struggling to figure out how to do this.我在 Stripe 中创建了几张优惠券,我希望能够从结帐页面验证优惠券,但我正在努力弄清楚如何做到这一点。 Here's what I have so far:这是我到目前为止所拥有的:

Frontend (Nuxt)前端(Nuxt)

Cart.vue:购物车.vue:

this.$apollo.query({
  query: validateCouponQuery,
  variables: {
    coupon: this.coupon
  }
})

validateCoupon.gql:验证优惠券.gql:

query($coupon: String!) {
  validateCoupon(coupon: $coupon) {
    id
    name
    valid
  }
}

Backend (Strapi): ./order/config/routes.json:后端(Strapi): ./order/config/ routes.json:

{
  "method": "GET",
  "path": "/orders/validateCoupon",
  "handler": "order.validateCoupon",
  "config": {
    "policies": []
  }
}

./order/config/schema.graphql.js: ./order/config/schema.graphql.js:

const { sanitizeEntity } = require('strapi-utils');

module.exports = {
  query: `
    validateCoupon(coupon: String): Order
  `,
  resolver: {
    Query: {
      validateCoupon: {
        resolverOf: 'Order.validateCoupon',
        async resolver(_, { coupon }) {
          const entity = await strapi.services.order.validateCoupon({ coupon });
          return sanitizeEntity(entity, { model: strapi.models.order });
        }
      }
    }
  }
}

./order/controllers/order.js: ./order/controllers/order.js:

'use strict';
require('dotenv').config();

const stripe = require('stripe')(`${process.env.STRIPE_SECRET_KEY}`);

module.exports = {
  validateCoupon: async ctx => {
    const { coupon } = ctx.request.body;
    console.log('request coupon: ', coupon);

    try {
      const coupons = await stripe.coupons.list({ limit: 3 }, function (err, coupons) {
        console.log('err: ', err);
        console.log('coupons: ', coupons);
      });

      return coupons;
    } catch (err) {
      console.error('error validating coupon: ', err)
    }
  }
};

Right now, when I try to run the query in the GraphQL Playground, I get the error strapi.services.order.validateCoupon is not a function .现在,当我尝试在 GraphQL Playground 中运行查询时,我收到错误strapi.services.order.validateCoupon is not a function

I'm fairly new to GraphQL... is there a better way to fetch external data than running a query?我对 GraphQL 还很陌生……有没有比运行查询更好的方法来获取外部数据?

****Update**** ****更新****

I've added my order service, which has gotten rid of that original error.我已经添加了我的订单服务,它已经摆脱了原来的错误。 The issue now is that even though the service appears to be returning the coupon correctly, the const entity in the schema.graphql.js returns undefined for some reason.现在的问题是,即使服务似乎正确返回了优惠券, schema.graphql.js中的const entity由于某种原因返回 undefined。 I wonder if the resolver can't be async/await?我想知道解析器是否不能异步/等待?

./order/services/order.js: ./order/services/order.js:

'use strict';
const stripe = require('stripe')(`${process.env.STRIPE_SECRET_KEY}`);

module.exports = {
  validateCoupon: ({ coupon }) => {
    stripe.coupons.list()
      .then(coupons => {
        return coupons.data.filter(c => {
          return (c.name === coupon && c.valid) ? c : null;
        });
        console.log('found: ', found);
      })
      .catch(err => console.error(err));
  }
};

Well, your code to look up coupons on Stripe looks just fine!好吧,您在 Stripe 上查找优惠券的代码看起来不错! Looks like Strapi expects your service to be at ./order/services/order.js —could it be as simple as that?看起来 Strapi 希望您的服务位于./order/services/order.js — 可以这么简单吗? Your example shows it at ./order/controllers/order.js .您的示例显示在./order/controllers/order.js https://strapi.io/documentation/3.0.0-beta.x/concepts/services.html#custom-services https://strapi.io/documentation/3.0.0-beta.x/concepts/services.html#custom-services

So I ended up creating a Coupon model in the Strapi content builder.所以我最终在 Strapi 内容生成器中创建了一张优惠券 model。 This enabled me to more easily return a Coupon object from my GraphQL query.这使我能够更轻松地从我的 GraphQL 查询中返回优惠券 object。 It's not ideal because I'm having to make sure I create both a Stripe and Strapi coupon object to match, however I also don't anticipate on creating too many coupons in the first place.这并不理想,因为我必须确保创建 Stripe 和 Strapi 优惠券 object 以匹配,但我也不希望首先创建太多优惠券。

My updated code looks like this: schema.graphql.js:我更新的代码如下所示: schema.graphql.js:

const { sanitizeEntity } = require('strapi-utils/lib');

module.exports = {
  query: `
    validateCoupon(coupon: String): Coupon
  `,
  resolver: {
    Query: {
      validateCoupon: {
        description: 'Validate Stripe coupon',
        resolver: 'application::order.order.validateCoupon',
      }
    }
  }
}

./order/controllers/order.js: ./order/controllers/order.js:

'use strict';
require('dotenv').config();

const { sanitizeEntity } = require('strapi-utils');

module.exports = {
  validateCoupon: async ctx => {
    const coupon = ctx.query._coupon;
    const found = await strapi.services.order.validateCoupon({ coupon });
    return sanitizeEntity(found, { model: strapi.models.order });
  }
};

./order/services/order.js: ./order/services/order.js:

'use strict';

const stripe = require('stripe')(`${process.env.STRIPE_SECRET_KEY}`);

module.exports = {
  async validateCoupon({ coupon }) {
    let foundCoupon = null;

    try {
      const coupons = await stripe.coupons.list();
      const found = coupons.data.filter(c => {
        return (c.name === coupon && c.valid) ? c : null;
      });
      if (found) foundCoupon = found[0];
    } catch (err) {
      console.error(err);
    }

    return foundCoupon;
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM