Stripe module issues at Parse - node.js

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()
}
});
});

Related

problem when making call interconnection using the plivo api

I am currently working with the plivo api to build an ivr, however, I have used all the recommendations given by the documentation and so far I can not establish a successful connection within the conference calls in the application, below I attach the code that is involved in the conference function.
getDialConnecting(numberFrom, numberTo, route){
let ivr = new Ivr();
let client = ivr.getClient();
client.calls.create(
`${numberFrom}`,
`${numberTo}`,
`${process.env.HOST}${route}`,
{
answerMethod: "POST"
},
).then(function(response){
console.log(response);
}, function(err){
console.log(err);
});
this function is called each time I make a conference call and enter the following parameters
I am currently working with the plivo api to build an ivr, however, I have used all the recommendations given by the documentation and so far I can not establish a successful connection within the conference calls in the application, below I attach the code that is involved in the conference function.
call.getDialConnecting(`${incomingNumber}`, `${incomingNumberTransmitter}`, 'conference');
in addition this is the path that is performing the handling of the function that accepts the call
const ivrGetConference = route.post('/voice/conference', call.callRequestConfirmed);
My name is Mohammed Huzaif, and I work at Plivo as a Product Evangelist.
From the information shared, I'm unable to determine the error you may have received on your end or the documents utilised.
However, you can follow the below steps to build an IVR.
First, we'll create our IVR, To do so, follow the directions in this documentation.
Once the IVR system is developed, we will make a call to the destination number by using the URL generated in above step.
To make a call, use the below code.
Note: Replace the placeholders "from": with the caller_id, "to": Destination number, and "answer_url": the url generated in above step.
var plivo = require('plivo');
(function main() {
'use strict';
var client = new plivo.Client("<auth_id>","<auth_token>"); // https://console.plivo.com/dashboard/
client.calls.create(
"+14151234567", // from
"+15671234567", // to
"https://s3.amazonaws.com/static.plivo.com/answer.xml", // answer url
{
answerMethod: "POST",
},
).then(function (response) {
console.log(response);
}, function (err) {
console.error(err);
});})();
In case, if you still need any assistance, feel free to reach out to our support-team.

PayPal JS SDK pass in custom trial days?

I'm trying to figure out how to pass in a "trial" period, or custom "start date" for a subscription. I have:
paypal.Buttons({
createSubscription: function(data, actions) {
return actions.subscription.create({
'plan_id': window.my_config.paypal_sub_ids[window.my_config["period"]],
'custom_id': $('#Email').val() + "----" + window.my_config["period"]
});
},
onApprove: function(data, actions) {
$('#AJAXloadingWrapper').show();
console.log({ data: data, actions: actions });
// all the rest is done on the server
},
onError: function (err) {
// Show an error page here, when an error occurs
console.log("ERROR")
console.dir(err);
}
}).render('#paypalWrapper');
This works fine. The problem I'm having, is that what I want to do is offer a unique number of free days to a user. A use case is that a user is already a paid member (one off payments), and they want to setup a subscription with us. So obviously you don't want the subscription to start until their current date has expired.
Is there a way to pass this in with the JS SDK? Or is it going to be a PITA where I have to create a custom price plan for that user, with the correct number of days set?
UPDATE: Alternatively, is there a way to "clone" an existing subscription plan, and then tweak the trial_days server side, ready to return to the front end for the JS side of things?
You can get a plan's details and create a new modified plan based on it.
The API call is https://developer.paypal.com/docs/api/subscriptions/v1/#plans_get

How to setup Stripe Ideal with webtask.io webhook

I have been trying for 2 days to setup a webhook for ideal payments in Stripe. First id like to test it using Stripe's inbuilt test methods but so far i cant even get a good response.
Can anybody help me out with a example for creating a source that runs webhook -> /charge when source.chargeable? Ive tried a dozen of examples from stripes own docs to all over the internet. Right now as a webhook i have this (which is from the stripe docs):
module.exports = function(ctx, req, res) {
var stripe = require("stripe")("sk_test_dfgfdgdf");
const charge = stripe.charges.create({
amount: 999,
currency: 'usd',
description: 'Example charge',
source: ctx,
})
};
There is a full example of receiving a webhook with Node(Express) here — that would be a good place to start, just plug in your API key and webhook secret, then run the app and enter your URL in https://dashboard.stripe.com/account/webhooks.
Once you have the event and parse it, you need to check the event type. If it's source.chargeable, then you can call the API to make the charge. You will most likely need to save information to a local database about the original order when it was submitted, as you will receive the webhook asynchronously some time after the user started the checkout flow. You can look up the saved order to determine any metadata to set on the charge/the Stripe customer object to use, etc. But for now a simple approach would be like this :
if(event.type == "source.chargeable"){
const source = event.data.object;
const charge = await stripe.charges.create({
amount: source.amount,
currency: source.currency,
source: source.id,
});
}

Twitter app OAuth with node.js

The following "should" work to post tweet with the contents of message below, i.e. "Lorem ipsum dolor..."
var OAuth = require("oauth").OAuth;
const twitterer = new OAuth( "https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
getContext().configuration.tasks.auto_tweet.apiAccessKey,
getContext().configuration.tasks.auto_tweet.apiAccessSecret,
// getContext().configuration.tasks.auto_tweet.apiPostKey,
// getContext().configuration.tasks.auto_tweet.apiPostSecret,
"1.0", null,"HMAC-SHA1");
// ... business logic
const message = "Lorem ipsum dolor..."
twitterer.post(
"https://api.twitter.com/1.1/statuses/update.json",
getContext().configuration.tasks.auto_tweet.apiPostKey,
getContext().configuration.tasks.auto_tweet.apiPostSecret,
({'status': message}),
"application/json",
function (error, data, response2) {
if(error){
failedTweets ++;
console.log("~~~~~~~~ Failed to send" , failedTweets, "tweets" );
console.log(error);
}
else{ sentTweets ++; }
console.log("~~~~~~~~ Sent" , sentTweets, "tweets" );
setTimeout(function(){
sendNextTweet();
},1000);
the result of the above, with the keys populated as in the twitter app dashboard is this error:
`{ statusCode: 401, data: '{"errors":[{"code":89,"message":"Invalid or expired token."}]}' }`
I'm at a loss here--this is within an app that needs to post to twitter as its own dedicated user, and it is not authenticating other users or anything of that sort, so I believe the callback_url is irrelevant... and in any case I don't know what the callback_url would be if it is required.
I have tried swapping the keys used s.t. the constructor uses the apiPostKey/secret while the post call uses the apiAccessKey/secret
I have generated new keys and updated the config with them.
I have verified that the server time is correct
Also, the 'Test OAuth' button on the app settings page (https://apps.twitter.com/app/XXXXX/settings) yields a page with this message "Sorry, that page doesn’t exist!" on it at https://dev.twitter.com/apps/XXXXX/oauth. It's not clear what this tells me, however
Turns out, the first bullet point was a lie. Most likely I "tested" when the app hadn't reloaded the swapped config. The issue was that the accessKey should be used in the post, and the "post" key (actually the consumer key) is the relevant value in the OAuth constructor.
From : https://dev.twitter.com/oauth/application-only
With Application-only authentication you don’t have the context of an
authenticated user and this means that any request to API for
endpoints that require user context, such as posting tweets, will not
work. However, the set of endpoints that will still be available can
have a higher rate limit.
And it won’t be able to:
Post tweets or other resources;
I recommend you to try use an node package for twitter :
for example
https://www.npmjs.com/package/twitter

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