Thanks! I referred the code of the extension tutorial AskACaster
router.post('/question', async (req, res) => {
console.log(req.body);
let {channelId, clientId} = req.body.auth;
console.log(channelId);
let token = app.getToken(req);
console.log(token);
let put = await postQuestion(req.body);
let twitchpubsubPost = await postToTwitchPubSub('newquestion', token, channelId, clientId);
console.log(twitchpubsubPost)
res.json(put);
})
The token they used here is from auth.token
.
But anyway I used the jwt I generated in backend using the code below:
const secret = Buffer.from('my-extension-secret', 'base64')
router.post('/pubsub', async (req, res) => {
console.log(req.body);
try {
let { channel_id, client_id } = await req.body;
let serverToken = makeServerToken(channel_id)
let requestPubSub = await reqPubSub('newquestion', serverToken, channel_id, client_id);
console.log("requestPubSub: ", requestPubSub)
res.json(serverToken);
}
catch (e) {
console.log(e)
}
})
const reqPubSub = async (message, serverToken, channelId, clientId) => {
request.post({
url: `https://api.twitch.tv/extensions/message/${channelId}`,
headers: {
Accept: 'application/vnd.twitchtv.v5+json',
Authorization: 'Bearer ' + serverToken,
'Client-ID': clientId,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: message,
content_type: 'application/json',
targets: ['broadcast']
}),
gzip: true
}, function (e, r, b) {
if (e) {
console.log(e);
} else if (r.statusCode == 204) {
console.log('Ok to ' + channelId);
} else {
console.log('Got ' + r.statusCode + ' to ' + channelId);
console.log(b);
}
});
}
function makeServerToken(channelId) {
const payload = {
exp: Math.floor(new Date().getTime() / 1000) + 600,
channel_id: String(channelId),
role: 'external',
pubsub_perms: {
send: ['broadcast']
}
};
return jwt.sign(payload, secret);
}
I used PostMan to test, backend logged Ok to xxx
. But nothing shows up at frontend. I have a listen in componentDidMount()
:
if (this.twitch) {
this.twitch.listen('broadcast', (target, contentType, body) => {
this.twitch.rig.log(`New PubSub message!\n${target}\n${contentType}\n${body}`)
})
}
I have this error when I refresh my page:
Uncaught (in promise) ERR_BADAUTH
value @ twitch-ext.min.js:22
value @ twitch-ext.min.js:1
value @ twitch-ext.min.js:22
This error comes out only when the page is refreshed not when I send to PubSub.
But it says bad auth
so I assume the token from EBS does not work?
Is there anything wrong in my code when generating token?