so I'm using Parse to handle a Stripe enabled app. We want our users to be able to cash out their in app credits, and we're planning on using Stripe to handle that. I've been able to create Customers in Stripe successfully, and link a bank account to these. Now I'm trying to initiate a transfer to one of these bank accounts, following
https://stripe.com/docs/tutorials/sending-transfers
But I'm running into an issue where Stripe.recipients is undefined.
Relevant code:
Initialization of Stripe:
var Stripe = require('stripe');
Stripe.initialize('sk_test_ukk7e8B46I39nxoUd6XILpPZ');
Parse Cloud Function for transferring:
Parse.Cloud.define("startTransfer", function(request, response) {
var userObjectId = request.params.userObjectId;
var credits = request.params.credits;
var StripeCustomer = Parse.Object.extend("StripeCustomer");
var stripeCustomerQuery = new Parse.Query(StripeCustomer);
stripeCustomerQuery.equalTo("userObj", userObjectId);
stripeCustomerQuery.find({
success: function(results) {
if(results.length == 0) {
} else if(results.length == 1) {
var customer = results[0];
// handle returning customer adding a new card
Stripe.Recipients.create({
name: customer.description,
type: "individual",
bank_account: customer.source,
email: customer.email
}, function(err, recipient) {
// recipient;
console.log("have a recipient");
if(err == nil) {
Stripe.transfers.create({
amount: credits,
currency: "usd",
recipient: recipient,
bank_account: customer.source,
statement_descriptor: "Cash Out"
}, function(err1, transfer) {
// asynchronously called
if(err == nil) {
response.success("Successfully transferred funds");
} else {
response.error(err1);
}
});
} else {
response.error(err);
}
});
}
}, error: function(error) {
reponse.error(error);
}
});
});
I'm calling this from iOS, using the PFCloud.callFunction API call. It seems to be hitting this code properly, but Recipients is said to be undefined in the error message, but the Stripe documentation requires it. How can I solve this?
Turns out, the Stripe cloud code module is indeed using an older version of Stripe. Therefore, according to this bug report, the solution is to download the newer SDK and manually add it to cloud code modules.
Source:
https://developers.facebook.com/bugs/523104684492016/
Actual post from the bug report (from Facebook employee):
Parse modules are using an old version of the API and there is no plan to update it in the near future.
As a workaround please download the newer SDKs directly off the third party site, place it in "cloud/" folder and import it using require();
We're going to close this by design.
Related
I'm integrating amazon connect chatbot on my end and I want to establish a connection between a customer and an agent. In order to so, I have used onMessage event to retrieve agent messages back on my platform but right now, it is not triggered.
I have initially used aws-sdk and #aws-sdk/client-connectparticipant library to send messages where I have used multiple SDKs api in this order
startChatContact -> createParticipantConnection -> sendEvent -> sendMessage
This was done in order to establish a connection between a client and an agent, so that they can send messages to each other as well. With these SDKs, I was successfully able to send messages from customer to agent but in order to retrieve the messages back, I have used getTranscript api inititally, which I was calling in every 2 seconds to check for any updated messages. I have also stored message ids on my end to avoid any duplicate entries.
But now I'm looking for a better solution and for that, I have used amazon-connect-chatjs library and I have used the code below:
import "amazon-connect-streams";
import "amazon-connect-chatjs";
connect.contact(contact => {
if (contact.getType() !== connect.ContactType.CHAT) {
// applies only to CHAT contacts
return;
}
contact.onAccepted(() => {
const cnn = contact.getConnections().find(cnn => cnn.getType() === connect.ConnectionType.AGENT);
const agentChatSession = connect.ChatSession.create({
chatDetails: cnn.getMediaInfo(),
options: {
region: "us-west-2"
},
type: connect.ChatSession.SessionTypes.AGENT,
websocketManager: connect.core.getWebSocketManager()
});
});
});
I have also tried creating a customer chat session, but it is not working as well
const customerChatSession = connect.ChatSession.create({
chatDetails: {
contactId: "...",
participantId: "...",
participantToken: "..."
},
options: { // optional
region: "us-west-2"
},
type: connect.ChatSession.SessionTypes.CUSTOMER
});
Apart from that, I have used onTyping event, but it is not getting triggered as well.
Please let me know if I'm missing anything or doing anything wrong here.
Update1
if i add console.log
const customerChatSession = connect.ChatSession.create({
chatDetails: {
contactId: "...",
participantId: "...",
participantToken: "..."
},
options: { // optional
region: "us-west-2"
},
type: connect.ChatSession.SessionTypes.CUSTOMER
});
console.log("Here");
then even it does not print Here.
There is no error on console.
To create agentChatSession need websocket
connect.core.getWebSocketManager()
this is undefined even.
I’ve successfully setup the Customers payment methods and am able to retrieve them using the following code:
return stripe.paymentMethods
.list({ customer: customerId, type: 'card' })
.then((cards) => {
if (cards) {
return { cards: cards.data, error: null };
}
return {
error: 'Error creating client intent',
cards: null,
};
})
.catch((e) => {
console.log(e);
return { cards: null, error: 'Error fetching user cards' };
});
I’m now trying to create a direct PaymentIntent that will route the payment to a Stripe Connect connected account.
To do this I’m running this code:
if (cards && cards.cards && cards.cards.length > 0) {
const card = cards.cards[0];
const paymentIntent = await stripe.paymentIntents.create(
{
amount: amount,
customer: card.customer,
receipt_email: userEmail,
currency,
metadata: {
amount,
paymentMode: chargeType,
orderId,
},
description:
'My First Test Charge (created for API docs)',
application_fee_amount: 0,
},
{
stripeAccount: vendorStripeAccount,
}
);
const confirmedPaymentIntent = await stripe.paymentIntents.confirm(
paymentIntent.id,
{ payment_method: card.id }
);
This gives me the error ‘No such customer’, even though the customer ID is defined and I can find the customer in my Stripe dashboard. I also see the customer’s payment methods there.
What am I doing wrong?
The problem is that the Customer exists on your platform account, not the connected account you're trying to create the Payment Intent on.
In your first code snippet you don't specify a stripeAccount, so that API request is being made on your platform account. The Customer exists there, which is why that works as expected.
In your second code snippet you do specify a stripeAccount, which means that API request is being made on the connected account specified, not your platform account. You can read more about making API calls on connected accounts in Stripe's documentation.
To resolve the situation you either need to create the Payment Intent on your platform account as a destination charge, or create the Customer object on the connected account so it can be used there.
I have set the project up as described in the blog post Twilio WhatsApp API and Flex in Minutes.
I followed the instructions and even after repeating the process twice, on two different accounts, when I send the message (through sandbox), the following error occurs:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'Enqueue'. One of '{Sms, Message, Redirect}' is expected.
The task does not show in Flex.
I have tried checking what WhatsApp sends vs what is sent when SMS arrives. This is what a simple function says about trigger.message for SMS:
{
EventType=onMessageSent,
InstanceSid=IS5aa457db5a2d44049c95f2d0b2699f56,
Attributes={\"proxied\":true},
DateCreated=2019-01-16T12:37:43.664Z,
Index=3,
From=sms_g13aggbhlwpgk7tbah3llj2kyjpsvvju,
MessageSid=IM9123e909eeda41ac92890201a6c3f1b4,
Source=API,
AccountSid=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
ChannelSid=CHbc79143368db4680a66c6c504103619f,
RetryCount=0,
ClientIdentity=sms_g13aggbhlwpgk7tbah3llj2kyjpsvvju,
WebhookType=studio,
To=CHbc79143368db4680a66c6c504103619f,
Body=Test Message,
ChannelAttributes={
status=ACTIVE,
forwarding=true,
serviceNumber=sms_g13aggbhlwpgk7tbah3llj2kyjpsvvju,
twilioNumber=+1228xxxxxxx,
from=+44798xxxxxxx,
channel_type=sms,
proxySession=KC1be96a19ed42aca39f9b6a9f06c26997
},
WebhookSid=WHcfc83a43a7c2424693fd0053b8b00a01
}
This is what is shows for WhatsApp message:
{
ApiVersion=2010-04-01,
SmsSid=SMb44cfdb4854c41e9ee255032a5449199,
SmsStatus=received,
SmsMessageSid=SMb44cfdb4854c41e9ee255032a5449199,
NumSegments=1,
From=whatsapp:+44798xxxxxxx,
To=whatsapp:+1228xxxxxxx,
MessageSid=SMb44cfdb4854c41e9ee255032a5449199,
Body=Test Message,
AccountSid=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
NumMedia=0
}
As you can see, the ChannelAttributes and ChannelSid are missing, and this is what Flex uses.
I then tried to transform the response with a function:
exports.handler = function(context, event, callback) {
let response;
if (!event.message.ChannelAttributes) {
response = {
name: event.message.From,
channelType: 'sms',
channelSid: 'CHbc79143368db4680a66c6c504103619f'
};
}
else {
response = {
name: "WhatsApp_" + event.message.ChannelAttributes.from,
channelType: event.message.ChannelAttributes.channel_type,
channelSid: event.message.ChannelSid
};
}
const twilioResponse = new Twilio.Response();
twilioResponse.setStatusCode(200);
twilioResponse.appendHeader('Content-Type', 'application/json');
twilioResponse.setBody(response);
callback(null, twilioResponse);
};
And assign the attributes in Studio like:
{
"name":"{{widgets.MyFunction.body.name}}",
"channelType":"{{widgets.MyFunction.body.channelType}}",
"channelSid":"{{widgets.MyFunction.body.channelSid}}"
}
Unfortunately, this shows the same error.
I am trying to develop an add-in for Microsoft Word Online. I am using Office.context.auth.getAccessTokenAsync call to get access token of a user, but it throws
error: Object {
name: "API Not Supported",
message: "This browser does not support the requested API.",
code: 5009
}
status: "failed"
Can anyone help?
Here is code that I am using to get Token.
"use strict";
(function() {
// The initialize function is run each time the page is loaded.
Office.initialize = function(reason) {
$(document).ready(function() {
// Use this to check whether the API is supported in the Word client.
if (Office.context.requirements.isSetSupported("WordApi", 1.1)) {
// Do something that is only available via the new APIs
$("#buttonPressed").click(getToken);
} else {
// Just letting you know that this code will not work with your version of Word.
$("#supportedVersion").html("This code requires Word 2016 or greater.");
}
});
};
function getToken() {
if (Office.context.requirements.isSetSupported("IdentityAPI", 1.1)) {
console.log("Yes Identity API is supported");
// code to request an SSO token.
Office.context.auth.getAccessTokenAsync(function(result) {
if (result.status === "succeeded") {
var token = result.value.accessToken;
console.log(token);
} else {
console.log("Error obtaining token", result.error);
}
});
} else {
console.log(" ID API not supported.");
}
}
})();
My manifest code placed above </VersionOverrides>
<WebApplicationInfo>
<Id> <My App ID is here> </Id>
<Resource>api://localhost:3000/<My App ID is here></Resource>
<Scopes>
<Scope>Files.Read.All</Scope>
<Scope>offline_access</Scope>
<Scope>openid</Scope>
<Scope>profile</Scope>
</Scopes>
</WebApplicationInfo>
Also tried
<Resource>https://localhost:3000</Resource>
in above code.
The user will click on a button that will invoke the Parse Cloud function sendText()
I've tried both Live Twilio and Testing Twilio accSID and authToken
I first initialize my Twilio by:
var Twilio = require('twilio');
Twilio.initialize('accountSid', 'authToken'); //put in my corresponding <<
then I set the Parse function by:
Parse.Cloud.define('sendText', function(request, response) {
Twilio.sendSMS({
From: '+1234567890', //From Number
To: "+0987654321", //To Number
Body: "Start using Parse and Twilio!" //Message <<
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
}
It would be great to have someone tell me if something here is wrong or if there are other approaches in sending SMS through Twilio via Parse Cloud.
On the SMS Summary on Twilio, it does not even know any SMS being sent out.
Going on...
The button that calls this cloud function is:
<button type="button" class="page-scroll btn btn-xl" onclick="saveData()">CONFIRM</button>
and the js function that is called saveData() is:
function saveData() {
booking.save({
something: something,
}, {
success: function (booking) {
window.location.href = 'final.php';
Parse.Cloud.run('sendText',
{
something: something
});
},
error: function (booking, error) {
alert('Failed to save');
}
});
}
NO ERROR LOG
Twilio developer evangelist here.
You seem to be using an old Parse module which is no longer supported by us. The new module however uses a newer version of our Node module.
Some documentation for it can be found here
It also has some sample code to do what you're trying to do.
// Require and initialize the Twilio module with your credentials
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');
// Send an SMS message
client.sendSms({
to:'+0987654321',
from: '+1234567890',
body: 'Hello world!'
}, function(err, responseData) {
if (err) {
console.log(err);
} else {
console.log(responseData.from);
console.log(responseData.body);
}
}
);
I think you will find your SMS will be sent using this version of the code. Notice how the initialization is different.