【发布时间】:2019-06-24 09:24:32
【问题描述】:
在我的 VueJS 电子商务应用程序中单击“结帐”按钮后,将在我的 Firebase“订单”子节点中创建一个包含订单参数的新“订单”字段。我已经创建了一个实时数据库 onCreate 'newBuyerOrder' 功能,一旦创建了新的“订单”字段,就会向用户发送一封电子邮件,通知他这个新订单。现在,我还想调用我使用 HTTPs onRequest 函数构建的 REST API“/checkout”,以通过 Paypal REST SDK 处理订单。我该怎么做?
我尝试过的一种解决方法是构建 HTTPs onCall 函数,客户端浏览器可以调用该函数以使用订单参数通过 Paypal 处理订单,并使用“newBuyerOrder”onCreate 函数单独发送电子邮件。但不幸的是,HTTPs onCall 不允许客户端重定向。而且,你瞧,在进行 Paypal REST 调用时需要客户端重定向,因此 HTTPs onCall 不适用于我的目的。
在函数/package.json中
"dependencies": {
"@sendgrid/mail": "^6.3.1",
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.1.0",
"paypal-rest-sdk": "^1.8.1"
}
在函数/src/index.ts中
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as sendgrid from '@sendgrid/mail'
import * as paypal from 'paypal-rest-sdk'
// init firebase admin
admin.initializeApp()
// set sendgrid api in function config
const SENDGRID_API_KEY = ...
// set paypal api in function config
paypal.configure({
...
});
// setup paypal payment object and redirect user to paypal payment
page
export const checkout = functions.https.onRequest((req, res) => {
// 1.Set up a payment information object, Build PayPal payment
request
const payReq = JSON.stringify({
...
})
// 2.Initialize the payment and redirect the user.
paypal.payment.create(payReq, (error, payment) => {
if (error) {
// handle error
} else {
// redirect to paypal approval link
for (let i = 0; i < payment.links.length; i++) {
if (payment.links[i].rel === 'approval_url') {
res.redirect(302, payment.links[i].href)
}
}
}
})
})
// send email and trigger paypal checkout api given new buyer order
export const newBuyerOrder = functions.database
.ref('users/{userId}/orders/{orderId}')
.onCreate((snapshot, context) =>
// expected solution to call 'checkout' REST API from above
// send email via sendgrid
const msg = {...}
return sendgrid.send(msg)
})
我希望在实时数据库中创建新的订单字段并且客户端被重定向到 Paypal 批准页面后调用“/checkout”API。
【问题讨论】:
标签: firebase vuejs2 google-cloud-functions paypal-rest-sdk