Как использовать Mollie Api с облачными функциями Firebase

Мне может понадобиться помощь в настройке API-интерфейса node.js от mollie с облачными функциями Firebase. Я пытался использовать части руководства по настройке облачной функции PayPal, но пока не заработал. Я новичок в облачных функциях и node.js, поэтому мне трудно это сделать. Я использую жестко закодированные платежные свойства для целей тестирования. Я использую пламенную подписку, чтобы иметь возможность выполнять запросы к службам, не относящимся к Google. Код, который у меня есть до сих пор:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
Mollie = require("mollie-api-node");
mollie = new Mollie.API.Client;
mollie.setApiKey("test_GhQyK7Gkkkkkk**********");
querystring = require("querystring");
fs = require("fs");

exports.pay = functions.https.onRequest((req, res) => {

    console.log('1. response', res)
mollie.payments.create({
    amount:      10.00,
    method: Mollie.API.Object.Method.IDEAL,
    description: "My first iDEAL payment",
    redirectUrl: "https://dummyse-afgerond",
    webhookUrl:  "https://us-c90e9d.cloudfunctions.net/process",
    testmode: true
}, (payment)=> {
    if (payment.error) {
        console.error('errrr' , payment.error);
        return response.end();
      }
    console.log('3. payment.getPaymentUrl()', payment.getPaymentUrl());
    res.redirect(302, payment.getPaymentUrl());
});

});

exports.process = functions.https.onRequest((req, res) => {

let _this = this;
this.body = "";
req.on("data", (data)=> {
    console.log('_this.body += data', _this.body += data)
  return _this.body += data;
});
req.on("end", ()=> {
    console.log('hier dan?')
  let mollie, _ref;
  _this.body = querystring.parse(_this.body);
  if (!((_ref = _this.body) !== null ? _ref.id : void 0)) {
    console.log('res.end()', res.end())
    return res.end();
  }
})

    mollie.payments.get(
        _this.body.id
    , (payment) => {

        if (payment.error) {
            console.error('3a. err', payment.error);
            return response.end();
          }

        console.log('4a. payment', payment);
        console.log('5a. payment.isPaid()', payment.isPaid());


        if (payment.isPaid()) {
          /*
            At this point you'd probably want to start the process of delivering the
            product to the customer.
          */
            console.log('6a. payment is payed!!!!!!!!!!')
        } else if (!payment.isOpen()) {
          /*
            The payment isn't paid and isn't open anymore. We can assume it was
            aborted.
          */
         console.log('6a. payment is aborted!!!!!!!!!!')
        }
        res.end();
    });
});

это руководство по API mollies: https://github.com/mollie/mollie-api-node< /а>

это руководство по облачным функциям PayPal: https://github.com/firebase/functions-samples/tree/master/paypal

ОБНОВЛЕНИЕ: я обновил код. Ошибка, которую я получаю сейчас, заключается в том, что все свойства платежной переменной не определены в функции procces (webhook). и функция payment.isPaid() говорит false, хотя должна говорить true.


person Sam van beastlo    schedule 25.03.2018    source источник


Ответы (1)


Я сделал то же самое, когда впервые попытался заставить Молли работать в облачных функциях Firebase, это:

let _this = this;
this.body = "";
req.on("data", (data)=> {
    console.log('_this.body += data', _this.body += data)
  return _this.body += data;
});
req.on("end", ()=> {
    console.log('hier dan?')
  let mollie, _ref;
  _this.body = querystring.parse(_this.body);
  if (!((_ref = _this.body) !== null ? _ref.id : void 0)) {
    console.log('res.end()', res.end())
    return res.end();
  }
})

не обязательно.

моя конечная точка веб-перехватчика намного проще, напрямую используя запрос и ответ, которые обеспечивают функции:

exports.paymentsWebhook = functions.https.onRequest((request, response) => {
// ...
console.log("request.body: ", request.body);
console.log("request.query: ", request.query);
mollie.payments.get(request.body.id, function (payment) {
    console.log("payment", payment);
    if (payment.error) {
        console.error('payment error: ', payment.error);
        response.end();
    }
    //checking/processing the payment goes here...
    response.end();
});
});
person Mike Verhees    schedule 27.03.2018
comment
ты лучший :) - person Sam van beastlo; 28.03.2018