Yammer Open Graph Post - How do i do it? - javascript

I am trying to figure out how the payload should be constructed for a Open Graph object to submit to yammer. I can post a standard message, but i would like to post an opengraph message instead.
{
"activity":{
"actor":{"name":"Sidd Singh",
"email":"sidd#xyz.com"},
"action":"create",
"object": {
"url":"https://www.sched.do",
"title":"Lunch Meeting"
},
"message":"Hey, let’s get sushi!",
"users":[
{"name":"Adarsh Pandit",
"email":"adarsh#xyz.com"}
]
}
}
This is some code nicked from their API documentation but doesn't show me how i should use this in javascript. Can someone assist me? Below is my existing code that posts a standard message...
yam.request({
url: "https://www.yammer.com/api/v1/messages.json?network_id=networkname", //this is one of many REST endpoints that are available
method: "POST",
beforeSend: function (req) { //send the access_token in the HTTP header
req.headers.Authorization = "Bearer " + access_token;
},
data: {
"network": "networkname",
"body": "Test Post",
"group_id": "3719771"
},
success: function (data) { //print message response information to the console
toastr.success('An Item was successfully posted to Yammer', "Yammer Network");
},
error: function (user) {
toastr.error('There was an error eith the request', "Yammer Network");
}
});

This post answered your question: Yammer Open Graph API Error 400
Simply replace the key value pairs in the data{} with the activity json strings. Also remember to change the RESTful api endpoint to https://api.yammer.com/api/v1/activity.json

Related

PayPal Orders API Express Checkout - CaptureOrder ID issue

bit of a beginner with some of this, but I am struggling understanding some of the walk throughs on the Paypal API checkout. I am ok with PHP but not really got round to fully understanding JavaScript* yet.
So, I have got the client side JAvascript for the check out buttons as shown on the Paypal API as follows:
<script>
paypal.Buttons(
{
env: 'sandbox', // sandbox | production
commit: true,
createOrder: function() {
return fetch('samples/AuthorizeIntentExamples/CreateOrder.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
})
.then(function(res) {
return res.json();
}).then(function(data) {
return data.id; // Use the same key name for order ID on the client and server
});
},
onApprove: function(data)
{
return fetch('samples/AuthorizeIntentExamples/CaptureOrder.php', {
method:'post',
headers: {
'content-type': 'application/json',
'id':data.id
},
body: JSON.stringify({
orderID: data.id
})
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Transaction funds captured from ' + details.payer_given_name);
})
}
}).render('#paypal-button-container');
</script>
The CreateOrder side of the code is working fine. I receive the JSON with the payment ID etc. However I am struggling to understand how get the OrderID to the CaptureOrder function. The paypal seems to skirt around this and just states "PUT ORDER ID HERE" in the captureOrder function:
namespace Sample\AuthorizeIntentExamples;
require ($_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php');
include ($_SERVER['DOCUMENT_ROOT'].'/vendor/paypal/paypal.php');
use PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
use Sample\PayPalClient;
class CaptureOrder
{
/**
* Below method can be used to build the capture request body.
* This request can be updated with required fields as per need.
* Please refer API specs for more info.
*/
public static function buildRequestBody()
{
return '{
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "GBP",
"value": "100.00"
}
}
]
}';
}
/**
* Below function can be used to capture order.
* Valid Authorization id should be passed as an argument.
*/
public static function captureOrder($authorizationId, $debug=false)
{
$request = new AuthorizationsCaptureRequest($authorizationId);
$request->body = CaptureOrder::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
/* print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Capture ID: {$response->result->id}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line */
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response->result;
}
}
/**
* Driver function for invoking the capture flow.
*/
if (!count(debug_backtrace()))
{
CaptureOrder::captureOrder('ORDER ID HERE', true);
}
Do I need to store the JSON results of CreateOrder in a SLQ database and call the order number from there to Capture Order or am I missing something and the client side JavaScript* code in the Paypal workflow Posts the orderID onApprove?
UPDATE:
So I have been and played around and I cannot understand why the order ID is not being sent to CaptureOrder when approved.
onApprove: function(data) {
return fetch('/my-server/capture-paypal-transaction', {
headers: {
'content-type': 'application/json'
},
**body: JSON.stringify({
orderID: data.id
})**
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Transaction funds captured from ' + details.payer_given_name);
})
}
The orderID does not seem to be here, despite the orderID being returned in data.id at the CreateOrder stage.
I get the following error "Uncaught TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body". This is despite follwoing the PayPal documentation.
I then tried POST data in the header
onApprove: function(data) {
return fetch('/my-server/capture-paypal-transaction', {
headers: {
'content-type': 'application/json',
'id': data.id
}
}).then(function(res) {
return res.json();
}).then(function(details) {
alert('Transaction funds captured from ' + details.payer_given_name);
})
}
This stopped the uncaught error, but the data sent in post 'id' was undefined. The then caused the API to return "RESOURCE ID NOT FOUND".
I just dont seem to get how the JAvaScript passes the OrderID between the function in CreateOrder and the function in OnApprove.
Trying my best to learn, but I the paypal documentation seems to assume a lot or miss bits out.

Geting "Bad Request: there is no photo in the request" in Telegram BOT API Using Google App Script

I am using the below code in Google App Script to send Image in Telegram Group.
Whenever I run this code the photo being sent to the group but I am getting below error:
Exception: Request failed for https://api.telegram.org returned code 400. Truncated server response: {"ok":false,"error_code":400,"description":"Bad Request: there is no photo in the request"} (use muteHttpExceptions option to examine full response). (line 27, file "Send Image")
Currently I am using google drive image link.
I have tried images from different sources but same error
var photo_url = "https://docs.google.com/uc?id=File_Id";
var id = "Chat_Id";
sendPhoto(id,photo_url)
function sendPhoto(id,photo_url) {
var API_TOKEN = "BOT_API_Code";
var payload = {
'method': 'sendPhoto',
'chat_id': String(id),
'photo': photo_url,
'caption': "My Caption"
}
var data = {
"method": "post",
"payload": payload
}
UrlFetchApp.fetch('https://api.telegram.org/bot' + API_TOKEN + '/', data);
}
I just added this line at the end of the data key
'muteHttpExceptions':true,
and the photo sends successfully without error.
var data = {
"method": "post",
"payload": payload,
'muteHttpExceptions':true,
}

I have a valid Facebook API Access Token, but it returns as Invalid/Non-Active: oAuthException

I send an access token in, that is valid by the Facebook Access Token Debugger, but it still says that it isn't an active/is an invalid access token
I have tried putting the access token through the debugger: Came up as active
var access_token = pathname.match(/\#(?:access_token)\=([\S\s]*?)\&/)[1];
$.ajax({
url: "https://graph.facebook.com/me?name?access_token=" + access_token,
type: 'GET',
success: function(response) {
console.log(response)
//Would want to do stuff with the Return data
},
error: function(response) {
$("#nameField").html("<li class='dataField' id='nameField'>The response could not locate the data source</li>")
}
});
I would want it to return JSON data/Single JSON entry. Ends up showing:
{
"error": {
"message": "An active access token must be used to query information about the current user.",
"type": "OAuthException",
"code": 2500,
"fbtrace_id": "BdmIzcoyALS"
}
}
Nevermind, found the answer:
It was the fact that I was using:
https://graph.facebook.com/me?name?access_token=
When I should have used:
https://graph.facebook.com/me?name&access_token=

Nodejs request post with body include api key

I have been trying about a week but I couldn't make a post request to get a result.
I tried a bunch of middlewares (exp: 'request', 'axios', 'reqclient','superagent etc..) but I couldn't make it.
Please provide me a simple post request with sending API key and body.
I also read all the documentation.
Please check below to see what I want :
*Authentication API key required.
*O-Auth Scopes trades
*Input One of: user_id + token or user_url is required.
here is my one of try :
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'api-site.com/Offer/v1/',
headers: {
'User-Agent': 'Request-Promise',
'Authorization': 'Basic 123123asdasd123123'
},
body: {
user_url: "site.com/user/user1234123",
otherparams: "parameter"
},
json: true
};
request(options)
.then(function (response) {
Console.log(response);
})
.catch(function (err) {
console.log('Error ', err.message);
});
I am getting this output :
Error : 401 - {"status":401,"time":1540458426,"message":"API Key Required"}
I tried some other request post middle-wares and played with content-type (application/json. dataForm, x-www-form-urlencoded) or
changed the location of my API key from header to body or
tried my API key inside of auth{authorization: "API Key"}
tried much more.
the result didn't change. I got the same output or errors.
EDIT :
this is the link that I am trying to do but got stack :
check here
Solved !
Everything works great. Problem was I needed to send my API Key base64 string.
Buffer.from("your_api_key_value" + ":", "ascii").toString("base64")

How to use an API with an app Fiori (SAPUI5)

I am trying to use this Mercedes Benz API in my app. Inside controller I have a ajax request:
onInit : function () {
var oModel = new JSONModel();
var url = 'https://api.mercedes-benz.com/image/v1/vehicles/WDDZH3HB8JA394212/components?apikey=my_apikey';
$.ajax({
beforeSend: function() {
//armamos la url y la asignamos a una var
},
url: url,
type: 'GET',
accepts: "application/json",
success: function (resp) {
console.log(resp)
},
error: function (jqXHR, estado, error) {
console.log(error +":" + " " + estado)
},
timeout: 10000
});
},
I just want response as OK but getting some error:
Request header field X-XHR-Logon is not allowed by
Access-Control-Allow-Headers in preflight response.
Responses
If you take a look to the documentation API I just need the API key. Maybe I am doing something wrong? Guide me if you has use an API inside a FIORI app it will be thankful
NOTE: my fiori server is on premise so we don't use SCP
If you really want to do an XHR you need to whitelist APIKEY in neo-app.json like this
{
"welcomeFile": "/webapp/index.html",
"routes": [{
...
],
"sendWelcomeFileRedirect": true,
"headerWhiteList": [
"APIKey"
]
}
Otherwise I strictly recommend using destinations, explained in here:
SAPUI5 / AJAX, submitting Basic Authentication Details (solved)
Authentication API in SAPUI5 without SAP Cloud Platform and Destinations (not solved)

Categories