twitch js count the number of gift subscriptions - node.js

I am making a bot for the twitch platform, and now I have reached gift subscriptions, now I have the following command:
client.on('subgift', (channel, username, streakMonths, recipient, methods, userstate) => {
subGiftHandler(channel, username, streakMonths, recipient, methods, userstate)
})
function subGiftHandler(channel, username, streakMonths, recipient, methods, userstate) {
client.say(channel,
`Thank you #${username} for gifting a sub to ${recipient}.`
)
}
It's good when they give only one subscription at a time. But when, let's say, 10 subscriptions are given, and there are 10 such messages from the bot, it will be so-so.
How can I get the number of gift subscriptions, and add this to the condition to display a different message if there are more than one subscription?
I tried const senderCount = userstate["msg-param-sender-count"]
but it only returns false.
And if const senderCount = ~~userstate["msg-param-sender-count"]
then it only returns 0.
I using tmi.js

Related

React-JS StripeCheckout get the Customer ID/Charge ID after successful purchase

I'm trying to get the Customer ID/Charge ID after the purchase and to send the Customer ID/Charge ID in database for future use.
import StripeCheckout from 'react-stripe-checkout';
onToken = async (token) => {}
<StripeCheckout
stripeKey='pk_test_51JG'
token={this.onToken}
amount={this.state.grandTotal * 100}
name='Payment'/>
The recommended way is to set up a webhook endpoint and subscribe to checkout.session.completed events: https://stripe.com/docs/payments/checkout/fulfill-orders#handle-the-event
Depending on what exactly you mean by "transaction ID" the information you need is likely already contained there, or can be retrieved from Stripe using the IDs available.

Stripe - how to list active and trialing subscriptions together

I am using NodeJs with Stripe. I want to retrieve all active and trialing subscriptions of one customer in a nice way. So far I was only able to retrieve subscriptions separately.
const activeSubscriptionsObject = await stripe.subscriptions.list({
customer: customerId,
status: 'active'
});
const trialingSubscriptionsObject = await stripe.subscriptions.list({
customer: customerId,
status: 'trialing'
});
What should I do to get a subscription object that contains both trialing and active subscriptions?
You cannot retrieve two explicit status (and not others) like you've asked. The way to do this is either:
As you've done, retrieve active and trialing separately then merge the results; or,
Request the list with status=all to get everything (API ref), then filter the results yourself.
Like so:
const allSubs = await stripe.subscriptions.list({
customer: customerId,
status: 'all'
});
const statuses = ['active', 'trialing'];
const trialAndActiveSubs = allSubs.data.filter(sub => statuses.includes(sub.status));

Stripe get product_id / price_id from session object

I'm currently using Stripe Webhooks to get notified when user pays for a product. This is working fine. From the payment intent I can get the Seesion and the Customer Object. But I don't find a way to get the product_id or price_id for what the user paid.
Does someone know a way to get product_id or price_id ?
Thanks for the question. As you noticed the Session data included in the checkout.session.completed event does not include the line_items where the Price ID is associated to the Checkout Session.
line_items is one of the expandable properties, so to retrieve the Price ID you'd retrieve the Checkout Session and use expand to include the line items in the response. There is not a way to configure your webhook to have the data sent to you include this data.
There are two approaches to associating a customer's purchase with a Checkout Session. First, you could store the ID of the Checkout Session in your database alongside the cart or list of items purchased by the customer. That way you if a checkout session is successful, you can look up the cart by ID and know which items were purchased.
Alternatively you could listen for the checkout.session.completed webhook event, then when you receive a new notification for a successful checkout, retrieve the Session with expand then use the related price data.
Using stripe-node that would look like the following:
const session = await stripe.checkout.sessions.retrieve(
'cs_test_xxx', {
expand: ['line_items'],
},
);
// note there may be more than one line item, but this is how you access the price ID.
console.log(session.line_items.data[0].price.id);
// the product ID is accessible on the Price object.
console.log(session.line_items.data[0].price.product);
To take this a step further, if you wanted more than just the ID of the product, you could also expand that by passing line_items.data.price.product which would include the line items their related prices and the full product objects for those prices.
While creating the Payment Intent, you can store additional information about the object in the metadata field.
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
payment_method_types: ['card'],
metadata: {
product_id: '123',
price_id: '20',
},
});
Once the payment is done, you can retrieve this information from the metadata field.
You can do the same for the Session Object as well.
cjav_dev answer is great! Here is the PHP code for the same.
$event = \Stripe\Event::constructFrom(
json_decode($payload, true), $sig_header, $endpoint_secret
);
$eventObject = $event->data->object;
$stripe = new StripeClient('testsk_ssdfd...sdfs');
$csr = $stripe->checkout->sessions->retrieve($eventObject->id,
['expand' => ['line_items']]
);
$priceid = $csr->line_items['data'][0]['price']['id'];
Note the above is only retrieving the 1st line item. You may have to do a loop for all items.

How to query all active / online users?

According to the documentation, it seems that one needs to indicate the users list that we want to query e.g.:
const response = await client.queryUsers({ id: { $in: ['john', 'jack', 'jessie'] } });
In this example, we need to indicate that we want the details of these 3 users. Is there a way to query all active users instead of passing an array of ids / names?
I tried:
const response = await client.queryUsers(
{ presence: true },
);
But it returned an empty string.
presence: true registers your client to presence events (online/offline).
There is no support to get this in one go. Also, beware if user is hidden, the user is requesting this information might not be able to see the real online users.
Current recommendation is to get channel with state: true and iterate your members and also setting presence: true, you will be notified by status changes.

How to get a customer's ID from a webhook with Braintree?

How can I get a customer's ID from a webhook notification from Braintree?
For example, I can do the following to get their ID:
gateway.webhookNotification.parse(sampleNotification.bt_signature, sampleNotification.bt_payload, (err, webhookNotification) => {
let customerId = webhookNotification.subject.subscription.transactions[0].customer.id;
});
But this requires the user to have at least one transaction first. How can I get a customer's ID if they do not have any transactions yet (eg. a new user)?
Here is the response when logging webhookNotification:
WebhookNotification {
timestamp: '2017-04-30T11:01:33Z',
kind: 'subscription_charged_unsuccessfully',
subject: {
subscription: {
id: 'jywgnr',
transactions: [],
addOns: [],
discounts: []
}
},
subscription: Subscription {
id: 'jywgnr',
transactions: [],
addOns: [],
discounts: []
}
}
Looks like you are using the subscription webhook. That appears to return a payment method token in the payload, which you can use in paymentMethod.find() call.
From that paymentMethod.find('token') result object, you can retrieve the customer_id.
EDIT: Looks like because the subscription was unsuccessful, there is no payment method token in that webhook. There is, though, a subscription ID, which you can use in a Subscription.find() API call, which will certainly return a result object that contains a payment method token.

Resources