linkedin API cannot create campaign - linkedin

We have got rw_ads permissions for an app. Through that app We have taken access_token with all given permissions.
As mentioned in the documentation, we have rw_ads permission, but If we try to create/update campaign we are getting the below error.
{
"serviceErrorCode": 100,
"message": "Not enough permissions to access: POST /adCampaignsV2/sdafnk",
"status": 403 }
var request = require("request");
var options = { method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2/sdafnk',
headers:
{ 'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json' },
body:
{ patch:
{ '$set':
{ runSchedule: { end: 1548405000000, start: 1547713800000 },
status: 'ACTIVE' } } },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Code for creation of campaign is mentioned below
var request = require("request");
var options = {
method: 'POST',
url: 'https://api.linkedin.com/v2/adCampaignsV2',
headers: {
'Authorization': 'Bearer <accessToken>',
'Content-Type': 'application/json'
},
body: {
account: 'urn:li:sponsoredAccount:<accountId>',
audienceExpansionEnabled: false,
costType: 'CPM',
creativeSelection: 'OPTIMIZED',
dailyBudget: { amount: '200', currencyCode: 'INR' },
locale: { country: 'IN', language: 'en' },
name: 'Campaign text ad test',
objectiveType: 'WEBSITE_TRAFFIC',
offsiteDeliveryEnabled: false,
runSchedule: { end: 1547708400000, start: 1547967600000 },
type: 'TEXT_AD',
unitCost: { amount: '10', currencyCode: 'INR' },
status: 'PAUSED'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

When you perform a partial update, the header X-RestLi-Method must be included in the request and set to PARTIAL_UPDATE.
Also if you use implicit grant-type, check if you have defined the scope correctly at the start. if you use client-credentials grant-type check if the account has the right permissions.
Direct Sponsored Content can be created by:
Ad Account Users with a role higher than VIEWER. Organization users
with DIRECT_SPONSORED_CONTENT_POSTER or ADMINISTRATOR roles.
also the code you added in this question is for Reactivating a campaign. not for updating/creating one.

Related

Failed to fetch. Possible Reasons: Cors Network failure URL Scheme

I trying to do a swagger documentation for an Express API and Firebase database, when I make request to my database in local with postman it work, but with the swagger interface I get this error:
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
For my documentation I use swagger-autogen and swagger-ui-express
there is a example for the login endpoint:
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
cors({
origin: `http://localhost:${port}`,
methods: ["GET", "POST", "DELETE", "PUT", "PATCH"],
credentials: true,
})
);
app.use(helmet());
app.use(morgan("combined"));
app.get("/", (req, res) => {
res.status(200).json({ message: "Welcome" });
});
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerFile, options));
swagger.js
const outputFile = "schemas/swagger.json";
const endpoints = \["routes/auth.js", "routes/menus.js"\];
const doc = {
info: {
version: "1.0.0",
title: "Menus API documentation",
description: "Documentation of MenusAPI",
termsOfService: "http://swagger.io/terms/",
contact: {
email: "contact#toto.com",
},
license: {
name: "Apache 2.0",
url: "http://www.apache.org/licenses/LICENSE-2.0.html",
},
},
servers: \[
{
url: "https://localhost:8081/menusapi/api/v1/",
},
\],
host: "/",
consumes: \["application/json"\],
produces: \["application/json"\],
securityDefinitions: {
OAuth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: process.env.AUTH_UTI,
tokenUrl: process.env.TOKEN_URI,
scopes: {
read: "Grants read access",
write: "Grants write access",
},
},
},
},
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
"#definitions": {
AddUser: userSchema.registration,
Login: userSchema.login,
Menus: menusSchema,
},
};
swaggerAutogen(outputFile, endpoints, doc).then(() =\> {
require("../app");
});
routes/auth.js
router.post("/login", auth.login);
controllers/auth_controller.js
exports.login = async (req, res) =\> {
/\* #swagger.tags = \['Auth'\]
\#swagger.description = 'Service to login';
\#swagger.summary = "Service to login a user to the app";
\#swagger.security = \[{
"OAuth2": \[
'read',
'write'
\]
}\]
\#swagger.responses\[200\] = {
description: 'Login sucess',
schema: {
"message": "Successfully connected!",
"jwt": "A very long token",
"refresh_jwt": "An other long token"
}
}
console error:
throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` +
^
Error: Value for argument "value" is not a valid query constraint. Cannot use "undefined" as a Firestore value
I looked everywhere but I really don't know what to do

getting error responses from nft.storage's /store API endpoint using fetch

let formData = new FormData();
formData.append("name",name);
formData.append("description",description);
formData.append("image", image);
fetch("https://api.nft.storage/store",{
method: "POST",
body: formData,
headers: {
'Authorization': 'Bearer '+process.env.TEST_API_KEY,
}
}).then(response => response.json())
.then((json)=>{
console.log(json)
})
This is what I've been trying to do but keep getting error as a response. Errors are usually invalid-file or something to do with content-type.
https://nft.storage/api-docs/ - This is the api documentation. If theres any example for the same, it'll be really helpful. Thanks!
Long time since question... just for any one wondering:
The api endpoint receives 1 parameter called meta which is a json_encoded representation of the fields, any falsy value like image: undefined, will be replaced with an extra field you must include, with the binary representation of the field... here is an example:
let params = {
name: 'name of the nft',
image: undefined,
description: 'description of the nft'
}
let formData = new FormData();
formData.append("meta",JSON.stringify(params));
formData.append("image",new File([ someBinaryImageData ], 'nft.png', { type: 'image/png' });
fetch("https://api.nft.storage/store",{
method: "POST",
body: formData,
headers: {
'Authorization': 'Bearer '+process.env.TEST_API_KEY,
}
})
.then(response => response.json())
.then((json)=>{
console.log(json);
})

How to upload the image using LinkedIn API without using curl request?

I've used the curl request to upload an image which successfully worked for me.
curl -i --upload-file ~/Desktop/Myimage.jpg -H 'Authorization: Bearer Redacted' "https://api.linkedin.com/mediaUpload/C5522AQHn46pwH96hxQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQLKRJOn_yNw6wAAAW2T0DWnRStny4dzsNVJjlF3aN4-H3ZR9Div77kKoQ&app=1983914&sync=0&v=beta&ut=1Dnjy796bpjEY1"
I've tried using the same request with "request" package which got failed and redirected me to the "404 page not found" LinkedIn page.
Here is the code:
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
},
method: 'put',
url: mediaUploadUrl
}
fs.createReadStream(filePath).pipe(request(options, function(err, httpsResponse, body){
if ( err ) {
console.log('err', err);
response(callback, 400, err);
} else {
console.log(body);
response(callback, 200, { mediaUrn });
}
}));
Documentation page that I've followed: https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/rich-media-shares
#linkedin
The request method is supposed to be POST but you are sending PUT instead, below code should work.
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'Content-Type': 'multipart/form-data'
},
method: 'post',
url: mediaUploadUrl
}
fs.createReadStream(filePath).pipe(request(options, function(err, httpsResponse, body) {
if ( err ) {
console.log('err', err);
response(callback, 400, err);
} else {
console.log(body);
response(callback, 200, { mediaUrn });
}
}));

firebase - How to know which registration_id is bad/expired/deleted

So I am pushining notifications in a batch to multiple devices. I want to delete device GFCM tokens from my databse if they are not in firebase.
Test request:
{"registration_ids": ["fznIum-OIL0:APA91bE9n6gxqVEB3hR0On_TZqH_cOOO7rFyLE5MYbvKXUX3737IonXquZRoHeY1UJf20G4nrahz35p80X8PAPouviYvXgtekAzeDFuwaWyiPI1sFlN1d1wGp5OulXv9wUzHyegeZiih","dsasadadsasdasdasdasdefs","fjb0qTB9ACI:APA91bHvx0pSlq-NuQz-bU70DhL7BXAcd-DqT9YT0ZjYw7R_pkBmr8oe6XdNw8IPlU67d-rXMfRY3mybaO7K5GHo_NH7G-Ya1Ae2xxJP1JIbuuSYomz31y_MPQijFK8w-bZXQ26SWE09"],
"notification":{
"body":"Yoou have a new message from Alice"}}
And response:
{
"multicast_id": 7971310728176484096,
"success": 1,
"failure": 2,
"canonical_ids": 0,
"results": [
{
"error": "NotRegistered"
},
{
"error": "InvalidRegistration"
},
{
"message_id": "0:1481547993513035%4f9c20964f9c2096"
}
]
}
How to detect which registration_ids are bad/Not registered?
Thanks!
Okey, i think i figured it out.
"results": Returns responses/errors in the order you specified it in registration_ids
when you are sending push notification to any mobile,you can find in err that registartion_ids/token isbad /not registered/
var serverKey = 'sdasd';//server key
var fcm = new FCM(serverKey);
var token = "token";//token here
var message = {
to: token,
collapse_key: 'your_collapse_key',
notification: {title: 'hello', body: 'test'},
data: {my_key: 'my value', contents: "stackoverflow.com"}
};
fcm.send(message, function (err, response) {
if (err) {
console.log(err);//find here registration_ids are bad/Not registered?
} else {
console.log(response);
}
});
});

HTTP.post to FCM Server not working

I am using Ionic 2 with HTTP native module to make a post request to FCM server for push notifications. The code I am using is:
HTTP.post(
"https://fcm.googleapis.com/fcm/send",
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token",
},
{
Authorization: {
key: "AUTHORIZATION KEY HERE"
}
})
Its giving me an error:
Unimplemented console API: Unhandled Promise rejection:
Unimplemented console API: Error: Uncaught (in promise): [object Object]
I tried the post request with Postman, it works perfectly fine delivering push notifications.
The code with Postman is:
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=Authorisation Key
Cache-Control: no-cache
Postman-Token: 446e253b-179a-d19b-21ea-82d9bb5d4e1c
{
"to": "Device Token",
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
}
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
}
Questions:
I am unable to add content-type to the header in the HTTP post request, but it works with postman.
If I try to add a function(response) { to get the response from the server, it gives me an error. The documentation for the same is at https://github.com/wymsee/cordova-HTTP
why are you using HTTP native module? Angular has a built in Http.
Using this one (importing HttpModule from #angular/http in your NgModule) you can just call
import { Http, Headers } from '#angular/http';
......
constructor(public http: Http) { }
sendPushNotification(deviceId: string) {
let url = 'https://fcm.googleapis.com/fcm/send';
let body =
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token"
};
let headers: Headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'key='+this.someKey
});
let options = new RequestOptions({ headers: headers });
console.log(JSON.stringify(headers));
this.http.post(url, body, headers).map(response => {
return response;
}).subscribe(data => {
//post doesn't fire if it doesn't get subscribed to
console.log(data);
});
}
push.on('notification', (data) => {
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: data.title,
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'Go to',
handler: () => {
//TODO: Your logic here
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.setRoot(EventsPage, {message: data.message});
}
});
push.on('error', (e) => {
alert(e);
});
});

Resources