How to setup Stripe Ideal with webtask.io webhook - stripe-payments

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

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.

Stripe Connect in Europe: Using Payment Intents to Charge Customers (React and Node js)

I am setting up a standard stripe connect account with direct charges.
This was working perfectly for me using the charges api with tokens but won't work for me using the payments intent api as required in EU.
The below code is working in terms of getting the client secret.
axios.post(`${process.env.REACT_APP_API}/paymentIntent`, stripeData).then(res => {console.log('paymentIntent res', res.data)
let clientSecret = res.data.clientSecret
this.props.stripe.createToken({}).then(res => {
console.log('stripe token', res)
if (!res.token) {
this.setState({
message:
"Invalid Credit Card. Your tickets have not been booked. You have not been charged"
})
}
else{
this.props.stripe.confirmCardPayment(
clientSecret,
{
payment_method: {
card: {
token: res.token.id
}
}
}
).then( res => {console.log(res)})
}
})
}
But I am getting the following errors in the console:
Failed to load resource: the server responded with a status of 404 ()
error:
code: "resource_missing"
doc_url: "https://stripe.com/docs/error-codes/resource-missing"
message: "No such payment_intent: pi_1FnrwXLkWxxxxxxxxxxxxxxx"
param: "intent"
type: "invalid_request_error"
There's a few things confusing me.
My clientSecret code is in the format:
pi_1FnrwXLkWxxxxxxxxxxxxxxx_secret_pGBi46eAzWxxxxxxxxxxxxxxx
From the error message, it appears only part of it is being sent to the stripe api. Is this what is causing the error?
Two stripe answers are suggesting using the following code on the frontend.
var stripe = Stripe(STRIPE_PUBLIC_KEY, { stripeAccount: "{{ connected_account }}" })
If this is correct how do I adapt this code for react and where do i put it in the component? It is throwing me an error as it currently is.
Ref1: Code=50 “No such payment_intent” when confirm payment intent for stripe
Ref2: Stripe Connect PaymentIntent error: No such payment_intent
Elsewhere in the Stripe docs it says to use the Payment Methods API instead of tokens with the Payment Intents API. Should I abandon using tokens altogether?
I've figured the answers to these questions (with some help from stripe)
Q1. This isn't an issue
Q3. Don't use tokens with Payment Intents API.
Q2. Don't use that code from the docs. Use
<StripeProvider
apiKey={process.env.REACT_APP_API_STRIPE_PUBLISH}
stripeAccount="{{ connected_account }}">
This worked for me when I hardcoded the account but wouldn't work when I was getting the connected account id from the backend and saving in State. I got it working by conditionally rending the component. I initialised the connected account in state to '' and used this code:
{this.state.userEvent.organiser.stripeAccountID !== '' &&
<StripeProvider
apiKey={process.env.REACT_APP_API_STRIPE_PUBLISH}
stripeAccount={this.state.userEvent.organiser.stripeAccountID}>
<Elements>
<CheckoutForm
total={this.displayTotal()}
applicationFee={this.displayAdminFee()}
currency={this.state.userEvent.currency}
eventTitle={this.state.userEvent.title}
purchaser={this.state.purchaser}
userEvent={this.state.userEvent}
numTicketsSought={this.state.userEvent.numTicketsSought}
/>
</Elements>
</StripeProvider>
}

How to get Conference Sid at the time of dialing twilio call

I've been working with twilio, using Node.js, and dialing call between two web end points. One is client and other is agent. I'm using following code to dial call.
function dialCall(calledNumber, url) {
client.calls.create({
to: `client:${calledNumber}`,
from: twilioNumber,
url: url
})
.then(call => call.sid));
}
I'm using following twiml to establish a call.
const generateTwiml = (conferenceName) => {
let twimlResponse = new VoiceResponse();
twimlResponse.say(`Welcome to unity dialer.`, {
voice: 'alice',
});
const dial = twimlResponse.dial({
timeLimit: '600',
});
dial.conference({
startConferenceOnEnter: true,
endConferenceOnExit: true
}, "Test Room");
return twimlResponse.toString();
};
I've been successfully calling both agents and clients and getting callSid of both calls. However, my question is that at this point of time I also want to get conference Sid as well as I'm dialing the call as conference. What is the method to get that. As per documentation there is a method to fetch conference using conference name and status. However, if I use this some time the same is not returned due to race condition and I have to implement set time out function for same arbitrary delay. I've been getting the result but is there any other solution available for that.
Twilio developer evangelist here.
At the time you return the TwiML to create the conference there is not yet a conference resource so there's no way to get the conference SID at that stage.
As you describe, you can use the conference resource to list conferences and filter by the name you give it. However, you can't list the conferences at the time you return the TwiML because that conference hasn't been created by then.
Rather than setting a timeout, which could be flaky, I recommend you use the statusCallback attribute of the <Conference> TwiML to set a URL to callback to when the conference starts. In the parameters to that callback you will get the ConferenceSid.

Using Twilio API resources within Twilio Functions

I've nearly finished my phone system with twilio and the final part is a voicemail playback. If the call fails or is declined, the calling party can leave a message and it saves to the twilio recordings. All server side code is done in Twilio Functions.
Now I want the end party to be able to check their voicemail by dialing an extension and playing back the saved messages. Everything up to the playing back of messages is done because I can't get the recording uri from a list of recordings.
Note NodeJS is not my strong suite.
I have tried playing back all recordings with:
exports.handler = function(context, event, callback) {
const twilioClient = context.getTwilioClient();
let response = new Twilio.twiml.VoiceResponse();
twilioClient.recordings.each(recording => response.play(recording.uri));
callback(null, response);
}
But I don't the expected result (i.e. I get a 200 OK and the <Response/> xml). I have Enable ACCOUNT_SID and AUTH_TOKEN enabled in the functions configuration.
I feel like it has something to do with the callback and the request to the api being asynchronous but I couldn't find much information on the recordings docs (https://www.twilio.com/docs/api/voice/recording).
Found the documentation I was after in the automated docs (https://www.twilio.com/docs/libraries/reference/twilio-node/3.11.2/Twilio.Api.V2010.AccountContext.RecordingList.html).
client.recordings.each({
callback: function (recording) {
response.say('New Message');
const recordingSid = recording.sid;
},
done: function () {
callback(null, response);
},
});

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

Resources