繁体   English   中英

PayPal 按钮和 Webhook 集成

[英]PayPal Buttons and Webhook integration

我有一个 Paypal 按钮设置,代码如下:

  paypal.Buttons({
      createSubscription: function(data, actions) {
        return actions.subscription.create({
          'plan_id': 'P-PLANID'
        });
      },
      onApprove: function(data, actions) {
        // Somehow pass info to Webhook
      }
  }).render('#paypal-button-container');

有没有办法让它与我用BILLING.SUBSCRIPTION.ACTIVATED设置的 webhook 集成?

我刚刚创建了 webhook,但我不确定如何将我的 PayPal 按钮连接到它

您需要使用与按钮相同的 app/client-id 订阅 webhook 事件。 您可以在开发人员仪表板中手动订阅,也可以通过 API 调用进行订阅。 这是文档


您的代码中的此注释没有意义:

// Somehow pass info to Webhook

订阅 webhook 事件通知是您在其他地方进行的一次性初始设置。 这不是您通过按钮执行的操作,它不会以任何方式调用或与按钮交互; webhook 稍后异步发送和处理。

如果您想将一些信息存储为订阅的一部分以供以后协调(例如,与订阅的用户一起,以便您的后端在收到 webhook 时知道该做什么)——那么您可以将custom_id设置为订阅创建。

我的示例本身并不完全是一个 webhook,但它对我很有用。 我在 onApprove function 中调用了onApprove Cloud Function调用,如下所示:

paypal.Buttons({
  createSubscription: function(data, actions) {
    return actions.subscription.create({
      'plan_id': 'P-PLANID'
    });
  },
  onApprove: function(data, actions) {
    const orderID = data.orderID;
    let url = "myCloudFunction?orderID="+orderID;
    //this will verify the purchase and complete order on back end
    fetch(url);
    //carry on with user experince
  }
}).render('#paypal-button-container');

然后使用我的云orderID中的 orderID 验证购买,并更新我的数据库或其他我需要做的事情:

const checkoutNodeJssdk = require('@paypal/checkout-server-sdk');
const functions = require("firebase-functions");

function environment() {
   let clientId = process.env.PAYPAL_CLIENT_ID || 'yourClientID';
   let clientSecret = process.env.PAYPAL_CLIENT_SECRET || 'yourClientSecret';
   return new checkoutNodeJssdk.core.LiveEnvironment(
       clientId, clientSecret
   );
}

function payPalClient() {
   return new checkoutNodeJssdk.core.PayPalHttpClient(environment());
}

exports.completeOrder = functions.https.onRequest((req, res) => {
   const orderID = req.query.orderID;
   let request = new checkoutNodeJssdk.orders.OrdersGetRequest(orderID);
   let order;
   try {
       order = await payPalClient().execute(request);
       console.log(order);
   } catch (err) {
       console.error(err);
       res.send({response: "failed"});
   }

   if (order.result.status === 'APPROVED') {
       //update DB or whatever else needs to happen to complete order
       res.send({response: "success"});
   } else {
       res.send({response: "failed"});
   }
});

您还可以通过将按钮的onApprove function 中返回的数据 object 中的订阅 ID 传递给云 function 来验证订阅是否处于活动状态。 使用以下方法验证订阅:

async function verifySubscription(subscriptionID, callback) {   
   const authUrl = "https://api-m.paypal.com/v1/oauth2/token";
   const subscriptionsUrl = "https://api.paypal.com/v1/billing/subscriptions/" + subscriptionID;
   const clientIdAndSecret = "myClientID:myCLientSecret";
   const base64 = Buffer.from(clientIdAndSecret).toString('base64')
   fetch(authUrl, { 
       method: 'POST',
       headers: {
           'Content-Type': 'application/json',
           'Accept': 'application/json',
           'Accept-Language': 'en_US',
           'Authorization': `Basic ${base64}`,
       },
       body: 'grant_type=client_credentials'
   }).then(function(response) {
       return response.json();
   }).then(function(data) {
       fetch(subscriptionsUrl, { 
           method: 'get', 
           headers: {
             'Authorization': 'Bearer '+data.access_token, 
             'Content-Type': 'application/json'
           }, 
       }).then(function(response) {
           return response.json();
       }).then(function(subscriptionData) {
           console.log("subscriptionData.status: ", subscriptionData.status);
           if (subscriptionData.status === "ACTIVE") {
               callback(true);
           } else {
               callback(false);
           }
       }).catch(function(error) {
           console.log("couldnt verify subscription");
           console.log(error);
           callback(false);
       });
   }).catch(function() {
       console.log("couldnt get auth token");
       callback(false);
   });
}

暂无
暂无

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

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