Create Stripe Charge for Connected Account - No Such Customer - javascript

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.

Related

create payment with the token of a saved card and 3d secure

I have integrated Stripe for payments.
I managed to save a card by obtaining the token, created the customer, and associated the token with the customer.
Now I am trying to make a backend (node) side payments using this code:
const createCharge = await stripe.charges.create({
amount,
currency: 'eur',
customer: user.stripeCustomerId,
card: cardId,
description: `userId: ${user._id}`,
});
If the card does not require authentication it works perfectly while if authentication is required it obviously fails with the error: authentication_required.
I tried to add authentication with 3d secure in-app but without success, this is what I tried but I always get errors and no authentication is done
const { paymentIntent, error } = await confirmPayment(clientSecret.client_secret, {
payment_method_options:{
"card": {
"installments": null,
"network": null,
"request_three_d_secure": "any"
}
},
type: 'Card',
cardDetails: this.props.cardList[0].cardId,
payment_method:'creditCard',
setupFutureUsage: 'OffSession',
});
Does anyone have any idea what I'm doing wrong?
Thanks!

Getting values from my web chat call in my website using backchannel

I'm trying to integrate the backchannel and getting the values.
https://github.com/Microsoft/BotFramework-WebChat/tree/master/samples/15.d.backchannel-send-welcome-event
I also tried this. Get URL Referer and Origin header from Microsoft Bot Framework
I also tried deserializing the values still not able to get the data.
how can i get the language values?
here's my sample code:
var userinfo = {
id: 'user-id',
name: 'user name',
locale: 'es'
};
var botConnection = new BotChat.DirectLine({
token: 'mytoken',
user: userinfo,
locale: 'es'
});
BotChat.App({
botConnection : botConnection,
user: userinfo,
bot: { id: 'bot-id', name: 'bot name' },
}, document.getElementById('botDiv'));
botConnection
.postActivity({
from: userinfo,
name: 'ConversationUpdate',
type: 'event',
value: '',
})
.subscribe(function (id) {
console.log('"trigger ConversationUpdate" sent');
});
The purpose of this I want to pass the locale to my bot from my website.
just like in the emulator.
Thanks!
I would recommend adding the locale to the back channel event's channel data. That way on the bot side you can simply access the locale in the incoming activity without having to deserialize any JSON objects when you receive the event. Note, you can also use text or value in place of channelData. See the code snippets below.
BotChat Back Channel Event
// Send back channel event
botConnection.postActivity({
from: userinfo,
name: 'setLocale',
type: 'event',
channelData: "es"
}).subscribe(id => console.log(id));
Bot - C#
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
...
} else if (turnContext.Activity.Type == "event") {
// Check for `setLocale` events
if (turnContext.Activity.Name == "setLocale") {
await turnContext.SendActivityAsync($"Your locale is set to {turnContext.Activity.ChannelData}");
}
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
}
}
Hope this helps!

Google datastore entity creation and update

I am attempting to update an entity in my datastore kind using sample code from here https://cloud.google.com/datastore/docs/reference/libraries. The actual code is something like this:
/ Imports the Google Cloud client library
const Datastore = require('#google-cloud/datastore');
// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';
// Creates a client
const datastore = new Datastore({
projectId: projectId,
});
// The kind for the new entity
const kind = 'Task';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);
// Prepares the new entity
const task = {
key: taskKey,
data: {
description: 'Buy milk',
},
};
// Saves the entity
datastore
.save(task)
.then(() => {
console.log(`Saved ${task.key.name}: ${task.data.description}`);
})
.catch(err => {
console.error('ERROR:', err);
});
I tried to create a new entity using this code. But when I ran this code and checked the datastore console, there were no entitites created.Also, I am unable to update an existing entity. What could be the reason for this?
I am writing the code in Google Cloud Functions.This is the log when I run this function:
{
insertId: "-ft02akcfpq"
logName: "projects/test-66600/logs/cloudaudit.googleapis.com%2Factivity"
operation: {…}
protoPayload: {…}
receiveTimestamp: "2018-06-15T09:36:13.760751077Z"
resource: {…}
severity: "NOTICE"
timestamp: "2018-06-15T09:36:13.436Z"
}
{
insertId: "000000-ab6c5ad2-3371-429a-bea2-87f8f7e36bcf"
labels: {…}
logName: "projects/test-66600/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2018-06-15T09:36:17.865654673Z"
resource: {…}
severity: "ERROR"
textPayload: "Warning, estimating Firebase Config based on GCLOUD_PROJECT. Intializing firebase-admin may fail"
timestamp: "2018-06-15T09:36:09.434Z"
}
I have tried the same code and it works for me. However, I have noticed that there was a delay before the entities appeared in Datastore. In order to update and overwrite existing entities, use .upsert(task) instead of .save(task) (link to GCP documentation). You can also use .insert(task) instead of .save(task) to store new entities.
Also check that the project id is correct and that you are inspecting the entities for the right kind.

Laravel 5.1 Cashier - Adds customer but without info

I am using Laravel 5.1 trying to set it up with Stripe using Cashier.
I am using a custom button to execute the javascript (using Angular):
$scope.subscribe = function(plan){
var handler = StripeCheckout.configure({
key: 'pk_test_*************',
image: '/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
var data = 'stripeToken=' + token.id;
$http.post("/createSubscription", data).success(function(data, status) {
console.log(data);
});
}
});
handler.open({
name: 'basic',
description: 'basic monthly $100',
currency: "usd",
amount: 10000
});
$(window).on('popstate', function() {
handler.close();
});
};
And in my Laravel code I have:
public function createSubscription(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
$token = Input::get('stripeToken');
$user->subscription("basic_plan")->create($token);
return 'test';
}
But I keep getting an error saying "this customer has no attached payment source".
The returned token at this line:
token: function(token) {
...
Does contain the users email, card info (+ card token), and stripe token. But when I check my Stripe dashboard, a customer is added without any data (no card, no email and not set up with the subscription).
I am trying to create customers with a subscription plan via this form.
(I do have the Billable trait set up and included in the controller)

Stripe javascript API Stripe.Recipients undefined

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.

Categories