YouTube Data API: add a subscription - youtube-data-api

I'm using YouTube's V3 Data API to add a subscription to a channel. This occurs on a Wordpress installation.
I added Google APIs (for oauth) on Wordpress theme functions:
wp_enqueue_script( 'googleapi', 'https://apis.google.com/js/client.js?onload=googleApiClientReady', array(), '1.0.0', true );
I added in the same way the oauth javascript file, which is the first one here: https://developers.google.com/youtube/v3/code_samples/javascript.
Following this guide(https://developers.google.com/youtube/v3/docs/subscriptions/insert (Apps Script)), I extended the OAuth js with the addSubscription method.
Google Client API seems to be loaded and working as it calls correctly googleApiClientReady on the oauth javascript.
So, this is how the subscription is being inserted:
OAUTH JAVASCRIPT
... ... ...
// After the API loads
function handleAPILoaded() {
addSubscription();
}
function addSubscription() {
// Replace this channel ID with the channel ID you want to subscribe to
var channelId = 'this is filled with the channel ID';
var resource = {
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelId
}
}
};
try {
var response = YouTube.Subscriptions.insert(resource, 'snippet');
jQuery('#success').show();
} catch (e) {
if(e.message.match('subscriptionDuplicate')) {
jQuery('#success').show();
} else {
jQuery('#fail').show();
alert("Please send us a mail () with the following: ERROR: " + e.message);
}
}
So, the first error comes with
YouTube.Subscriptions.insert(resource, 'snippet')
It says YouTube is not defined. I replaced it with:
gapi.client.youtube.subscriptions.insert(resource, 'snippet');
And that error went away. When checking response, as the subscription isn't completed, this is what I get
{"wc":1,"hg":{"Ph":null,"hg":{"path":"/youtube/v3/subscriptions","method":"POST","params":{},"headers":{},"body":"snippet","root":"https://www.googleapis.com"},"wc":"auto"}}
So, I would like to know what's happening on that POST request and what's the solution to this.
I can post the full OAuth file, but it's just as in the example, plus that addSubscription method at the end.

Okay, I got it working, the problem was on the POST request. Here is the full method working:
// Subscribes the authorized user to the channel specified
function addSubscription(channelSub) {
var resource = {
part: 'id,snippet',
snippet: {
resourceId: {
kind: 'youtube#channel',
channelId: channelSub
}
}
};
var request = gapi.client.youtube.subscriptions.insert(resource);
request.execute(function (response) {
var result = response.result;
if (result) {
// alert("Subscription completed");
}
} else {
// alert("Subscripion failed");
// ...
}
});
}
Also make sure to load Google Apps API (in fact without it the authorize/login button won't work) and jQuery.

Any chance you can post everything that made this work...all the JS entire auth.js save for your private keys, im working on this exact problem.

Related

Make outbound Teams PSTN call - Azure Communication Services Teams Interoperability

I try to implement a PSTN call feature using Azure Communication Services Teams Interoperability referring this sample code and use case:
https://github.com/Azure-Samples/communication-services-javascript-quickstarts/tree/main/add-1-on-1-cte-video-calling
https://learn.microsoft.com/en-us/azure/communication-services/concepts/interop/custom-teams-endpoint-use-cases#use-case-1-make-outbound-teams-pstn-call
I added the following code to the sample, but I got an error.
startPSTNButton.addEventListener('click',async () => {
try {
console.log('PSTN IN');
const pstnCallee = { phoneNumber: '+81311112222' }
const oneToOneCall = teamsCallAgent.startCall([pstnCallee], { threadId: '00000000-0000-0000-0000-000000000000' });
console.log('Call out');
// Subscribe to the call's properties and events.
subscribeToCall(oneToOneCall);
} catch (error) {
console.error(error);
}
});
Error:
CallingCommunicationError: Starting a one to one with thread ID is invalid.
at TeamsCallAgentImpl.startCall (sdk.bundle.js:183:140138)
at W.value (sdk.bundle.js:161:2267)
at HTMLButtonElement. (client.js:311:1) (anonymous) # client.js:317
Is threadId: '00000000-0000-0000-0000-000000000000' correct?
How to fix the error?
I found it out, and threadId is not required.
https://github.com/Azure/Communication/blob/master/releasenotes/acs-javascript-calling-library-release-notes.md#170-beta1-2022-08-01
const phoneCallee = { phoneNumber: '<PHONE_NUMBER_E164_FORMAT>' }
const oneToOneCall = teamsCallAgent.startCall(phoneCallee );
I try this, and it works fine.

Window object is undefined after deploy to netlify

I want to build an email verification. After the user registers, the user gets an email and clicks on it for verification purposes. The email-link invokes a netlify lambda function (api end point). Inside the link is a jwt token, which I decode on the backend. I used
window.location.href
for it and sliced the part I needed and decoded it. On localhost, it works fine, however, if I deploy it to netlify, I get an
window is undefined
error. I read that you have to check for
typeof window !== 'undefined'
However, if I add that to my lambda function I don't get any console.log statements.
exports.handler = async (event, context, callback) => {
if (typeof window !== 'undefined') {
let url = window.location.href
let index = url.indexOf("=");
let token = url.slice(index+1)
console.log(token, 'token here')
const decoded = jwt.verify(token, process.env.SECRET);
console.log('confirm registration route triggered',decoded)
if (decoded) {
const { email } = decoded;
console.log(decoded, 'decoded here')
User.findOneAndUpdate({email: email}, {verified: true },(...e)=>{
console.log(e)
});
} else {
console.log('could not update user')
//redirect user to page with message about email confirmation link expiration
//and proposal to register again
}
console.log('confirm registration got invoked')
}
return {
statusCode: 400,
body: "Oops"
}
};
I read that the function first runs on the server when deployed and afterwards on the client. Seems like it does not run on my client, as I invoke the api-endpoint directly? I'm quite a beginner when it comes to API-Endpoints, thanks for reading!
In case you have the same issue when deploying to netlify, you have to run
event.queryStringParameters
which gives you access to the query parts of your url.

How can I access `figma.clientStorage` in a Figma Plugin UI?

In my plugin code (code.ts), I am using the ClientStorage Figma Plugin API to store some state.
How can I read data from clientStorage from UI code (ui.html)?
I am not sure that you can access clientStorage directly from the UI, but you can pass the stored value from code.ts to ui.html using figma.ui.postMessage.
Here is an example of code that is retrieving a value from clientStorage, and sending it to the UI:
function retrieveFromStorage() {
(async () => {
try {
var item = await figma.clientStorage.getAsync('item');
figma.ui.postMessage({ type: 'send-item', payload: item);
} catch (err) {
console.log(err);
}
}})();
}
And then you can access it in the UI like so:
if(event.data.pluginMessage.type == 'send-item') {
var item = event.data.pluginMessage.payload
}
In this example I am also using "type" to make sure I am receiving the correct message.

Fitbit URL callback giving a response of NULL

I'm having trouble getting a response from a callback uri and I would really appreciate any help you could give me.
I am trying to use the Fitbit API which requires you to use a callback url to get an Auth Code.
Workflow:
1. Go to Fitbit url to get user to allow the app access to their personal data.
2. User agrees to the conditions
3. User gets redirected to my API
4. The API returns the code from (Code is located in URL and I can access it)
5. I console.log the code out to verify it
6. API returns the code
7. I work with code then exchanging it for an access token.
The problem is that I don't return the code (Or anything )when I return to the app even though I can console.log it on the API. The response I get is NULL
Here is the URL:
url = "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=https://REDIRECT_URL&scope=activity%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight&expires_in=604800";
I then open the URL in the InAPPBrowser successfully:
if (url !== "") {
const canOpen = await Linking.canOpenURL(url)
if (canOpen) {
try {
const isAvailable = await InAppBrowser.isAvailable()
if (isAvailable) {
const result =InAppBrowser.open(url, {
// iOS Properties
dismissButtonStyle: 'done',
preferredBarTintColor: 'gray',
preferredControlTintColor: 'white',
// Android Properties
showTitle: true,
toolbarColor: '#6200EE',
secondaryToolbarColor: 'black',
enableDefaultShare: true,
}).then((result) => {
console.log("Response:",JSON.stringify(result))
Linking.getInitialURL().then(url => {
console.log("Tests: ",url)
this._setTracker(url as string);
});
})
} else Linking.openURL(url)
} catch (error) {
console.log("Error: ",error)
}
}
}
From here the URL opens successfully.
Here is the API now which is done in Typescript on AWS serverless and Lambda
export const handler: APIGatewayProxyHandler = async (event, _context, callback) =>{
let provider = event.path
//prints code
let x = event.queryStringParameters
console.log("Code: ",x)
const response = {
statusCode: 200,
body: "Success"
};
return response;
}
Please let me know if further detail is required?
Thank you!
Right so it turns out what I was doing was correct apart from the response should have been 301 which is a redirect response.
const response= {
statusCode: 301,
headers: {
"location": `app://CALLBACK RESPONSE ADDRESS?type=${provider}`
},
body: "Boom"
}

Cannot get the getCallbackTokenAsync to function correctly

I am a newbie to outlook js. I am developing a very simple add-in. The add-in simply will forward a selected email to a defined email address. So we click a button and forward the message. My command handler gets called, but that is about all I have gotten to work. The first problem is the authorization does not appear to work. I have followed the example on https://learn.microsoft.com/en-us/outlook/add-ins/use-rest-api.
The permission in my manifest is set to ReadWriteMailbox.
var accessToken;
Office.onReady(info => {
// If needed, Office.js is ready to be called
Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function(result) {
if (result.status === "succeeded") {
accessToken = result.value;
} else {
accessToken = "error";
}
});
});
function MyButtonClick(event) {
const message = {
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Performed action. Access token: " + accessToken,
icon: "Icon.80x80",
persistent: true
}
Office.context.mailbox.item.notificationMessages.replaceAsync("action", message);
event.completed();
}
I have tried moving the getCallbackTokenAsync all around, but it seems not to work properly. The accessToken is always undefined.
I have been messing with this for the past day. So I am assuming I am missing something.
We are primarily targeting Outlook 2016 on the mac and windows 10.
Any thoughts?
Tom

Resources