How to set up Stripe API for Parse Cloud Code - javascript

How do we set up Stripe API for Parse Cloud Code. I've managed to get the code working, but I'd like to edit it. The function below is "stripe.customers.create", it only works when I remove the source line. How can I request the token? I am also trying to connect the Stripe customer to the parse user.t
Parse.Cloud.define("customer", function(request, response){
stripe.customers.create({
description: request.params.description
//source: request.params.token
}, function(err, customer) {
if(err){
console.log(err);
response.error(err);
}
else{
console.log(customer);
response.success(customer);
}
});
});

I already answered this question before. You can find my here
The idea is that in parse-server you can install any npm module that you want so in my answer i explain how you can first install the stripe npm module and then call it from your cloud code function.

Related

GCP: Stripe webhook error: No signatures found matching the expected signature for payload

Stripe version: "8.107.0"
I keep getting a Stripe webhook verification error whenever I run my webhook on GCP. I've tried using the raw body in the signature, as the code snippet below mentions, as well as other ways to pass the req.rawBody as other StackOverflow answers mention.
The weird thing is that this error seems to be thrown when I deploy to GCP, and not when I run locally. I tried to manually create the signature (https://stripe.com/docs/webhooks/signatures#verify-manually), and the same result there: locally the signatures match, on GCP it doesn't.
Our server is hosted on GCP GKE, and we serve requests to our server through an Nginx Reverse Proxy. Other stack overflow solutions mentioned Google Cloud Functions and Lambda. As far as I'm aware, we do not parse requests on GCP
I do use bodyParser.json(), but that's setup after this endpoint. These are the ways I've tried creating / using a rawBody:
app.use(express.json({verify: (req,res,buf) => { req.rawBody = buf }}));
bodyParser.json({
verify: (req: any, res, buf) => {
req.rawBody = buf.toString();
},
}),
event = stripe.webhooks.constructEvent(req.rawBody, sig, webhookSecret);
I based my code on the stripe example found here: https://github.com/stripe/stripe-node/blob/master/examples/webhook-signing/node-express/express.js
// Stripe requires the raw body to construct the event
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Successfully constructed event
console.log('✅ Success:', event.id);
// Return a response to acknowledge receipt of the event
res.json({received: true});
});
Any help would be appreciated, thanks.
The issue was with one of our setup files, where basically a space or an \n character was getting added to our webhookSecret
We had the same problem here, and it was fixed by looking for a development webhook secret (as we have a different url for development environment - it is a different webhook secret - consider look that when you have this problem).

How to fix error 'WooCommerce.get(...).then is not a function'?

I'm trying to start work with WooCommerce API - Node.js Client, which looks very straightforward.
But when I copy a simple example from WooCommerce official website, I get the following error:
TypeError: WooCommerce.get(...).then is not a function
Here is the code:
var WooCommerceAPI = require('woocommerce-api');
var WooCommerce = new WooCommerceAPI({
url: 'https://somewebsite.com/',
consumerKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumerSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
wpAPI: true,
version: 'wc/v1'
});
WooCommerce.get("products/1359")
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error.response.data);
});
https://woocommerce.github.io,
NPM package
Have found this at the bottom of the NPM package page:
Every method can be used in a promified way just adding Async to the method name. Like in:
WooCommerce.getAsync('products').then(function(result) {
return JSON.parse(result.toJSON().body);
});
Which actually makes the code works now.
I still want to understand what I was doing wrong, I don't think that the official API documents website of WooCommerce is showing all code examples as wrong.
I guess it got to do something with WooCommerce.get not returning a promise, but again that is the way it's in the documents.
Apparently woocommerce.github.io are referring to #woocommerce/woocommerce-rest-api NPM package where docs.woocommerce.com official website refer to WooCommerce API - Node.js Client NPM package.
Kinda confusing...but that solves the mystery.
I was facing a similar problem but with post method. Solved adding a function callback with response argument.
WooCommerce.post("orders", data,function(req,res){
console.log(res.statusMessage);
});

Writing code inside sudo.exec in Electron App

I need to execute code with admin rights at many places. I find sudo.exe and successfully prompt user for permission and password. I still could not figure out how exactly to use sudo.exe. As I am getting same error of permission denied while deleting a file that need admin permission. That is how my code looks like:
const fs = require('fs')
var sudo = require('sudo-prompt');
var options = {
name: 'Electron',
};
sudo.exec('echo hello', options,
function(error, stdout, stderr) {
if (error) throw error;
// Code that I want to run with admin rights
fs.unlinkSync("/private/var/log/fsck_hfs.log", (err) => {
alert("File succesfully deleted");
});
}
);
I think this method can only be used to run command, like echo hello in this case. What if I actually want to execute a chunk of code instead of a command?
Does this method works or these is any other approach available?
Is there a better method available in Electron to get privileges?
You can see the admin prompt approach in a popular Electron app: https://github.com/microsoft/vscode
In the package.json file they have two useful dependencies:
https://www.npmjs.com/package/native-is-elevated
https://www.npmjs.com/package/#vscode/sudo-prompt
They check to see if permissions are elevated using native-is-elevated, and if not, prompt for an admin password using sudo-prompt.
You can read the source code for the process here: https://github.com/microsoft/vscode/blob/8845f89c1e4183b54126cd629cd45c8f0f7549f2/src/vs/platform/native/electron-main/nativeHostMainService.ts#L491
I have created an example Electron app using this approach here: https://github.com/kmturley/electron-runas-admin
If you want to run Node.js code, you can put it inside a script.js and run:
node script.js

Add Mailchimp susbscriber through Firebase Function

Scenario :
I'm trying to create a Firebase Function to add a subscriber to a Mailchimp list using the Mailchimp API but after three days of trying different methods I've had little luck.
Currently my function resembles:
exports.addSubscriber = functions.https.onRequest((req, res) => {
const Mailchimp = require('mailchimp-api-v3')
const mailchimp = new Mailchimp('MY_API_KEY');
mailchimp.post('/lists/'MY_LIST_ID'/members', {
"email_address": 'test#gmail.com',
"status": 'pending'
}).then(function(results) {
console.log('added new user to mailchimp list');
})
.catch(function(err) {
console.log(err);
})
return null
});
When I try to trigger the function it results in a 'crash' with Error: Cannot find module 'mailchimp-api-v3' in the logs.
I've already ran npm install mailchimp-api-v3 in my local Firebase
directory so the module should be available.
Where am I going wrong?
Is there a simpler way to use the Mailchimp API with Javascript?
Try to run
npm install mailchimp-api-v3 --save
It seams the above package is missing.

What is the syntax for deleting/releasing Twilio phone numbers in Node.js?

I'm getting a 404 error when trying to delete a Twilio phone number via the API.
Here's my code:
var twilioSID = user.numberSID; // PN946a0603c974be563c5916f865be4d0b
var accountSid = '{removed}';
var authToken = '{removed}';
var client = require('twilio')(accountSid, authToken);
client.incomingPhoneNumbers(twilioSID).delete(function(err, deleted) {
if (err){
console.log(err);
} else {
console.log('Deleted from Twilio');
}
});
Here is the error I'm getting in the console:
{
status: 404,
message: 'The requested resource /2010-04-01/Accounts/{removed}/IncomingPhoneNumbers/PN946a0603c974be563c5916f865be4d0b.json was not found',
code: 20404,
moreInfo: 'https://www.twilio.com/docs/errors/20404'
}
The Twilio API doesn't have hardly any documentation for deleting numbers either. Any ideas on why this is not working?
#parkeragee Your solution is working
client.incomingPhoneNumbers(poneNumberSID).delete(function(err, deleted) {
if (err){
console.log(err);
} else {
console.log('Deleted from Twilio');
}
});
They changed it from delete to remove in their node js module.
As of this writing, the function to remove Twilio phone numbers via the API is called remove. If you try to use delete, you should receive the following error:
client.incomingPhoneNumbers(...).delete is not a function
I wasn't able to find any reference in the Twilio API docs; found this by reading the source, Luke.
Here's an example invoking remove:
client.incomingPhoneNumbers(sid).remove()
.then(function(deleted) {
// Success
})
.catch(function(error) {
// Handle error
});
According to their REST API documentation, you can send an HTTP DELETE request to a url like /2010-04-01/Accounts/{AccountSid}/IncomingPhoneNumbers/{IncomingPhoneNumberSid}. So the URL in the error message looks almost right, except for the .json on the end. Either way it looks like a bug in their code if the phone number is in fact still attached to your account.
My issue was that I was overwriting my production phone nuber numberSID variable with my test phone number. So the user.numberSID; that I was assigning to a variable was for the Twilio test phone numbers. So, when it was searching for that numberSID, it returned a 404.

Categories

Resources