How to use webhook lib of bots business inside our website? - bots.business

Hello i want to know can I use webhook lib inside my website because when I change user_id in webhook then it show error
https://api.bots.business/v1/bots/185720/new-webhook?&command=Bok%24%40%25%23%5E&public_user_token=cad2968320d3a8ef7149fb1c9af582aa&user_id=72992
See At The Bottom Of Url.
It have user_id parameter when I change it it show error,so can i use webhook lib in our website to easy my devlopment.

Use bot webhook instead user webhook
In BJS:
let webhookUrl = Libs.Webhooks.getUrlFor({
// this command will be runned on webhook
command: "/onWebhook"
})
Then you can pass user_id in request (web page):
$.ajax({
type: "POST",
url: webhookUrl,
data: { user_id: YOUR_USER_ID },
success: success,
dataType: dataType
});
on webhook command (BJS) - run command for user
Bot.run({ command: '/your_user_command', user_id: content.user_id })

Related

Get Twilio phone number Friendly Name when forwarding SMS message using Twilio Functions

I would like to pass along the Twilio phone number's Friendly Name when I forward the SMS message to another phone number. (The Friendly Name is a property assigned to a Twilio number when it is purchased.)
This is not the same as "Send Branded SMS Messages Using Twilio Alphanumeric Sender ID" described here and here.
I am operating in the USA where the above is not supported, and I am OK including the "Friendly Name" in the body of the forwarded message (or the subject line of the email). Also, The "Friendly Name" is not associated with the original sender of the message as in the above examples, but instead is associated with my Twilio numbers. Hope that's all clear.
I am using this example code:
Forwarding SMS messages to another phone number – Twilio Support
Three parameters are passed into the function:
exports.handler = function(context, event, callback) {
context includes environment variables I configure. callback isn't relevant to this question. And for the event parameter, we have these properties:
AccountSid
ApiVersion
Body
From
FromCity
FromCountry
FromState
FromZip
MessageSid
NumMedia
NumSegments
SmsMessageSid
SmsSid
SmsStatus
To
ToCity
ToCountry
ToState
ToZip
Using Twilio Functions, I want to obtain Friendly Name, which is not a property of event. Is it possible to obtain the Friendly Name through one of the other properties? If so, how?
UPDATE: from this Twilio doc I see a clue that I can possibly get Friendly Name from AccountSid.something.outgoing_caller_id.friendlyName
I can't quite understand how to do that in a Twilio function. I tried using:
context.getTwilioClient();
The docs say that "will return an initialized REST client that you can use to make calls to the Twilio REST API." However, it returns an empty httpClient object along with strings for username, password and accountSID. I was expecting a populated object from which I could obtain the phone number's Friendly Name.
As an aside, I would like to ask what objects get passed into the event parameter. In what circumstances would the event parameter contain different properties from those I listed above?
You are well on the right path! Excellent research. In fact, context.getTwilioClient() is part of it. Once you have the Twilio REST API client initialized, you can use another Twilio API to determine what the FriendlyName is from the event.To. I found that here, Filter IncomingPhoneNumbers with exact match.
Below is one way, there certainly may may be others.
const got = require('got');
// async function to deal with async REST API call
exports.handler = async function(context, event, callback) {
const client = context.getTwilioClient();
// await an async response
await client.incomingPhoneNumbers
.list({phoneNumber: event.To, limit: 1})
.then(incomingPhoneNumbers => event.friendlyName = incomingPhoneNumbers[0].friendlyName)
.catch(err => console.log(err));
const requestBody = {
personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
from: { email: context.FROM_EMAIL_ADDRESS },
subject: `New SMS message from: ${event.From}`,
content: [
{
type: 'text/plain',
value: `${event.Body} - ${event.friendlyName}`
}
]
};
got
.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
"Content-Type": 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
console.log(response);
let twiml = new Twilio.twiml.MessagingResponse();
twiml.message({to: '+1555xxxxxxx'}, `You Message: ${event.Body} - ${event.friendlyName}`);
callback(null, twiml);
})
.catch(err => {
console.log(err);
callback(err);
});
};
Specific to the key's associated with the event object, this is a handy one to use.
Object.keys(event).forEach( thisKey => console.log(`${thisKey}: ${event[thisKey]}`));

Send message in hindi language using mg91 api in node.js

I am using msg91 Node.js API to send SMS. It is working fine if the message's text is in English.
Now I want to send SMS in Hindi.
Problem is, if I don't encode the message, it returns Authentication error. Post encoding it says the message is sent, but I don't receive any message on the test target.
Error Message:
{ success: 'false',
token: 'Authentication failure' }
Sample message is:
मोजो में आपका स्वागत है
npm module used: msg91
npm install --save msg91
Sending SMS via msg91 is just a simple get call. You don't need to rely on a language specific API.
As long as you send unicode=1 in the get call you can insert hindi text in you messages.
For more information about the same read here - https://control.msg91.com/apidoc/textsms/send-sms.php
You can refer NodeJS package https://www.npmjs.com/package/springedge to send sms. You can install as
npm install springedge
Code example of sending sms:
// send sms
var springedge = require('springedge');
var params = {
'apikey': '', // API Key
'sender': 'SEDEMO', // Sender Name
'to': [
'919019xxxxxxxx' //Moblie Number
],
'message': 'test+message'
};
springedge.messages.send(params, 5000, function (err, response) {
if (err) {
return console.log(err);
}
console.log(response);
});
You will just need api key and trail account to use it. or you can customize it as per your requirement.

Express routing: How to take user to an optional validation flow and back?

I have a Node Express web app, on which I need to implement this flow:
/product/:productId/buy: User submits a form with Name, Address and phone number that I submit to my API layer
API responds with 201 for All good, and 202 for Order submitted, but we need to verify your mobile number first
/product/:productId/confirm: If 201, show user the confirmation screen
/verify/phone: If 202, take user to a phone verification screen that says: Verify your phone number: <insert phone number
entered at step#1> with the OTP sent to your phone
/product/:productId/confirm: User enters OTP. Hit API, verify and take them to the confirmation screen. Else reload
/verify/phone
I have setup the following routes:
{
method: 'GET',
path: '/product/: productId/buy',
action: ['productController', 'getBuyForm']
},
{
method: 'POST',
path: '/product/: productId/buy',
action: ['productController', 'postBuyForm']
},
{
method: 'GET',
path: '/verify/phone',
action: ['verificationController', 'getVerificationForm']
},
{
method: 'POST',
path: '/verify/phone',
action: ['verificationController', 'postVerificationForm']
}
When I POST the postBuyForm, I submit phone, address and name in the request body.
The server responds with an empty body and a status code.
Now, if the status code is 202 I need to navigate to the verify/phone page, but I also need to somehow carry forward the phone value that I submitted with the postBuyForm because I need to display it on the page.
One option to do this, is to use:
res.redirect('verify/phone/'+phone)
But my business doesn't want the phone number to be part of the query string, as this will allow misuse.
Another option is to use sessions like mentioned below by #circusbred:
app.post('/product/: productId/buy', (req, res) => {
req.session.phone = phone;
});
app.get('/verify/phone', (req, res) => {
console.log(req.session.phone);
});
But we're trying to not use session as by design we only use session for authenticated users and this functionality has to work for non-authenticated users as well.
My question is this:
Is there a way to navigate or redirect to the verification page, while passing the phone value along without having to include it in the query string?
Your only viable option is to utilize sessions of some sort.
app.post('/product/: productId/buy', (req, res) => {
req.session.phone = phone;
});
app.get('/verify/phone', (req, res) => {
console.log(req.session.phone);
});

Stripe module issues at Parse

I am developing a project which integrates Stripe + Parse for iOS. It uses web hooks and Cloud code via node js. Currently i am in need of implementing a couple of functions:
cancel user subscription with flag atPeriodEnd;
subscribe cancelled customer once again (named multiple subscriptions via Stripe docs).
As for the first one: I'm sending a request as follows in Parse's API -
Stripe.Customers.cancelSubscription(request.params.customerID, 1, null)
but the second parameter, i.e. atPeriodEnd remains 0 when i receive Stripe's response and my webhook catches request for cancelling user immediately. Also i have checked Stripe's dashboard to see parameters that i pass and it says 'No query parameters'. Hope you can help me with this one out.
Second one: as i mentioned earlier user needs to have ability to subscribe once again after cancellation. That means that i already have a valid customer saved at Stripe and all i need is to 'attach' to him a new subscription. There is a method for this at Stripe docs:
stripe.customers.createSubscription("cus_00000000000", { plan: "planName" }, function(err, subscription) {
});
But i can't find similar to this in Parse's API. Hope you can help with this one out.
Sorry if there are some mistakes or misunderstandings for you - feel free to ask, i will answer as much clear as i can. Thanks!
Here is a workaround to #1 - make an http call directly to the stripe endpoint using Parse.Cloud.httpRequest. (I agree that Stripe.Customers.cancelSubscription in the Parse cloud module does not seem to be working)
Parse.Cloud.define("cancel", function(request, response) {
var user = request.user;
var customerStripeId = user.get("stripeId");
var key = "<stripe_api_key>"
var url = "https://api.stripe.com/v1/customers/" + customerStripeId + "/subscription"
Parse.Cloud.httpRequest({
method: 'DELETE',
params: { at_period_end: true, key: key },
url: url,
success: function() {
response.success()
},
error: function(httpResponse) {
console.error('Delete failed with response code ' + httpResponse.status);
response.failure()
}
});
});

Google+ insert moment with nodejs client

Has anyone been able to get the google-api-nodejs-client to successfully insert a moment?
Whatever I try, I get a generic 400 "Invalid value" error but am unable to narrow down the invalid value because the API Explorer doesn't work either.
Would it be because of the missing data-requestvisibleactions parameter? I'm using passport.js's require('passport-google-oauth').OAuth2Strategy for handling oauth access, and that part is working fine, but I have no idea how to incorporate requestvisibleactions into the oauth request flow since this is definitely not originating from a clientside form.
Here's a snippet of what I'm trying to do (using the latest version of googleapis, v1.0.2):
var google = require('googleapis')
var auth = new google.auth.OAuth2()
auth.setCredentials({
'access_token': user.token
})
google.plus('v1').moments.insert({
collection: 'vault',
userId: 'me',
debug: true,
resource: {
type: "http://schemas.google.com/AddActivity",
target: {
type: "http://schema.org/CreativeWork",
url: "...omitted...",
image: "...omitted...",
description: "test",
name: "test"
}
},
auth: auth
}, function (err, response) {
if (err) {
console.error(err)
res.send(err.code, err)
} else {
console.log(response)
res.send(200)
}
})
ref 1 (out-of-date w.r.t. an older version of googleapis)
ref 2 (client-side, where the use of data-requestvisibleactions is more obvious)
As you speculated, you need the request_visible_actions parameter as part of the URL calling the oauth endpoint.
It looks like the current version of passport-google-oauth doesn't support this parameter. Judging by several of the open issues and pull requests, it isn't clear that the author will respond to requests to add it either. You have two possible options:
Switch to using the OAuth support that is included in google-api-nodejs-client
Patch the passport-google-oauth code. (And possibly submit a pull request in the hopes it will be useful to someone else.)
I don't use passport.js or the passport module in question, so I can't test this, but based on the github repository, I think you can insert the following in lib/passport-google-oauth/oauth2.js after line 136 and before the return statement:
if (options.requestVisibleActions) {
// Space separated list of allowed app actions
// as documented at:
// https://developers.google.com/+/web/app-activities/#writing_an_app_activity_using_the_google_apis_client_libraries
// https://developers.google.com/+/api/moment-types/
params['request_visible_actions'] = options.requestVisibleActions;
}

Resources