Skip to content

Instantly share code, notes, and snippets.

@furious
Last active February 9, 2021 12:59
Show Gist options
  • Save furious/d284d67af89a00866fa60c318a84bf50 to your computer and use it in GitHub Desktop.
Save furious/d284d67af89a00866fa60c318a84bf50 to your computer and use it in GitHub Desktop.
Twitch - Current Payout (Dashboard)
// ==UserScript==
// @name Twitch - Current Payout (Dashboard)
// @namespace twitchpayout
// @version 1.5.1
// @description Shows current accumulated/estimated payout revenue and last payment on dashboard
// @author FURiOUS
// @homepage https://furious.pro
// @downloadURL https://gist.github.com/furious/d284d67af89a00866fa60c318a84bf50/raw/frs-twitch_current_payout_dashboard.user.js
// @supportURL https://twitch.tv/furious
// @match https://dashboard.twitch.tv/u/*
// @require https://code.jquery.com/jquery-1.12.4.min.js
// @require https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js
// @grant GM_xmlhttpRequest
// @run-at document-idle
// ==/UserScript==
(function() {
'use strict';
var userinfo = Cookies.getJSON('twilight-user');
var client_id = 'kimne78kx3ncx6brgo4mv6wki5h1ko';
jQuery.ajax({
url: 'https://gql.twitch.tv/gql',
method: 'POST',
headers: { 'client-id': client_id, 'authorization': `OAuth ${userinfo.authToken}`, 'content-type': 'application/json'},
data: JSON.stringify({query: "{ currentUser { payoutBalance { currency currentPayoutBalanceAmount month year } payout { history { iframeURL } } } }"}),
dataType: 'json',
success: function(response,x,s){
var data = response.data;
if(data.currentUser){
var payment_info = jQuery(`<div id="last_payout_info" style="cursor: pointer" title="Fetching last payment data..." class="sunlight-tile tw-flex tw-flex-column tw-full-height tw-full-width tw-justify-content-center tw-pd-x-1 tw-pd-y-05"><p class="sunlight-tile__title tw-c-text-alt-2 tw-ellipsis tw-font-size-6">Estimated Payout:</p><p class="sunlight-tile-body-text tw-c-text-inherit tw-ellipsis tw-font-size-4" id="last_payment">US$ ${data.currentUser.payoutBalance.currentPayoutBalanceAmount.toFixed(2)}</p></div></span>`);
payment_info.on('click', () => { window.location.href = 'https://dashboard.twitch.tv/channel-analytics/payouts'; });
jQuery('nav.sunlight-top-nav div.tw-pd-r-1').prepend(payment_info);
payments(data.currentUser.payout.history.iframeURL);
}
}
});
function payments(url){
if(url == null){
jQuery("#last_payment_info").attr('title', `Not received yet`);
//jQuery('#last_payment').text(`Unavailable`);
//current_revenue((new Date("2016-01-01")).toISOString(), (new Date()).toISOString());
return;
}
GM_xmlhttpRequest({
method: "GET",
url: url,
headers: { "User-Agent": navigator.userAgent },
onload: function(r) {
// parse headers
var headers = {};
for(var h of r.responseHeaders.split(/[\r\n]+/)){
var val; if(val = h.match(/([^:]+): ?(.+)/)) headers[val[1]] = val[2];
}
parse(headers);
}
});
}
function parse(headers){
GM_xmlhttpRequest({
url: 'https://ui2.tipalti.com/PayeePaymentHistory/GetPayeePaymentHistory',
method: 'POST',
headers: {'content-type': 'application/json', 'authorizationtoken': headers['authorizationtoken']},
data: JSON.stringify({ pagingData: { PageCount: 1, PageSize: 1 } }),
onload: function(r){
try {
var payouts = JSON.parse(r.responseText);
var last_payment = payouts.payeePaymentHistoryIFrameModels[0];
var start_date = new Date('2016-10-01');
var payment_date = "Since: " + start_date.toLocaleDateString('pt-BR');
var end_date = new Date();
var last_amount = "Not received yet";
if(last_payment){
start_date = new Date(last_payment.date);
payment_date = start_date.toLocaleDateString('pt-BR');
start_date.setDate(1); // check Twitch Help FAQ about Net15 payments
last_amount = `US$ ${last_payment.amountSubmitted.amount}`;
//current_revenue(start_date.toISOString(), end_date.toISOString());
} else {
//current_revenue(start_date.toISOString(), end_date.toISOString());
}
jQuery("#last_payment_info").attr('title', `Latest payment: ${last_amount} (${payment_date})`);
} catch(e) {
console.log(e);
}
}
});
}
function current_revenue(start_date, end_date){
jQuery.ajax({
url: `https://api.twitch.tv/kraken/channels/${userinfo.id}/dashboard/revenues?fraction=day&start_date=${start_date}&end_date=${end_date}`,
method: 'GET',
headers: { 'accept': 'application/vnd.twitchtv.v5+json', 'client-id': client_id, 'authorization': `OAuth ${userinfo.authToken}`, 'content-type': 'application/json' },
dataType: 'json',
success: function(d,x,s){
var total_rev = 0;
for(var subs of d.twitch_subscriptions){
total_rev += sum_revenue(subs.revenue);
}
for(var gifts of d.gift_subscriptions){
total_rev += sum_revenue(gifts.revenue);
}
for(var mgifts of d.multi_month_gift_subscriptions){
total_rev += sum_revenue(mgifts.revenue);
}
total_rev += sum_revenue(d.prime_subscriptions);
total_rev += sum_revenue(d.ads);
total_rev += sum_revenue(d.bits);
total_rev += sum_revenue(d.bounty_board);
total_rev += sum_revenue(d.game_commerce);
total_rev += sum_revenue(d.extensions);
total_rev += sum_revenue(d.polls);
total_rev = (total_rev / 100).toFixed(2);
jQuery('#last_payment').text(`US$ ${total_rev}`);
}
});
}
function sum_revenue(revenues){
var total = 0;
for(var rev of revenues){
total += rev.amount;
}
return total;
}
})();
@furious
Copy link
Author

furious commented Jul 4, 2020

Changelog

1.5.1

  • Fixed visual bug caused by Twitch design updates

1.4

  • Using payout balance calculated by Twitch (now available in their GraphQL)
  • Info now links to the payment page, since now they're showing more details about your payout balance

1.3

  • Display when user doesn't have any revenue information (not an affiliate/partner)

1.2

  • Fixes information style issues on the navbar
  • Fetches revenue data from the first day of the month from the last payment received date (check Twitch Help FAQ about Net15 payments)

1.1

  • Users that never received payments will now show the current revenue since Twitch started using Tipalti API (October 2016)

1.0

  • Initial release

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment