How to use the yammer API for subscription - subscription

I am totally new to yammer API. I need the subscription code, i've created a code but its not at all working, I am stucked in it. please help me out. The following is the code which i used.
yam.config({appId: "Kcab3g7Y5P1y1g0H05Bve"});
function post() {
yam.getLoginStatus( function(response) {
var target_id = '4583632';
var target_user = "user";
if (response.authResponse) {
yam.request(
{
url : "https://www.yammer.com/api/v1/subscriptions"
, method: "GET"
, data: { target_id : target_id,target_type:target_user }
, success: function (msg) {
for(var key in msg) {
var value = msg[key];
alert("success "+value);
}
}
, error: function (msg) {
for(var key in msg) {
var value = msg[key];
alert("err "+value);
}
}
}
);
}
});
}
Waiting for the reply. Thanks.

It's not clear from the code you posted exactly what you are trying to do. The following code illustrates how you can check if the currently logged on user is following (subscribed to) another Yammer user with the id: 1514517708. I discovered the id for the user by looking at the user in my Yammer network on the Yammer website and copying the user's feedId from the URL. For this to work you'll need to use an id for a user in your Yammer network and also replace the appId value with the id of the app you configure in your network.
<html>
<head>
<title>A Yammer App</title>
<script src="https://assets.yammer.com/platform/yam.js"></script>
<script>
yam.config({ appId: "[your appId goes here]" });
</script>
</head>
<body>
<button onclick='post()'>Check following!</button>
<script>
function post() {
yam.getLoginStatus(function (response) {
if (response.authResponse) {
check_subscription_to_user(1514517708);
} else {
yam.login(function (response) {
if (!response.authResponse) {
check_subscription_to_user(1514517708);
}
});
}
});
};
function check_subscription_to_user(id) {
yam.request(
{
url: "https://www.yammer.com/api/v1/subscriptions/to_user/" + id + ".json"
, method: "GET"
, success: function (msg) { alert("You are following: " + id); }
, error: function (msg) { alert("You are not following" + id); }
}
);
};
</script>
</body>
</html>
For other operations on subscriptions, see the REST API docs here: https://developer.yammer.com/restapi/#rest-subscriptions

Related

Ionic FB account kit login with sms

I work with FB account kit and I get error on button click : AccountKit SDK was not initialized. Call AccountKit.init first. And I realize when i test in browser when I come to same page and do refresh and click button its working without error. Or maybe someone can help me with code with FB account kit:
.controller('RegistrationCtrl', function($scope, $http, $ionicPopup) {
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:mycode,
state:"{{csrf}}",
version:"v1.0"
}
);
console.log("{{csrf}}")
};
$scope.loginWithSMS = function() {
AccountKit.login("PHONE",{}, loginCallback);
function loginCallback(response) {
console.log(response);
if (response.status === "PARTIALLY_AUTHENTICATED") {
document.getElementById("code").value = response.code;
document.getElementById("csrf_nonce").value = response.state;
document.getElementById("my_form").submit();
}
else if (response.status === "NOT_AUTHENTICATED") {
}
else if (response.status === "BAD_PARAMS") {
}
}
}
$scope.submit = function(){
$scope.data = {};
$http.post(app4travel.apiUrl + '/register_mobile')
.success(function(response, status, headers, config) {
console.warn('Sent')
console.warn(response)
console.warn(status)
$scope.response = response.data;
})
}
})
Firstly, In the FB's document:
CSRF protection: The {{csrf}} placeholder above should be replaced with a non-guessable value which should originate in the app's server, and be passed to the login flow. It is returned back to the app client unchanged, and the app client can pass it back to server to verify the match with the original value.
Secondly: Check why: AccountKit.init not called.
Solved problem, i just called Account Kit.init function in index.html(main) and it works.
<script type="text/javascript">
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:id,
state:"{{csrf}}",
version:"v1.1"
}
);
console.log("{{csrf}}")
};
</script>

Make facebook posts with ionic/angular app

I'm creating an app with the ionic framework and integrate the facebookConnectPlugin for login and making posts to a fan page.
The login part is working properly, I can see the user data and display on the app. The problem I'm having is when I try to make a post to facebook.
This is the complete controller that manage the login and the post
.controller('signupCtrl', function($scope, $state, $q, UserService, $ionicLoading){
// This is the success callback from the login method
var accesstoken;
var fbLoginSuccess = function(response){
if (!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
accesstoken = authResponse.accessToken;
getFacebookProfileInfo(authResponse).then(function(profileInfo){
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture: "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
}, function(fail){
// Fail get profile info
alert('profile info fail ' + fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
alert('fbLoginError ' + error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse){
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function (response) {
console.log(response);
info.resolve(response);
},
function (response) {
console.log(response);
info.reject(response);
}
);
return info.promise;
};
//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function(){
console.log('---> facebookSignIn');
facebookConnectPlugin.getLoginStatus(function(success){
if (success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
//alert('getLoginStatus ' + success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if (!user.userID){
alert('UNO');
getFacebookProfileInfo(success.authResponse).then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture: "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
//$state.go('menu.home');
}, function(fail){
// Fail get profile info
alert('profile info fail ' + fail);
});
}else{
//alert('DOS');
$state.go('menu.home');
var fan_token = 'EAAH1eElPgZBl1jwZCI0BADZBlrZCbsZBWF5ig29V1Sn5ABsxH1o4kboMhpjZBDfKtD1lfDK1dJLcZBI4gRBOF2XGjOmWMXD0I8jtPZA4xLJNZADarOGx8fiXBRZCTOaxwBLQEwRjsvaqTtb2DTCI0Qdo3haX6vqHlJoWMZD';
console.log('access token', accesstoken);
facebookConnectPlugin.api(
'/186259017448757/feed',
'POST',
{
access_token: fan_token,
'message':'HOLA!'
},
function(response){console.log(response);alert(response.id)}
)
}
}else{
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
alert('getLoginStatus ' + success.status);
$ionicLoading.show({
template: 'Logging in...'
});
// Ask the permissions you need. You can learn more about
// FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
})
This is the part where I try to make a post to a facebook wall
facebookConnectPlugin.api('/181297057448657/feed', 'POST', {access_token: fan_token, 'message':'HOLA!'},
function(response){
console.log(response);
alert(response.id)
}
)
I went to https://developers.facebook.com/tools/explorer to generate the access tokens, tried with several tokens (user, fanpage, etc) but any seem to work. I've also used this code snippet provided in the facebook devs explorer tool
FB.api(
'/174801556748297/feed',
'POST',
{"message":"testing3"},
function(response) {
// Insert your code here
}
);
The result is always the same, I get a JSON error in the response object and no facebook post to the wall
Any help would be really appreciated!
PD: app ID's have been modified, that why they don't match. Same with the tokens and fan page ID
I used following in my app to post ,Reference https://github.com/ccoenraets/sociogram-angular-ionic
$scope.share = function () {
OpenFB.post('/me/feed', $scope.item)
.success(function () {
console.log("done");
$ionicLoading.hide();
$scope.item.message="";
$ionicLoading.show({ template: 'Post successfully on Facebook!', noBackdrop: true, duration: 2000 });
$scope.status = "This item has been shared from OpenFB";
})
.error(function(data) {
$ionicLoading.hide();
alert(data.error.message);
});
};
HTML
<div class="media-body">
<textarea placeholder="What's on your mind?" ng-model="item.message"></textarea>
</div>
<hr style="margin-top: -1px;" />
<div style="text-align:right;padding-right:20px;padding-bottom:10px;">
<button class="fb-login" ng-click="share()">Post to Facebook</button>
</div>

Angular API call fails in MEAN application

In a MEAN app I am trying to allow an authorised user (email and password login) to change their username.
I can successfully use Postman to PUT a new username to http://localhost:3000/api/users/xxxxxxxxxxxxxxxx.
But the angular code fails.
Here is the relevant part of the edit page:
<form ng-submit="user.saveUser()">
<div class="form-group">
<label> New Username</label>
<input type="text" class="form-control" ng-model="user.userData.name">
</div>
Here is the controller:
.controller('userEditController', function($routeParams, User) {
var vm = this;
vm.type = 'edit';
User.get($routeParams.user_id)
.success(function(data) {
vm.userData = data;
});
// function to save the user
vm.saveUser = function() {
vm.processing = true;
vm.message = '';
// call the userService function to update
User.update($routeParams.user_id, vm.userData)
.success(function(data) {
vm.processing = false;
// clear the form
vm.userData = {};
// bind the message from our API to vm.message
vm.message = data.message;
});
};
});
Here is the service:
// update a user
userFactory.update = function(id, userData) {
return $http.put('/api/users/' + id, userData);
};
at this point userData contains name: “Fred” or whatever was input to the form
and here is the api.js
apiRouter.route('/users/:user_id')
// get the user with that id
.get(function(req, res) {
User.findByIdAndUpdate(req.params.user_id, function(err, user) {
if (err) return res.send(err);
// return that user
res.json(user);
});
})
// update the user with this id
.put(function(req, res) {
console.error(req.params.user_id);
User.findById(req.params.user_id, function(err, user) {
if (err) return res.send(err);
// set the new user information if it exists in the request
if (req.body.name) user.name = req.body.name;
// save the user
user.save(function(err) {
if (err) return res.send(err);
// return a message
res.json({ message: 'User updated!' });
});
});
});
(I had to use findByIdAndUpdate instead of findById because of a CastError.)
Although the console states:
XHR finished loading: PUT http:/localhost/3000/api/users/user_id
The value of req.params.user_id is just user_id.
The terminal shows:
PUT /api/users/user_id 200 4.040 ms - 2273
GET /api/users/user_id - - ms - -
GET /api/users/user_id - - ms - -
GET /api/users/user_id - - ms - -
Like I say Postman can communicate with the API and can update without problems. I am stumped, and hopefully someone will put me out of my misery
I had to change tack with this one. The fact that a manually entered user_id in Postman worked should have told me that the user_id provided by the Angular code was not correct. So I made sure that the JWT included the user_id:
var token = jwt.sign({
name: user.name,
email: user.email,
user_id: user._id
Then added an api endpoint to get user information:
apiRouter.get('/me', function(req, res) {
res.send(req.decoded);
});
Then connected a service:
userFactory.get = function() {
return $http.get('/api/me/');
};
Then in the controller I could call get:
User.get()
.success(function(result) {
$scope.user_id = result.user_id;
});
$scope.user_id now has the correct user_id which I can pass into the update method:
User.update($scope.user_id, vm.userData)
.success(function(data)
So now it works as intended.

API OAuth Google Integration Access error (origin-mismatch ) for google Calendar

I am intgrating google Calendar with Angular UI Calendar, to get the data of events of google Calendar
This is my HTML
<div ng-controller="newCalendarCtrl">
<button ng-click="handleAuthClick()">Authorize</button>
<script src="https://apis.google.com/js/client.js"></script>
</div>
And this is my JS
angular.module('loginApp').controller('newCalendarCtrl', function ($scope, $log) {
var clientId = '*******'
//var apiKey = '{API KEY}';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleAuthResult(authResult) {
console.log(authResult);
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
// authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
$scope.handleAuthClick=function (event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.calendarList.list();
request.execute(function(resp){
$.each( resp.items, function( key, value ) {
console.log(resp.items[key].id);
});
});
var request1 = gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': '2015-12-23T04:26:52.000Z'//Suppose that you want get data after 23 Dec 2014
});
request1.execute(function(resp){
$.each( resp.items, function( key, value ) {
console.log(resp.items[key].id);
});
});
});
}
});
When I try to acces the data upon click Authorize Button then it goes to google login and login procedure proceed successfully but when response come then Error message comes on my page origin-mismatch .
The problem is solve .
Replace JAVASCRIPT ORIGINS - https://www.example.com with
JAVASCRIPT ORIGINS http://localhost:8080
And if you have your own Domain then replace it with your Domain and be specific of using https or http

AngularJS reload data after PUT request

Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};

Resources