I am setting up phone authentication with Twilio, using nodejs....All is working as expected, except when verifying the token. Below is the function which I am using:
verifyPhone: function (req, res) {
client.verify.services('VAxxxxxxxxxxxxxxxx')
.verificationChecks
.create({ to: '+15017122661', code: '123456' })
.then(function (err, verification_check) {
if (err) {
res.status(500).send(err);
} else if (verification_check ==='approved') {
res.status(200).send('Account Verified');
}
})
}
I am checking the endpoint in postman, and it is timing out with no response.
When, I checked in twilio portal, the number status changed to approved.
Any idea why the response is not showing up.
Btw, I turned off SSL certificate
Thanks,
The Twilio Function JavaScript below works for me.
Since Verify v2 is relatively new, make sure your Twilio Helper library is up to date, https://github.com/twilio/twilio-node/releases.
Example to execute function (I have Check for valid Twilio signature turned off for my Twilio function to demo this):
(Example URL to Run Function):
https://mango-abcdef-1234.twil.io/v2start?phoneNumber=%2b15555551234&code=720732
exports.handler = function(context, event, callback) {
const client = context.getTwilioClient();
const code = event.code;
let phoneNumber = event.phoneNumber;
client.verify.services('VAxxxxxxxxxxxxxxxx')
.verificationChecks
.create({to: phoneNumber, code: code})
.then(verification_check => {
console.log(`***VERIFICATION STATUS***: ${verification_check.status}`);
callback(null, `${verification_check.status}`);
})
.catch(err => {
console.log(err);
callback();
});
};
Also recent blog on this topic.
Serverless Phone Verification with Twilio Verify and Twilio Functions
Related
I use twilio to send sms after a order is placed, but it isn't sending any sms and also not console logging anything.
Code: npm i twilio
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require("twilio")(accountSid, authToken);
exports.createOrder = (req, res) => {
const { orders, status, details } = req.body;
const order = new Order({
orders: orders,
status: status,
details: details,
});
order.save((error, order) => {
if (error) return res.status(400).json(error);
if (order) {
// if (res.status === 201) {
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid));
// }
return res.status(201).json({ order });
}
});
};
LINK TO DOC (where I took the code) : https://www.twilio.com/docs/sms/quickstart/node
Twilio developer evangelist here.
There is likely an issue in sending your message, but the code you have is dropping errors, so you can't see what is going on. Try updating it to this:
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid))
.catch(error => console.error(error));
Once you see what the error is, you will be able to fix it. My guess is that you have either configured your Account Sid and Auth Token incorrectly, or you are using a trial account and trying to send a message to a number you haven't verified yet, or you are trying to send a message to a country that isn't enabled.
I have a shopify store mystore and I have an nodejs app myapp. I need to do is when something happens on mystore a webhook will be created/registered in my nodejs app. I have tried https://www.npmjs.com/package/#shopify/koa-shopify-webhooks this package but it is not working for me and I don't think that it is the same thing that I want. I just want that when let suppose order is created in store a webhook is registered.
if you just have to register a webhook you can use this code.
You just have to change the webhook topic and the endpoint.
This is for orders/create webhook registration
add shopify-api-node and request-promise packages and require them
const ShopifyAPIClient = require("shopify-api-node");
const request = require("request-promise");
then
const createOrderWebhook = await registerWebhook(yourShopDomain, yourShopAccessToken, {
topic: "orders/create",
address: "Your node app end point" //www.example.com/webhooks/createOrder,
format: "json",
});
add your registerWebhook function
const registerWebhook = async function (shopDomain, accessToken, webhook) {
const shopify = new ShopifyAPIClient({
shopName: shopDomain,
accessToken: accessToken,
});
const isCreated = await checkWebhookStatus(shopDomain, accessToken, webhook);
if (!isCreated) {
shopify.webhook.create(webhook).then(
(response) => console.log(`webhook '${webhook.topic}' created`),
(err) =>
console.log(
`Error creating webhook '${webhook.topic}'. ${JSON.stringify(
err.response.body
)}`
)
);
}
};
for checking the webhook already not created at Shopify you can use following code
const checkWebhookStatus = async function (shopDomain, accessToken, webhook) {
try {
const shopifyWebhookUrl =
"https://" + shopDomain + "/admin/api/2020-07/webhooks.json";
const webhookListData = {
method: "GET",
url: shopifyWebhookUrl,
json: true,
headers: {
"X-Shopify-Access-Token": accessToken,
"content-type": "application/json",
},
};
let response = await request.get(webhookListData);
if (response) {
let webhookTopics = response.webhooks.map((webhook) => {
return webhook.topic;
});
return webhookTopics.includes(webhook.topic);
} else {
return false;
}
} catch (error) {
console.log("This is the error", error);
return false;
}
};
Happy coding :)
You can not create/register a new webhook when the order created.
Webhooks are a tool for retrieving and storing data from a certain event. They allow you to register an https:// URL where the event data can be stored in JSON or XML formats. Webhooks are commonly used for:
Placing an order
Changing a product's price
Notifying your IM client or your pager when you are offline
Collecting data for data-warehousing
Integrating your accounting software
Filtering the order items and informing various shippers about the order
Removing customer data from your database when they uninstall your app
I have a checkout session:
app.post("/create-checkout-session", async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: converted_items,
mode: "payment",
success_url: process.env.URL + "/order-success.html",
cancel_url: process.env.URL + `/order-page.html`,
billing_address_collection: 'required',
});
res.json({ id: session.id, order: req.body });
});
And I would like to set up a webhook so that after a payment is successfully made, it collects the data from the customer (name, address, products purchased)
I copied this right from the webhook docs:
const fulfillOrder = (session) => {
// TODO: fill me in
console.log("Fulfilling order", session);
}
app.post('/webhook', bodyParser.raw({ type: 'application/json' }), (request, response) => {
const payload = request.body;
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
} catch (err) {
return response.status(400).send(`Webhook Error: ${err.message}`);
}
console.log(event.type)
// Handle the checkout.session.completed event
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
console.log("did order")
// Fulfill the purchase...
fulfillOrder(session);
}
response.status(200);
});
How I am setting it up is I am first running my server on localhost and then I am running the testing webhook command from the terminal
stripe listen --forward-to localhost:3000/webhook --events=checkout.session.completed
When I make a payment, it shows me these messages in the terminal:
It looks like you've made some modifications to that webhook handler code from the docs. If you're using Checkout and following the docs, what made you switch the code to look for charge.succeeded?
You should add some logging to figure out why your server is returning 400, but most likely the verification is failing in constructEvent. The snippet you've shared doesn't show you setting endpointSecret, but you need to update the value using the secret shown to you when you run stripe listen.
You should review the Checkout fulfillment docs and focus on checkout.session.completed events. You can modify your CLI command to listen to online these events:
stripe listen --forward-to localhost:3000/webhook --events=checkout.session.completed
then your handler would look like the docs and you can implement fulfillOrder to meet your needs. If you want the details you listed, then you will need to retrieve the session with expansion to include the line items and payment details:
const session = await stripe.checkout.sessions.retrieve(
'cs_test_123',
{
expand: ['line_items', 'payment_intent.payment_method']
},
);
Then session.line_items will be what you created and the name, address and email will be on session.payment_intent.payment_method.billing_details.
Updated to suggest removing signature verification temporarily to diagnose:
The 400 errors suggest your server is returning an error, most likely as a result of signature verification. I recommend testing a basic endpoint without verification following this example, to ensure everything else is working as intended. When that is settled, re-adding signature verification is strongly recommended.
I am writing an Alexa Skill where one of the functions is to request to send an email to a user using AWS SES.
When the utterance is said to send the email, the email will send however Alexa will always reply 'There was a problem with the requested skill's response'.
I have tested to make sure the 'getEmail' intent itself is working and it is.
I have also tried moving the function within the intent but this has the same results.
This is the function to send the email using SES which seems to be working:
function sendEmail (event, context, callback){
var params = {
Destination: {
ToAddresses: ["xyz#gmail.com"]
},
Message: {
Body: {
Text: { Data: "Hi. Here is your email"
}
},
Subject: { Data: "Here is an email"
}
},
Source: "abc#gmail.com"
};
ses.sendEmail(params, function (err, data) {
callback(null, {err: err, data: data});
if (err) {
console.log(err);
context.fail(err);
} else {
console.log(data);
context.succeed(event);
}
});
}
Here is the intent which call the sendEmail() function.
'getEmail': function () {
sendEmail();
var bodyTemplate1 = new Alexa.templateBuilders.BodyTemplate1Builder();
var template1 = bodyTemplate1.setTitle("email").setTextContent(makeRichText("email")).setBackgroundImage(makeImage(image)).build();
this.response.speak("Your email has been sent").renderTemplate(template1).shouldEndSession(true);
this.emit(':responseReady');
},
When I run this I would like for the email to send to the the device and Alexa to just say "Your Email has been sent". At the moment it is just the email that is sending and the device saying "There was a problem with the requested skill's response"
Here is the error message from AWS Cloud
Looking at logs, your callback(null, {err: err, data: data}); is the issue here. From the code that you posted, callback doesn't exist (will be undefined). It doesn't look like you need that there so you can remove it.
AWS SDK - SES.sendEmail
The "callback" is just your function that's passed as the second argument.
My Assistant app gets a status of PEMISSION_DENIED with a message saying that
the caller does not have permission
I have followed all instructions here by this person: Digital Goods Implementation
I have created APK, managed SKU (valid status) items, Android app that became published (valid status), enabled Actions API from Google API Console and made a service account key for my project, and released my Assistant app for beta to test it. The Connect App status is connected and the toggle is on. I think everything required is completed but the error message does not get fixed, which means I cannot receive purchasable items I prepared in my Google Developer Console.
const createJwtClient = () => {
const scopes = [
"https://www.googleapis.com/auth/actions.purchases.digital"
];
return new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes,
null
);
};
const packageName = 'com.myproject.name'
const getSkus = (tokens, conv) => {
return new Promise((resolve, reject) => {
const url = `https://actions.googleapis.com/v3/packages/${packageName}/skus:batchGet`;
const convId = conv.request.conversation.conversationId;
const param = {
conversationId: convId,
skuType: "SKU_TYPE_IN_APP",
ids: [
"item-id1",
"item-id2"
]
};
request.post(url, {
auth: {
bearer: tokens.access_token
},
json: true,
body: param
}, (err, httpResponse, body) => {
if (err) {
reject(err);
} else {
const statusCode = httpResponse.statusCode;
const statusMessage = httpResponse.statusMessage;
console.log(`${statusCode}: ${statusMessage}`);
console.log(JSON.stringify(body));
resolve(body);
}
});
});
};
I expect I get purchasable items as JSON, but my request to fetch SKU seems to fail.
But I do receive access_token from JWT request using my service account key.
Could you point out something that is wrong??
First, make sure your testing email is different from the Play Console Admin's email. Second, ensure you've added managed products and subscriptions to the Google Play Console (see below) The Actions on Google Github sample has been recently updated as well and the Kotlin APK has all the specifics in the 'Getting Started' section of the readme.