How to setup Braintree API in node js? - javascript

I want use braintree for website paymentgateway, unfortunately when I follow the guideline online, & the code unable to be use in node js. Is anything missing?
Index.js:
//send token to clients
app.get("/client_token", function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.send(response.clientToken);
});
});
//Receive payment from clients
app.post("/checkout", function (req, res) {
var nonceFromTheClient = req.body.payment_method_nonce;
// Use payment method nonce here
});
//Test sandbox
gateway.transaction.sale({
amount: "10.00",
paymentMethodNonce: nonceFromTheClient,
options: {
submitForSettlement: true
}
}, function (err, result) {
if (err) {
console.error(err);
return;
}
if (result.success) {
console.log('Transaction ID: ' + result.transaction.id);
} else {
console.error(result.message);
}
});
Error unable pass the node js npm start:
paymentMethodNonce: nonceFromTheClient,
Details in IDE:
ReferenceError: nonceFromTheClient is not defined
at Object.<anonymous> (/Users/desmondkam/codecampvn/index.js:37:23)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:445:3
Solved
Remove //Test sandbox part would solve the problem of compiled normal in localhost & IDE.
Inorder to running with Sandbox, would required some add-on code regarding: https://developers.braintreepayments.com/reference/general/testing/node:
"fake-valid-nonce"
Your code would be:
gateway.transaction.sale({
amount: "10.00",
paymentMethodNonce: "fake-valid-nonce",
options: {
submitForSettlement: true
}
}, function (err, result) {
});

In case someone is searching for a solution,
import braintree, {
BraintreeGateway,
KeyGatewayConfig,
ValidatedResponse,
Transaction,
ClientToken,
TransactionRequest
} from 'braintree';
import { ITransactionResponse } from '../components/payment/payment.types';
export default class BraintreeWrapper {
private gateway: BraintreeGateway;
constructor() {
// get the braintree key gateway config from environment, which we set in global environment objecr
const env: KeyGatewayConfig = environment.braintree;
// creates a gateway instance using
this.gateway = new braintree.BraintreeGateway(env);
}
// generate the client token
public async generateToken(): Promise < string > {
const result : ValidatedResponse < ClientToken > = await this.gateway.clientToken.generate({});
const { clientToken } = result;
return clientToken;
}
// make transaction
public async transaction(request: TransactionRequest): Promise < ITransactionResponse > {
const result: ValidatedResponse < Transaction > = await this.gateway.transaction.sale(request);
// extract transaction response keys from result
const {
transaction: {
id,
status,
type,
currencyIsoCode,
amount,
merchantAccountId,
orderId,
createdAt,
updatedAt,
}
} = result;
// map transaction response keys
const response: ITransactionResponse = {
id,
status,
type,
currencyIsoCode,
amount,
merchantAccountId,
orderId,
createdAt,
updatedAt,
};
return response;
}
}
I have created a guide to help you get started with the implementation
Integrate Braintree Payment Gateway SDK in Node.js and React

Related

How to resolve parsing error: Unexpected reserved word 'await'

Hi I am trying to deploy my react native function to Firebase. The pre-conigured firebase function (helloWorld)seems to deploy correctly so I am definitely connected to Firebase. I am trying to deploy my own function which is the chatGPT API and followed the syntax of the initial pre-configured function. The function is a node environment which receives data and sends the data to the chatGPT API which is the completetion function below in the code. It seems that 'await' is already a reserved keyword so I have tried putting 'async' in multiple places but can't seem to deploy this to firebase
const functions = require("firebase-functions"); // Firebase initial function
const OpenAIApi = require("openai") // ChatGPT dependency
const Configuration = require("openai")// ChatGPT dependency
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
// // Create and deploy your first functions
// // https://firebase.google.com/docs/functions/get-started
//
exports.helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello logs!", {structuredData: true});
response.send("Hello from Firebase!");
});
exports.firebasePromptReceiver = functions.https.onRequest((request, response) => {
if (!configuration.apiKey) {
res.status(500).json({
error: {
message:
'OpenAI API key not configured, please follow instructions in README.md',
},
});
return;
}
const prompt = request.body.prompt || '';
if (prompt.trim().length === 0) {
res.status(400).json({
error: {
message: 'Please enter a valid prompt',
},
});
return;
}
try {
const completion = await openai.createCompletion({ //ChatGPT API
model: 'text-davinci-003',
prompt: generatePrompt(prompt),
temperature: 0.9,
max_tokens: 2048,
});
response.status(200).json({result: completion.data.choices[0].text});
console.log(completion);
} catch (error) {
// Consider adjusting the error handling logic for your use case
if (error.response) {
console.error(error.response.status, error.response.data);
res.status(error.response.status).json(error.response.data);
} else {
console.error(`Error with OpenAI API request: ${error.message}`);
res.status(500).json({
error: {
message: 'An error occurred during your request.',
},
});
}
}
});
Please any help is greatly appreciated
functions.https.onRequest(async(request, response) => {..}
await operator sould be used in async function

Is there a problem with the way I have specified my "intents" with discord.js? [duplicate]

This question already has an answer here:
Discord.js v13 code breaks when upgrading to v14
(1 answer)
Closed last month.
Here is my code:
const Discord = require('discord.js');
const request = require('request');
// Set up the bot with a command prefix
const bot = new Discord.Client({
ws: {
intents: Discord.Intents.FLAGS.GUILDS |
Discord.Intents.FLAGS.GUILD_MESSAGES |
Discord.Intents.FLAGS.DIRECT_MESSAGES,
},
});
bot.commands = new Discord.Collection();
// Set up the Spotify API client
const spotifyClientId = 'myId';
const spotifyClientSecret = 'mySecret';
let spotifyAccessToken = null;
// Define a function for getting a new access token from the Spotify API
const getSpotifyAccessToken = () => {
return new Promise((resolve, reject) => {
request.post('https://accounts.spotify.com/api/token', {
auth: {
user: spotifyClientId,
pass: spotifyClientSecret,
},
form: {
grant_type: 'client_credentials',
},
}, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(JSON.parse(body).access_token);
}
});
});
};
// Define the command for playing a song
bot.commands.set('play', async (message, args) => {
// Get a new access token if necessary
if (!spotifyAccessToken) {
spotifyAccessToken = await getSpotifyAccessToken();
}
// Search for the song on Spotify
request.get({
url: 'https://api.spotify.com/v1/search',
headers: {
Authorization: `Bearer ${spotifyAccessToken}`,
},
qs: {
q: args.join(' '),
type: 'track',
},
}, (error, response, body) => {
if (error) {
console.error(error);
return;
}
const tracks = JSON.parse(body).tracks.items;
if (!tracks.length) {
message.channel.send('No songs found!');
return;
}
const track = tracks[0];
// Play the first matching song
const channel = message.member.voice.channel;
channel.join().then(connection => {
connection.play(track.preview_url);
}).catch(console.error);
});
});
// Log the bot in
bot.login('My Token');
However, when run, the code returns
TypeError: Cannot read properties of undefined (reading 'FLAGS')
at Object.<anonymous> (C:\Users\myusername\bot.js:7:30)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
I have
Updated discord.js (running at version 14.7.1)
Checked for syntax errors
Made sure there are no errors
I would like the code to successfully run and allow me to use my discord bot.
The actual result is that I am left with an error shown above.
Discord.js is installed and I am running the code using "node bot.js". Node.js is running at v16.14.2
Changed the intents property to the following worked for me:
[ Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildMessages, Discord.GatewayIntentBits.DirectMessages ]

How to read json file from storage blob container with azure function using javascript?

I'm totally new in azure and I would like to create azure function, which will read the content from azure storage container file.json.
Folder structure :
Storage account name: storageaccounttest
Container name: test
File name: file.json
File.json:
[
{
"name":"Kate",
"age":"28"
},
{
"name":"John",
"age":"30"
}
]
Cors on storage account: get enabled.
Environemnts variable added: process.env.AZURE_STORAGE_NAME and process.env.AZURE_STORAGE_KEY and process.env.AZURE_CONNECTION_STRING
I'm using VisualStudioCode to deploy the function.
I installed locally the dependencies:
"dependencies": {
"azure-storage": "^2.10.3",
"dotenv": "^8.1.0"
}
I choose the javascript -> HttpTrigger fn-> anonymus options
I'm using getBlobToText fn.
My index.js:
var storage = require('azure-storage');
var blobService = storage.createBlobService();
var containerName = 'test';
var blobName = 'file.json';
module.exports = blobService.getBlobToText(
containerName,
blobName,
function(err, blobContent) {
if (err) {
console.error("Couldn't download blob");
console.error(err);
} else {
console.log("Sucessfully downloaded blob");
console.log(blobContent);
}
});
Fn is deployed successfully, but I'm not able to see results.
After start, fn is finished with status 500, Internal Server Errror, Console: No new trace in the past 1 min(s).
What I made wrong?
Just summarized for helping others who get the same issue.
I think you were using context.binding.response to pass the blobContent value to the output response as the offical document Azure Functions JavaScript developer guide said.
Here is my sample code with Promise feature to solve it.
var azure = require('azure-storage');
var blobService = azure.createBlobService();
var containerName = 'test';
var blobName = 'file.json';
async function getBlobContent(containerName, blobName) {
return new Promise((resolve, reject) => {
blobService.getBlobToText(containerName, blobName, function(err, blobContent) {
if (err) {
reject(err);
} else {
resolve(blobContent);
}
});
});
}
module.exports = async function (context, req) {
await getBlobContent(containerName, blobName).then(
function(content) {
context.res = {
headers: {"Content-Type": "application/json"},
body: content
}
}, function(error) {
context.res = {
status: 400,
body: error
}
}
);
};
It works as the figure below.

Error: Node.js module defined by file index.js is expected to export function named xxxx

Hello there dev community. I´m trying to debug a firebase function and being trying using several tutorials, but with no success...
I´ve tried
(https://medium.com/#mwebler/debugging-firebase-functions-with-vs-code-3afab528bb36)
(https://medium.com/#david_mccoy/build-and-debug-firebase-functions-in-vscode-73efb76166cf)
My purpose is to get google contacts.
functions/index.js
const { google } = require('googleapis');
const oauthUserCredential = require('./oauthUserCredential.json')
const OAuth2 = google.auth.OAuth2
const key = require('./serviceAccountKey.json')
const jwt = new google.auth.JWT(key.client_email, null, key.private_key, 'https://www.googleapis.com/auth/contacts')
exports.getGoogleContacts = functions.https.onCall(async (data, context) => {
const requestingUser = data.requestingUser
console.log('getGoogleContacts-requestingUser', requestingUser)
const oauth2Client = new google.auth.OAuth2(
'client_id',
'client_secret',
'http://localhost:5000/xxx-xxx/us-central1/OAuthCallbackUrl'
);
const contacts = google.people({
version: 'v1',
auth: oauth2Client,
});
console.log('contacts ?', contacts)
(async () => {
const { data: groups } = await contacts.people.get({
resourceName: 'contactGroups',
});
console.log('Contact Groups:\n', groups);
})()
jwt.authorize((err, response) => {
console.log('inside authorize')
if (err) {
console.error(err);
response.end();
return;
}
// Make an authorized request to list contacts.
contacts.people.connections.list({
auth: authClient,
resourceName: 'people/me'
}, function (err, resp) {
if (err) {
console.error(err);
response.end();
return;
}
console.log("Success");
console.log(resp);
response.send(resp);
});
});
// this is another approach I´ve tried, but it´s also not working
const oAuth2Client = new OAuth2(
oauthUserCredential.web.client_id,
oauthUserCredential.web.client_secret,
oauthUserCredential.web.redirect_uris,
)
oAuth2Client.setCredentials({
refresh_token: oauthUserCredential.refresh_token
})
return new Promise((resolve, reject) => {
console.log('[INSIDE PEOPLE CONNECTIONS]')
contacts.people.connections.list({
auth: oauth2Client //authetication object generated in step-3
}, function (err, response) {
if (err) {
console.log('contacts.people.connections error')
console.log(err)
reject(new Error(err))
} else if (response) {
console.log('contacts.people.connections response')
console.log(response)
resolve(response)
}
});
})
.then(result => { return { found: result } })
.catch(err => { return { error: err } })
})
I´ve tried several different approachs and followed different tutorials
(Using Google People API with Cloud Functions for Firebase)
(https://flaviocopes.com/google-api-authentication/)
(https://medium.com/#smccartney09/integrating-firebase-cloud-functions-with-google-calendar-api-9a5ac042e869)
(https://cloud.google.com/community/tutorials/cloud-functions-oauth-gmail)
but none of them show clearly how could I get my contacts list.
I was able to use a client side code by following this tutorial (https://labs.magnet.me/nerds/2015/05/11/importing-google-contacts-with-javascript.html)
but I thought that living the client_id, client_secret and apiKey exposed in the client side would be a security problem...
I´m submitting also a tutorial request to make it very clear how to get contacts list from google account using firebase functions.
The Error you are receiving is because the cloud function cannot find the function named xxxx to execute, as you have not defined any function named xxxx in the index.js file.
Your Cloud Function to execute name, according to the error message is xxxx but the function that you are calling in index.js is getGoogleContacts. Please make sure that these names are the same, for example change getGoogleContacts to xxxx or change function to execute to getGoogleContacts

Bot Framework V4 - TypeError: Cannot perform 'get' on a proxy that has been revoked

I am trying to make a rest query against a database that stores knowledge articles for users and returns an array of results based on what the user has searched for. Whenever I try to search I get:
"TypeError: Cannot perform 'get' on a proxy that has been revoked"
I have tried adding it to async as shown but I still keep getting the same error. Any idea what I am doing wrong?
const Response = async (turnContext) => {
if (turnContext.activity.value.choice === 'feedbackProvider') {
try {
const feedbackBody = turnContext.activity.value.feedbackBody;
const feedbackEmail = turnContext.activity.value.feedbackEmail;
storage.write(feedbackBody, feedbackEmail);
await turnContext.sendActivity(`Feedback Sent`);
} catch (err) {
console.log('fetch failed', err);
}
} else if (turnContext.activity.value.choice === 'issueRaiser') {
try {
const bugTitle = turnContext.activity.value.issueTitle;
const bugDesc = turnContext.activity.value.issueDescription;
const bugEmail = turnContext.activity.value.issueEmail;
const request = require('request');
request({
method: 'Post',
uri: `<uri>issues?title=${ bugTitle }&description=${ bugDesc } ${ bugEmail }&labels=bug`,
json: true,
headers: {
'Private-Token': '<token>'
}
});
turnContext.sendActivity(`Issue Raised`);
} catch (err) {
console.log('fetch failed', err);
}
} else if (turnContext.activity.value.choice === 'knowledgeBaseSearch') {
try {
const knowledgeBaseTopic = turnContext.activity.value.knowledgeBaseTopic;
request({
url: process.env.SN_KB_URL + knowledgeBaseTopic,
json: true,
auth: {
'username': process.env.Ticket_User,
'password': process.env.Ticket_Key
}
}, async (error, response, body) => {
try {
var stuff = [];
for (var i = 0, len = body.result.length; i < len; i++) {
stuff.push(
CardFactory.heroCard(body.result[i].short_description, ['imageUrl1'], [`${ process.env.SN_KB_Resp_URl }${ body.result[i].number }`])
);
}
let messageWithCarouselOfCards = MessageFactory.carousel(stuff);
await turnContext.sendActivity(messageWithCarouselOfCards);
} catch (err) {
console.log(error);
}
});
} catch (err) {
console.log('fetch failed', err);
}
}
};
Full Error Message:
TypeError: Cannot perform 'get' on a proxy that has been revoked
cardMiddleware.js:35
at Request.request [as _callback] (c:\Bots\sdk4-2\skills\cardMiddleware.js:35:45)
at Request.self.callback (c:\Bots\sdk4-2\node_modules\request\request.js:186:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (c:\Bots\sdk4-2\node_modules\request\request.js:1163:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (c:\Bots\sdk4-2\node_modules\request\request.js:1085:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
From my post on the forum I was informed that I was using a request module that did not support Promises, which I believe was causing my error. I've now began to use Axios for my request which is shown below;
try {
return await axios.get(process.env.SN_KB_URL + knowledgeBaseTopic, {
headers: {
auth: {
username: process.env.Ticket_User,
password: process.env.Ticket_Key
}
}
})
}
However now when I run the request I get a 401 'Unauthorised' error and I'm not sure what is wrong with my request.
This issue happened because I was using a request module that did not support promises. Changing my request module for one that did support promises (which I found out about by using this article) resolved the issue.
The answer for me was to double check I didn't miss any await usage that might be necessary. Turns out I called this.dialog.run(context, this.dialogState); without the await and that threw the same error. I found the answer on this Github issue
I spent a lot of time struggling with this issue. As other commenters have noted, the issue lies in the fact that the Lex Runtime is not promise-based, so you cannot await requests, which causes the proxy to be revoked.
Here is my solution:
async callLex(context) {
const params = {
botAlias: 'prod',
botName: 'botName',
userId: context.activity.from.id,
contentType: 'text/plain; charset=utf-8',
accept: 'text/plain; charset=utf-8',
inputStream: context.activity.text.trim()
}
let request = lexruntime.postContent(params)
await request.promise().then(
async response => {
console.log(response)
console.log('Success!')
await context.sendActivity(response.message)
},
err => {
console.log(err)
console.log('Error!')
})
}
Rather than directly invoke the request like "lexruntime.postContent(params, callback func)", I exclude the callback function and utilize the "promise" property of AWS.Request to send the request as a promise which enables me to use "await" and keeps the proxy open. See documentation here.
I'm going to put this here only because it's the first result that pops up when searching, although it doesn't directly relate to this issue.
There's a very easy way to use setTimeout() and avoid this error:
await new Promise(resolve => setTimeout(() => resolve(
turnContext.sendActivity('I was sent 5 seconds later')
), 5000));
In my scenario, we were trying to upload files from a Task Module (modal popup of teams) to the bot and in response the bot would give a first confirmation that the attachments are uploading. This activity would close the task module (as the bot must reply within 10 seconds or teams would resend the request). Now when the attachments were uploaded, we wanted to update the previously sent adaptive card with the list of the uploaded attachments. We achieved this using the proactive messaging feature of bot framework.
const conversationReference = TurnContext.getConversationReference(activity);
Promise.all(listOfPromises).then(() => {
await botAdapter.continueConversation(conversationReference, async turnContext => {
await turnContext.sendActivity('All attachments uploaded!');
});
}
Docs: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0&tabs=javascript
Check for lines that needs await inside any aync function. I hope that azure will point usto which file or line specifically but I have not figured it out until I looked at all my functions.
Okay, so this is indeed a very cryptic error message as the github thread here suggested .
But I found that I was not await ing in this block:
this.onMessage(async (context, next) => {.
const didBotWelcomedUser = await this.welcomedUserProperty.get(
context,
"false"
);
if (didBotWelcomedUser === false) {
// first time user is in chat
await this.sendWelcomeMessage(context); `<-------- await here was missing`
} else {
await this.sendSuggestedAction(context); `<-------- await here was missing`
}
await next();
});
this.onMembersAdded(async (context, next) => {
await this.sendWelcomeMessage(context);
await next();
});
}
I thought await.next() is enough. We all gotta learn this somehow... Hope you resolve yours.

Categories

Resources