Paypal не возвращает пользовательскую переменную - PullRequest
0 голосов
/ 14 января 2019

Я пытаюсь завершить транзакцию PayPal, используя PayPal-Rest-SDK, все настроено и работает, однако мне нужно вернуть clientId из PayPal в пути успеха, чтобы сохранить его в моей модели client_feature_payment , Я обнаружил, что мы можем установить «настраиваемое» поле, в котором мы можем установить все, что угодно, и оно будет отправлено PayPal, но этот feautre доступен только в классическом PayPal SDK и недоступен в rest-SDK. Есть ли обходной путь для этого?

/ / Объекты и методы Paypal из rest-sdk:

client_page: {
      args: {
        clientId: {
          type: GraphQLString
        }
      },
      type: ClientType,
      resolve: async (_, args) => {
        if (args.clientId) {
          let clientMongoId = fromGlobalId(args.clientId).id;
          let client = await Client.queryOne("id")
            .eq(clientMongoId)
            .exec();
          let clientName = client.name;
          let clientSecret = client.secret;
      let company = await Company.queryOne("id")
        .eq(client.companyId)
        .exec();
      let companyName = company.name;

      let service = await Service.queryOne("id")
        .eq(client.serviceId)
        .exec();
      let serviceName = service.name;

      let clientFeature = await ClientFeature.query("clientId")
        .eq(clientMongoId)
        .exec();

      let totalFeatures = [];
      let clientFeatureId = [];
      for (let i = 0; i < clientFeature.length; i++) {
        clientFeatureId.unshift(clientFeature[i].id);

        let feature = await Feature.query("id")
          .eq(clientFeature[i].featureId)
          .exec();
        let newFeature;
        feature.map(
          feature =>
            (newFeature = [
              feature.name,
              feature.cost,
              feature.trial,
              feature.frequency
            ])
        );
        totalFeatures.unshift(newFeature);
      }

      let trial, freq;
      let cost = [];
      totalFeatures.map(item => {
        if (item[2] && item[3]) {
          trial = item[2];
          freq = item[3];
        }
        cost.unshift(item[1]);
      });

      const finalCost = cost.reduce((accumulator, currentValue) => {
        return accumulator + currentValue;
      }, 0);
      let paypalFreq;
      let frequencyInterval;
      var isoDate = new Date(Date.now() + 1 * 60 * 1000);

      switch (freq) {
        case "bi-weekly":
          paypalFreq = "DAY";
          frequencyInterval = "7";
          break;
        case "monthly":
          paypalFreq = "MONTH";
          frequencyInterval = "1";
          break;
        case "3 months":
          paypalFreq = "MONTH";
          frequencyInterval = "3";
          break;
        case "6 months":
          paypalFreq = "MONTH";
          frequencyInterval = "6";
          break;
        case "1 year":
          paypalFreq = "YEAR";
          frequencyInterval = "1";
          break;
        default:
          break;
      }

      var billingPlanAttributes = {
        description:
          "Create Plan for Trial & Frequency based payment for features and services used by customer",
        merchant_preferences: {
          auto_bill_amount: "yes",
          cancel_url: "http://localhost:3000/cancel",
          initial_fail_amount_action: "continue",
          max_fail_attempts: "1",
          return_url: "http://localhost:3000/success",
          setup_fee: {
            currency: "USD",
            value: "0"
          }
        },
        name: "Client Services & Features Charge",
        payment_definitions: [
          {
            amount: {
              currency: "USD",
              value: finalCost
            },
            cycles: "0",
            frequency: paypalFreq,
            frequency_interval: frequencyInterval,
            name: "Regular 1",
            type: "REGULAR"
          },
          {
            amount: {
              currency: "USD",
              value: "0"
            },
            cycles: "1",
            frequency: "DAY",
            frequency_interval: trial,
            name: "Trial 1",
            type: "TRIAL"
          }
        ],
        type: "INFINITE"
      };

      var billingPlanUpdateAttributes = [
        {
          op: "replace",
          path: "/",
          value: {
            state: "ACTIVE"
          }
        }
      ];

      var billingAgreementAttr = {
        name: "Fast Speed Agreement",
        description: "Agreement for Fast Speed Plan",
        start_date: isoDate,
        plan: {
          id: "P-0NJ10521L3680291SOAQIVTQ"
        },
        payer: {
          payment_method: "paypal",
          payer_info: {
            payer_id: clientMongoId
          }
        },
        shipping_address: {
          line1: "StayBr111idge Suites",
          line2: "Cro12ok Street",
          city: "San Jose",
          state: "CA",
          postal_code: "95112",
          country_code: "US"
        }
      };

      // Create the billing plan
      let billingPlan = await new Promise((resolve, reject) => {
        paypal.billingPlan.create(
          billingPlanAttributes,
          (error, billingPlan) => {
            if (error) {
              throw error;
            } else {
              resolve(billingPlan);
            }
          }
        );
      });

      // let billingPlan = await billingPlanPromise;

      // Activate the plan by changing status to Active
      let billingAgreementAttributes = await new Promise(
        (resolve, reject) => {
          paypal.billingPlan.update(
            billingPlan.id,
            billingPlanUpdateAttributes,
            (error, response) => {
              if (error) {
                throw error;
              } else {
                billingAgreementAttr.plan.id = billingPlan.id;
                resolve(billingAgreementAttr);
              }
            }
          );
        }
      );

      // Use activated billing plan to create agreement
      let approval_url = await new Promise((resolve, reject) => {
        paypal.billingAgreement.create(
          billingAgreementAttributes,
          (error, billingAgreement) => {
            if (error) {
              throw error;
            } else {
              for (
                var index = 0;
                index < billingAgreement.links.length;
                index++
              ) {
                if (billingAgreement.links[index].rel === "approval_url") {
                  var approval_url = billingAgreement.links[index].href;
                  let newApprovalUrl =
                    approval_url + `&custom=${clientFeatureId}`;
                  resolve(newApprovalUrl);

                  // See billing_agreements/execute.js to see example for executing agreement
                  // after you have payment token
                }
              }
            }
          }
        );
      });

      let data = {
        companyId: companyName,
        serviceId: serviceName,
        name: clientName,
        secret: clientSecret,
        features: totalFeatures,
        endpoint: approval_url
      };

      return Object.assign(data);
    }
  }
},

Путь успеха:

app.get("/success", (req, res) => {
    console.log("This is response", res);
    let paymentToken = req.query.token;
    paypal.billingAgreement.execute(paymentToken, {}, function(
      error,
      billingAgreement
    ) {
      if (error) {
        throw error;
      } else {
        console.log("Billing agreement", billingAgreement);
        let date = billingAgreement.start_date;
        let amountString =
          billingAgreement.plan.payment_definitions[1].amount.value;
        let trial =
          billingAgreement.plan.payment_definitions[0].frequency_interval;
        let frequencyInterval =
          billingAgreement.plan.payment_definitions[1].frequency_interval;
        let frequency = billingAgreement.plan.payment_definitions[1].frequency;
        let totalFrequency = frequencyInterval + " " + frequency;
        let period = [trial, totalFrequency];
        let amount = parseInt(amountString);
        try {
          Payment.create({
            id: uuidv1(),
            date: date,
            amount: amount,
            period: period
          });
        } catch (err) {
          throw new Error(err);
        }
        res.render("index");
      }
    });
  });

1 Ответ

0 голосов
/ 14 января 2019

Моя реализация выглядит совсем иначе, но я могу вывести любые платежные реквизиты. Мой payment.execute () выглядит так:

const express = require("express");
const paypal = require("paypal-rest-sdk");
const app = express;

paypal.configure({
  mode: "sandbox", //sandbox or live
  client_id:
    "...",
  client_secret:
    "..."
});

app.set("view engine", "ejs");

app.get("/", (req, res) => res.render("index"));

app.post("/pay", (req, res) => {
  const create_payment_json = {
    intent: "sale",
    payer: {
      payment_method: "paypal"
    },
    redirect_urls: {
      return_url: "http://localhost:3000/success",
      cancel_url: "http://localhost:3000/cancel"
    },
    transactions: [
      {
        item_list: {
          items: [
            {
              name: "Item",
              sku: "001",
              price: "3.33",
              currency: "USD",
              quantity: 1
            }
          ]
        },
        amount: {
          currency: "USD",
          total: "3.33"
        },
        description:
          "Hope this helps."
      }
    ]
  };

  paypal.payment.create(create_payment_json, function(error, payment) {
    if (error) {
      throw error;
    } else {
      // console.log("Create Payment Response");
      // console.log(payment.id);
      // res.send('test')
      for (let i = 0; i < payment.links.length; i++) {
        if (payment.links[i].rel === "approval_url") {
          res.redirect(payment.links[i].href);
        }
      }
    }
  });
});

app.get("/success", (req, res) => {
  const payerId = req.query.PayerID;
  const paymentId = req.query.paymentId;

  const execute_payment_json = {
    payer_id: payerId,
    transactions: [
      {
        amount: {
          currency: "USD",
          total: "3.33"
        }
      }
    ]
  };

  paypal.payment.execute(paymentId, execute_payment_json, function(
    error,
    payment
  ) {
    if (error) {
      console.log(error.response);
      throw error;
    } else {
      console.log(JSON.stringify(payment));   
    }
  });
});

app.get("/cancel", (req, res) => {
  res.send("Cancelled");
});

app.listen(3000, () => console.log("Server Started"));
...