PayPal JS SDK pass in custom trial days? - paypal-rest-sdk

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

Related

How to add an extension number in twilio click to call using node js

As per the documentation here & the github source code here, I have cloned the application, its working perfectly.
Suppose if my sales person having some extension then how can I give that extension in this script. Normally, using senddigit I can pass the extension in twilio but I dont know how to implement that with this salesNumber.
twilioClient.createCall(salesNumber, phoneNumber, headersHost)
.then((result) => {
response.send({message: result});
})
.catch((error) => {
response.status(500).send(error);
});
Please some one help on this.
I think you're looking at the wrong code snippet here. The code above doesn't call the Twilio client directly. Instead, it calls the helper function from this file to initiate the call.
Once the user picks up, they will be connected to the sales person via TwiML in this function:
voiceResponse: (salesNumber, Voice = VoiceResponse) => {
let twimlResponse = new Voice();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
return twimlResponse.toString();
}
In this function, you'll be able to send digits along as mentioned here.

Return Stripe Response within Firebase Function to Swift Application

I’m trying to make an iOS that connects to Stripe and can show user information and data and things.
I’m doing this by using Firebase Functions, so I don’t have to maintain a server, and also because I’m a newb to the extreme.
But when I try to say, get a customer by using the Firebase callable functions, ex.
exports.getCustomer = functions.callableFunctions((data, context) => {
stripe.customers.retrieve(
data.customerID, function (err, customer) {
console.log(‘customer’)
});
});
I’m not sure where to place the “return” in order to actually use that ‘customer’ object in my app. I tried to stick a “return customer” under the console.log, but it’s never....... returning. I’ve also tried creating an empty string variable that I set after the console log and return, but that is always coming up as an empty string on the app.
Sorry for the typesetting issues, and this question is very theoretical - I’m typing on my phone because I don’t want to forget it and I’ll be away from my computer for a while.
Can anyone provide any guidance on how I’d return the ‘customer’ object to my iOS app?
As detailed here, since the release of the Stripe node.js API version 2, they added support for promises: "Every resource method now returns a Promises/A+ compliant promise in addition to supporting the conventional callback".
So you could do as follows:
exports.getCustomer = functions.callableFunctions((data, context) => {
const stripeCustomerID = data.customerID;
return stripe.customers.retrieve(stripeCustomerID)
.then(customer => {
return { customer: customer };
})
.catch(err => {
throw new functions.https.HttpsError('<status error code>', 'xxxxxxx');
});
});
As indicated in the doc, have a look here for the possible values of

Cloud Functions for Firebase - action on email verified

Im trying to create a Cloud Function trigger that will execute after email has been verified.
In the Cloud Functions samples I could only find examples on triggers for onCreate and onDelete.
Within the documentation I found something about creating custom action handlers but I don't actually want to replace the standard email verification dialog they have by default, I just want to change the property of a "user" after the email is verified.
Does anyone have any experience with this, and is this even possible? Or is my only option to create my custom verification view/dialog webpage?
I faced this problem and took me a long time to figure it out how to solve so I hope this could help anyone that could get stuck into this too:
1 -> I created a function that was triggered with onCreate() for a new user
exports.sendConfirmationEmail = functions.auth.user()
.onCreate((user) => {
const actionCodeSettings = {
url: 'https://appNextURL.com/',
handleCodeInApp: false//ensure that the link will open into browser
};
return admin.auth().generateEmailVerificationLink(user.email, actionCodeSettings)
.then(async (link) => {
await db.collection('users').doc(user.uid).set({
verificationLink: link,
emailVerified: false
}, {merge: true});
return sendCustomVerificationEmail(user.email, user.displayName, link);
})
.catch((err) => {
console.error("Error:", err);
return Promise.reject(err);
});
});
The generateEmailVErificationLink() will generate the link based on the link we will save on step 3.
The function sendCustomVerificationEmail() is just an internal function that overcomes the standard email firebase send
2 -> Then I created a function that will receive a manual http trigger with the data that would be generated automatically by firebase when sending an automatic email
exports.verifyEmail = functions.https.onRequest((req, res) => {
const {mode, oobCode, apiKey, continueUrl, lang} = req.query;
const link = "https://us-central1-projectId.cloudfunctions.net/verifyEmail/?mode=" + encodeURIComponent(mode) + "&oobCode=" + encodeURIComponent(oobCode) + "&apiKey=" + encodeURIComponent(apiKey) + "&continueUrl=" + encodeURIComponent(continueUrl) + "&lang=" + encodeURIComponent(lang);
return db.collection("users")
.where("verificationLink", "==", link)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (user) {
const userData: UserData = user.data();
console.log("email verified: ", userData.userId);
return admin.auth().updateUser(userData.userId, {
emailVerified: true
}).then(function (userRecord) {
return db.collection('users').doc(userData.userId).set({emailVerified: true}, {merge: true});
});
});
return res.sendStatus(200).end();
}).catch(function (err) {
console.log("error:", err);
return res.sendStatus(403).end();
});
});
As I saved the link in the onCreate() I can now query that link to get who is the user that I am authenticating
3 -> the third step is to change the link in to Firebase Authentication template to the link generated into the 2nd step:
Navigate to Authentication>Templates:
Click on edit icon> Click on customize action URL:
Navigation
Paste the link generated into the step 2 and save:
Save link
Now every link generated automatically will go trought that function you created on step 2 and you will be able to handle the actions you want to happen.
I hope I could be clear.
you could still check for the verification status (at least) on Android with interface UserInfo method isEmailVerified(); eg. in order to send another verification email upon successful login, in case the current user has not yet verified the email address - and show the login screen again. one could as well HTTP trigger a cloud function or update values in the Firebase directly, through the client library. this might also apply to other platform clients, where one can check for the verification status.
this would not be exactly the event when the email just had been verified, but upon each single login attempt one knows the verification status and this value might be merely relevant on the client-side.
Create a publish button so your users trigger your cloud function
Instead of firing the cloud function immediately upon auth.emailVerified, I'm giving my users a 'Publish Profile' button which fires an http cloud function (passing in user.uid). This function looks up the user auth using the passed in user.uid
if user.uid && auth.emailVerified
write auth.emailVerified to each user.post
By default, post document "post.emailVerified" fields start out false, and cannot be written to except via adminFirestore in a cloud function.

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 wallet for digital goods - let user determine price

I've got google wallet for digital goods working fine for fixed price items. However, I would like to sell user priced items or subscriptions (i.e., pay what you want or can). So the user would enter the price they want to pay.
However, I cannot seem to find any way to do this with google wallet for digital goods. Any ideas or tips?
The key item is for the JWT to be generated server-side.
A trivial example is here
Pls. note that I just mocked this so I'm not doing a lot of validations to user input - so please be gentle - it's just for reference showing how you can accomplish things.
Also this says nothing of Google's policy (check with them about donations)....
In summary what the sample does:
Allow user to provide some value in a standard <input />
Send data to server via Ajax (e.g. jQuery $.post) and generate the necessary JWT based on user input/s
If JWT is generated successfully, call buy (google.payments.inapp.buy) and supply it the server generated value (the JWT) returned from #2
E.g.
$(function () {
$("#donateForm").on("submit", function (e) {
e.preventDefault();
var data = $("#donateForm").serialize();
$.post("ajaxhandler.ashx", data) //send to server to generate JWT
.done(function (d) { //d is the JWT in this sample
google.payments.inapp.buy({
"parameters": {},
"jwt": d, //d goes here
"success": function (result) {
//handle Wallet success as you deem fit
},
"failure": function (result) {
//handle Wallet failures as you deem fit
}
}
);
}).fail(function (f) {
//handle ajax failure as you deem fit
}).always(function (a) {
//handle as you deem fit
});
........
Hth...

Resources