aws-lambda#Callback TypeScript Examples
The following examples show how to use
aws-lambda#Callback.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: addOrder.ts From Stripe-shop-backend with MIT License | 6 votes |
addOrder: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: Order = JSON.parse((event as APIGatewayEvent).body);
const timestamp = new Date().getTime();
const params: OrdersTable = {
TableName: process.env.DYNAMODB_TABLE_ORDERS,
Item: {
orderId: uuid.v1(),
customerId: data.customerId,
products: data.products,
createdAt: timestamp,
updatedAt: timestamp,
status: "ordered",
},
};
dynamoDb.put(params, (error, result) => {
// handle potential errors
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t create an order', error );
}
return successHandler(callBack, result);
});
}
Example #2
Source File: index.ts From cdk-ssm-document with Apache License 2.0 | 6 votes |
handler = function (
event: LambdaEvent = {},
context: Context,
callback: Callback
) {
event = fixBooleanParameters(event as DocumentEvent);
new CustomResource(event, context, callback, logger)
.onCreate(Create)
.onUpdate(Update)
.onDelete(Delete)
.handle(event);
}
Example #3
Source File: index.ts From cdk-ec2-key-pair with Apache License 2.0 | 6 votes |
handler = function (
event: LambdaEvent,
context: Context,
callback: Callback
) {
new CustomResource(context, callback, logger)
.onCreate(Create)
.onUpdate(Update)
.onDelete(Delete)
.handle(event);
}
Example #4
Source File: refund-payment.ts From sleekypay with MIT License | 6 votes |
exports.handler = async function (
event: APIGatewayEvent,
context: Context,
callback: Callback) {
const requestBody: RefundPayload = JSON.parse(event.body);
console.log(`Refunding ${requestBody.amount}$ on payment ${requestBody.paymentId}.`);
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
refundId: uuid(),
})
};
}
Example #5
Source File: payment-methods.ts From sleekypay with MIT License | 6 votes |
exports.handler = async function (event: APIGatewayEvent, context: Context, callback: Callback) {
// Get request's body
const request = JSON.parse(event.body)
const API_URL = process.env.API_URL || 'https://localhost:12666';
const SITE_URL = process.env.URL || 'http://localhost:3000';
// Validate that the request is coming from Snipcart
const response = await fetch(`${API_URL}/api/public/custom-payment-gateway/validate?publicToken=${request.PublicToken}`)
// Return 404 if the request is not from Snipcart
if (!response.ok) return {
statusCode: 404,
body: ""
}
// Create payment method list
let paymentMethodList: SnipcartPaymentMethod[] = [{
id: 'sleeky_pay',
name: 'SleekyPay',
checkoutUrl: `${SITE_URL}/index.html`,
}]
// Return available payment methods
return {
statusCode: 200,
body: JSON.stringify(paymentMethodList)
};
}
Example #6
Source File: listener.ts From Stripe-shop-backend with MIT License | 6 votes |
webhookListener: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
console.log({ "Webhook data": data })
return successHandler(callBack, {
received: true,
});
}
Example #7
Source File: connect.ts From Stripe-shop-backend with MIT License | 6 votes |
createTerminalConnection: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const config: Stripe.StripeConfig = {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
};
const stripe = new Stripe(process.env.STRIPE_API_KEY, config);
console.log('config', process.env);
try {
const terminalToken = await stripe.terminal.connectionTokens.create();
console.log('terminalToken', terminalToken);
return successHandler(callBack, {
success: true,
message: 'Terminal Connection Created!',
terminalToken: terminalToken,
});
} catch (err) {
return errorHandler(callBack, 'Terminal Connection FAILED!', err);
}
}
Example #8
Source File: capture.ts From Stripe-shop-backend with MIT License | 6 votes |
capturePaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const config: Stripe.StripeConfig = {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
};
const stripe = new Stripe(process.env.STRIPE_API_KEY, config);
console.log('config', config);
const data = JSON.parse((event as APIGatewayEvent).body);
try {
const paymentIntent = await stripe.paymentIntents.capture(data.pi_id);
console.log('paymentIntent capture', paymentIntent);
return successHandler(callBack,{
success: true,
message: 'SUCCESS payment intent captured!',
paymentIntent: paymentIntent,
});
} catch (err) {
return errorHandler(callBack, 'FAILURE payment intent not captured!', err);
}
}
Example #9
Source File: getPaymentIntents.ts From Stripe-shop-backend with MIT License | 6 votes |
getPaymentIntents: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const limit: number = 10;
const paymentIntents = await stripe.paymentIntents.list(
{
limit,
}
);
return callBack(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'List first ' + limit + ' Payment Intents!',
PaymentIntent: paymentIntents,
},
null,
2,
),
});
}
Example #10
Source File: createPaymentIntent.ts From Stripe-shop-backend with MIT License | 6 votes |
createPaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const requestData: any = JSON.parse((event as APIGatewayEvent).body);
const results = validatePaymentIntent(requestData);
if (! results.isValid) {
return errorHandler(
callBack,
'ERROR The PaymentIntent contains invalid data!',
results.errors,
);
}
try {
const paymentIntent = await stripe.paymentIntents.create(results.params);
return successHandler(
callBack,
{
message: 'Payment Intent Created!',
PaymentIntent: paymentIntent,
});
}
catch(error) {
return errorHandler(
callBack,
'ERROR Payment Intent Creation FAILED!',
error
);
}
}
Example #11
Source File: getOrder.ts From Stripe-shop-backend with MIT License | 6 votes |
getOrder: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_ORDERS,
Key: {
orderId: data.orderId,
},
};
dynamoDb.get(params, (error, result) => {
// handle potential errors
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the order', error );
}
// create a response
return successHandler(callBack, result);
});
}
Example #12
Source File: lambda.ts From iplocate with MIT License | 6 votes |
handler = (
event: APIGatewayProxyEvent,
context: Context,
cb: Callback
) => {
context.callbackWaitsForEmptyEventLoop = false;
app.ready((e) => {
if (e) return console.error(e.stack || e);
awsServerlessExpress.proxy(server, event, context, "CALLBACK", cb);
});
}
Example #13
Source File: importCustomers.ts From Stripe-shop-backend with MIT License | 6 votes |
importCustomers: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: ImportCustomers = JSON.parse((event as APIGatewayEvent).body);
const params: CustomerTable = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
};
const errors: string[] = [];
const results: string[] = [];
for(let i = 0; i< data.Count; i++) {
params.Item = data.Items[i];
dynamoDb.put(params, (error, result) => {
if (error) {
errors.push(params.Item.name);
}
else {
results.push(params.Item.name);
}
});
}
return successHandler(callBack, { errors, results });
}
Example #14
Source File: getCustomers.ts From Stripe-shop-backend with MIT License | 6 votes |
getCustomers: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
Select: 'ALL_ATTRIBUTES',
};
dynamoDb.scan(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the customer', error );
}
return successHandler(callBack, result);
});
}
Example #15
Source File: getCustomer.ts From Stripe-shop-backend with MIT License | 6 votes |
getCustomer: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
Key: {
customerId: data.customerId,
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the customer', error );
}
return successHandler(callBack, result);
});
}
Example #16
Source File: addCustomer.ts From Stripe-shop-backend with MIT License | 6 votes |
addCustomer: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: CustomerInput & saveCustomer = JSON.parse((event as APIGatewayEvent).body);
console.log('incomming data', data);
const validCustomer: validCustomer = validateCustomer(data);
if (! validCustomer.isValid) {
return errorHandler(callBack, 'ERROR: Customer contains invalid data.', validCustomer.error );
}
try {
const stripeCustomer = (data.isSaveCustomer === 1) && await upsertToStripe(validCustomer);
validCustomer.params.StripeCustomerId = (data.isSaveCustomer) ? stripeCustomer.id : '';
const params: CustomerTable = {
TableName: process.env.DYNAMODB_TABLE_CUSTOMERS,
Item: validCustomer.params,
};
const savedData = await upsert(params);
console.log('savedData', savedData);
return successHandler(
callBack,
{
message: 'Stripe Customer Created!',
id: params.Item.customerId,
stripeCustomer: stripeCustomer,
});
}
catch(error) {
return errorHandler(
callBack,
'ERROR Customer Creation FAILED!',
error
);
}
}
Example #17
Source File: importProducts.ts From Stripe-shop-backend with MIT License | 6 votes |
importProducts: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: ImportProduct = JSON.parse((event as APIGatewayEvent).body);
const params: ProductTable = {
TableName: process.env.DYNAMODB_TABLE_PRODUCTS,
};
const errors: string[] = [];
const results: string[] = [];
for(let i = 0; i< data.Count; i++) {
params.Item = data.Items[i];
dynamoDb.put(params, (error, result) => {
if (error) {
errors.push(params.Item.name);
}
else {
results.push(params.Item.name);
}
});
}
return successHandler(callBack, { errors, results });
}
Example #18
Source File: getProducts.ts From Stripe-shop-backend with MIT License | 6 votes |
getProducts: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const limit: number = 10;
const params = {
TableName: process.env.DYNAMODB_TABLE_PRODUCTS,
Select: 'ALL_ATTRIBUTES',
};
console.log('inside getProducts', params);
dynamoDb.scan(params, (error, result) => {
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the products.', error );
}
return successHandler(callBack, result);
});
}
Example #19
Source File: addProduct.ts From Stripe-shop-backend with MIT License | 6 votes |
addProduct: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: Product = JSON.parse((event as APIGatewayEvent).body);
const timestamp = new Date().getTime();
const params: ProductTable = {
TableName: process.env.DYNAMODB_TABLE_PRODUCTS,
Item: {
productId: uuid.v1(),
name: data.name,
description: data.description,
amount: data.amount,
currency: 'cad',
createdAt: timestamp,
updatedAt: timestamp,
},
};
dynamoDb.put(params, (error, result) => {
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t add the Product.', error );
}
return successHandler(callBack, { productId: params.Item.productId });
});
}
Example #20
Source File: getCarts.ts From Stripe-shop-backend with MIT License | 6 votes |
getCarts: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const items = await getCustomerItems(data.customerId);
return successHandler(
callBack,
items,
);
}
Example #21
Source File: addCartItem.ts From Stripe-shop-backend with MIT License | 6 votes |
addCartItem: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const uuid = require('uuid');
const data: PostCartItem = JSON.parse((event as APIGatewayEvent).body);
const timestamp = new Date().getTime();
const params: CartTable = {
TableName: process.env.DYNAMODB_TABLE_CARTITEMS,
Item: {
cartItemId: uuid.v1(),
customerId: (data.customer) ?? uuid.v1(),
productId: data.item,
quantity: 1,
createdAt: timestamp,
updatedAt: timestamp,
},
};
dynamoDb.put(params, (error, result) => {
if (error) {
return errorHandler(callBack, 'ERROR: Couldn\'t add the Cart Item.', error );
}
return successHandler(callBack, {
cartItemId: params.Item.cartItemId,
customerId: params.Item.customerId,
});
});
}
Example #22
Source File: importBusinesses.ts From Stripe-shop-backend with MIT License | 6 votes |
importBusinesses: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data: ImportBusinesses = JSON.parse((event as APIGatewayEvent).body);
const errors: any[] = [];
const results: any[] = [];
data.Items.map(async (business) => {
try {
const validBusiness = validateBusiness(business);
if (!validBusiness.isValid) {
throw (validBusiness.errors);
}
const params: BusinessTable = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Item: validBusiness.params,
};
const result = upsert(params);
results.push(result);
} catch (e) {
errors.push({
message: 'Failed to insert ' + business.businessName,
error: e,
});
}
});
return successHandler(callBack, {errors, results});
}
Example #23
Source File: getBusinesses.ts From Stripe-shop-backend with MIT License | 6 votes |
getBusinesses: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Select: 'ALL_ATTRIBUTES',
};
dynamoDb.scan(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the business', error );
}
return successHandler(callBack, result);
});
}
Example #24
Source File: getBusiness.ts From Stripe-shop-backend with MIT License | 6 votes |
getBusiness: Handler = (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const data = JSON.parse((event as APIGatewayEvent).body);
const params = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Key: {
businessId: data.businessId,
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
return errorHandler(callBack, 'ERROR: Couldn\'t fetch the business', error );
}
return successHandler(callBack, result);
});
}
Example #25
Source File: addBusiness.ts From Stripe-shop-backend with MIT License | 6 votes |
addBusiness: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const data: BusinessInput = JSON.parse((event as APIGatewayEvent).body);
const validBusiness: validBusiness = validateBusiness(data);
if (!validBusiness.isValid) {
return errorHandler(callBack, 'ERROR: Business contains invalid data.', validBusiness.errors);
}
try {
// const stripeBusiness: Stripe.Business = await createBusiness(stripe, validBusiness.params);
// validBusiness.params.StripeBusinessId = stripeBusiness.id;
const params: BusinessTable = {
TableName: process.env.DYNAMODB_TABLE_BUSINESSES,
Item: validBusiness.params,
};
const savedData = await upsert(params);
console.log('savedData', savedData);
return successHandler(
callBack,
{
message: 'Stripe Business Created!',
business: params.Item,
});
} catch (error) {
return errorHandler(
callBack,
'ERROR Business Creation FAILED!',
error
);
}
}
Example #26
Source File: cancelPaymentIntent.ts From Stripe-shop-backend with MIT License | 5 votes |
cancelPaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const requestData: any = JSON.parse((event as APIGatewayEvent).body);
const { piid, cancellation_reason } = requestData;
if (! piid) {
return callBack('Must provide the PaymentIntentID');
}
const reason: Stripe.PaymentIntentCancelParams.CancellationReason = cancellation_reason ?? 'abandoned';
try {
const paymentIntent = await stripe.paymentIntents.cancel(piid, {
cancellation_reason: reason
});
return callBack(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'Payment cancelled!',
PaymentIntent: paymentIntent,
},
null,
2,
),
});
}
catch(error) {
return callBack(null, {
statusCode: 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'ERROR Payment Intent Cancellation FAILED!',
errorDetails: error,
},
null,
2,
),
});
}
}
Example #27
Source File: startPayment.ts From Stripe-shop-backend with MIT License | 5 votes |
startPayment: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
const {
customerId,
payment_method_types,
capture_method = 'automatic',
billing_details=undefined,
saveCustomer=false,
}: any = JSON.parse((event as APIGatewayEvent).body);
try {
const items = await getCustomerItems(customerId);
if (! items.length) {
return errorHandler(
callBack,
'ERROR startPayment FAILED!',
'Your Cart is Empty',
);
};
const products = await getItemProductAmounts(items);
const total: number = products.reduce((acc, prod) => acc += prod.amount, 0);
const stripePI: PaymentInput = {
amount: total,
currency: 'usd',
}
if (payment_method_types) {
stripePI.payment_method_types = payment_method_types;
}
if (capture_method) {
stripePI.capture_method = capture_method;
}
const results: Validation = validatePaymentIntent(stripePI);
if (!results.isValid) {
return errorHandler(
callBack,
'ERROR The PaymentIntent contains invalid data!',
results.errors,
);
};
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
if (saveCustomer) {
if(billing_details) {
const stripeCustomer = await createCustomer(billing_details);
results.params.customer = stripeCustomer.id;
}
}
const paymentIntent = await stripe.paymentIntents.create(results.params);
return successHandler(
callBack,
{
message: 'startPayment Created!',
paymentIntent,
});
}
catch(error) {
return errorHandler(
callBack,
'ERROR startPayment FAILED!',
error
);
}
}
Example #28
Source File: updatePaymentIntent.ts From Stripe-shop-backend with MIT License | 5 votes |
createPaymentIntent: Handler = async (event: APIGatewayEvent | ScheduledEvent, context: Context, callBack: Callback) => {
// @ts-ignore
const stripe = new Stripe(process.env.STRIPE_API_KEY, {
apiVersion: process.env.STRIPE_API_VERSION,
typescript: true,
});
const requestData: any = JSON.parse((event as APIGatewayEvent).body);
// @todo validation on inputs
const {
amount,
currency,
payment_method_types,
capture_method,
off_session,
} = requestData;
const valid_payment_method_types = (payment_method_types) ? payment_method_types : ['card'];
const valid_capture_method = (capture_method == 'manual') ? capture_method : 'automatic';
// const valid_setup_future_usage = (off_session) ? 'off_session' : 'on_session';
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency,
payment_method_types: valid_payment_method_types,
capture_method: valid_capture_method,
// setup_future_usage: valid_setup_future_usage,
});
return callBack(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'Payment Intent Created!',
PaymentIntent: paymentIntent,
},
null,
2,
),
});
}
catch(error) {
callBack(null,{
statusCode: 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
message: 'ERROR Payment Intent Creation FAILED!',
errorDetails: error,
},
null,
2,
),
});
}
}
Example #29
Source File: confirm-payment.ts From sleekypay with MIT License | 5 votes |
exports.handler = async function (
event: APIGatewayEvent,
context: Context,
callback: Callback) {
interface ConfirmResult {
returnUrl: string;
}
const requestBody = JSON.parse(event.body);
const paymentId = uuid();
const API_URL = process.env.API_URL || 'https://localhost:12666';
const SITE_URL = process.env.URL || event.headers.origin;
const response = await fetch(
`${API_URL}/api/private/custom-payment-gateway/payment`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.BEARER_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
paymentSessionId: requestBody.paymentSessionId,
state: requestBody.state,
error: requestBody.error,
transactionId: paymentId,
instructions: 'Your payment will appear on your statement in the coming days',
links: {
refunds: `${SITE_URL}/.netlify/functions/refund-payment?transactionId=${paymentId}`,
}
}),
});
if (response.ok) {
const body = (await response.json()) as ConfirmResult;
return {
statusCode: 200,
body: JSON.stringify({ ok: true, returnUrl: body.returnUrl })
};
}
}