
Next, add the following to
billing.js.
import stripePackage from "stripe"; import { calculateCost } from "./libs/billing-lib"; import { success, failure } from "./libs/response-lib"; export async function main(event, context) { const { storage, source } = JSON.parse(event.body); const amount = calculateCost(storage); const description = "Scratch charge"; // Load our secret key from the environment variables const stripe = stripePackage(process.env.stripeSecretKey); try { await stripe.charges.create({ source, amount, description, currency: "usd" }); return success({ status: true }); } catch (e) { return failure({ message: e.message }); } } 100 or fewer, we’ll charge $2 and anything more than a 100 is $1 per note. Clearly, our serverless infrastructure might be cheap but our service isn’t!
Configure the API Endpoint
Let’s add a reference to our new API and Lambda function.
Add the following above the
resources: block in the
serverless.yml.
billing: handler: billing.main events: - http: path: billing method: post cors: true authorizer: aws_iam
Make sure this is indented correctly. This block falls under the
functions block.
Commit Our Changes
Let’s quickly commit these to Git.
$ git add . $ git commit -m "Adding a billing API"
Now before we can test our API we need to load our Stripe secret key in our environment.
For help and discussionComments on this chapter
If you liked this post, please subscribe to our newsletter, give us a star on GitHub, and follow us on Twitter.