posting into WordPress with WP API "code issue" - php

I am trying to post into a WordPress site using the WP API. I have the code below but it does not seem to be working, am not getting any post in my site.
<?php
$options = array (
'http' =>
array (
'ignore_errors' => true,
'method' => 'POST',
'header' =>
array (
'Authorization' => 'Basic ' . base64_encode( 'user' . ':' . 'pass' ),
),
'content' =>
http_build_query( array (
'title' => 'Hello World',
'content' => 'Hello. I am a test post. I was created by the API',
'tags' => 'tests',
'categories' => 'API',
)),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'http://freeglobaljob.com/wp-json/posts/',
false,
$context
);
$response = json_decode( $response );
?>

Related

logging into a remote site via wordpress site and saving session id

i have a code.
$url = 'sample.com/endpoint';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(
'gonderi_olustur' => 1,
'customer_id' => 1,
'product' => 3715,
'count' => 1,
'payment_type' =>'N',
'post_check_price' => 170
),
'cookies' => array('PHPSESSID'=>'0td1s9mj7osdk528sb347sn878')
));
I am saving data to a remote website through my wordpress site. while doing this I type the session id manually.
as in code: 'cookies' => array('PHPSESSID'=>'0td1s9mj7osdk528sb347sn878') .
I manually set the session id each time.
I want to automate this process. first i want to login to remote website and get session id and save other data.
I am logging in with the following code. returns successfully. but the session is not valid for subsequent post requests.
$url = 'https://sample.com/endpoint';
$body = [
'uye_eposta' => 'email',
'uye_sifre' => 'password',
'uye_giris '=> '1'
];
$body = wp_json_encode( $body );
$options = [
'body' => $body,
'headers' => [
'Content-Type' => 'application/json',
],
'timeout' => 60,
'redirection' => 5,
'blocking' => true,
'httpversion' => '1.0',
'sslverify' => false,
'data_format' => 'body',
];
$response = wp_remote_post( $url, $options );
$cookies = wp_remote_retrieve_cookies( $response );
$arr = (array)$cookies[0];
$session_id = $arr['value'];

Create a image share for linkedin api v2 by php

I write a code which share a post on linkedin account. My code is working fine for text post but facing issue in image post. I tried and search a lot but not find any success for now. Here is my code for image share in linkedin V2 api.
I follow this doc
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context
/*1.Register your image to be uploaded.*/
$imageData = array (
'registerUploadRequest' =>
array (
'recipes' =>
array (
0 => 'urn:li:digitalmediaRecipe:feedshare-image',
),
'owner' => 'urn:li:person:'.$data['identifier'],
'serviceRelationships' =>
array (
0 =>
array (
'relationshipType' => 'OWNER',
'identifier' => 'urn:li:userGeneratedContent',
),
),
),
);
$headers = [
'Content-Type' => 'application/json',
'x-li-format' => 'json',
'X-Restli-Protocol-Version' => '2.0.0',
];
$image_request = $adapter->apiRequest('assets?action=registerUpload', 'POST', $imagedata, $headers);
$image_request = json_decode(json_encode($image_request), True);
/*2.Upload your image to LinkedIn.*/
$media = $image_request['value']['asset'];
$image_path = '/var/www/domain.com/img/laptop-green-bg.jpg';
$postfield = array("upload-file" => $image_path );
$headers = array();
$headers[] = 'Authorization: Bearer '.$tokens['access_token'];// token generated above code
$headers[] = 'X-Restli-Protocol-Version: 2.0.0';
$headers[] = 'Content-Type: data/binary';
$headers[] = 'Content-Length: 0';
$ch = curl_init();
$options = array(
CURLOPT_HEADER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $image_request['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'],
CURLOPT_HTTPHEADER => $headers,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_SAFE_UPLOAD => false,
CURLOPT_POSTFIELDS => $postfield
);
curl_setopt_array($ch, $options);
$imgResponse = curl_exec($ch);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$assets = explode(":", $media);
$assetRequest = $adapter->apiRequest('assets/'.$assets[3], 'GET');
/*3. Create the image share.*/
$status = $this->imagePostArray($data, $media);
function imagePostArray($data, $media) {
$newData = array (
'author' => 'urn:li:person:'.$data['identifier'],
'lifecycleState' => 'PUBLISHED',
'specificContent' =>
array (
'com.linkedin.ugc.ShareContent' =>
array (
'shareCommentary' =>
array (
'text' => $data['introtext'],
),
'shareMediaCategory' => 'IMAGE',
'media' =>
array (
0 =>
array (
'status' => 'READY',
'description' =>
array (
'text' => $data['introtext'],
),
'media' => $media,
'title' =>
array (
'text' => $data['introtext'],
),
),
),
),
),
'visibility' =>
array (
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
),
);
return $newData;
}
$response = $adapter->apiRequest('ugcPosts', 'POST', $status, $headers);
print_r($response);
/*responsestdClass Object
(
[id] => urn:li:share:XX4665961029465XXXX
)*/
print_r($imgResponse);
/*HTTP/1.1 201 Created
Date: Tue Jun 18 08:15:02 UTC 2019
Server: Play
Set-Cookie: lang=v=2&lang=en-us; Path=/; Domain=api.linkedin.com
x-ambry-creation-time: Tue Jun 18 08:15:02 UTC 2019
access-control-allow-origin: https://www.linkedin.com
Content-Length: 0
X-Li-Fabric: prod-lor1
Connection: keep-alive
X-Li-Pop: prod-esv5
X-LI-Proto: http/1.1
X-LI-UUID: z1rSbeU8qRUA8kkBZSsXXX==
Set-Cookie: lidc="b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"
X-LI-Route-Key: "b=OB77:g=1398:u=7:i=1560845701:t=1560926538:s=AQG2sbwmHWudXf8tikgpzQdf4uhbXXX"*/
But still cannot see my post in linkedin. Please help to debug or provide some solution.
I've solved posting using Guzzle library of php. It's simple and straight forward.
First we need to upload the image using following code:
$linkedInClient = new GuzzleHttp\Client(['base_uri' => 'https://api.linkedin.com']);
$response = $linkedInClient->post(
'/media/upload', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer {accessToken}',
],
'multipart' => [
[
'name' => 'fileupload',
'contents' => fopen('image-path', 'r'),
],
],
]
);
After that we need to decode the json response the uploaded image to use in the post request as follow:
$contents = json_decode($response->getBody()->getContents());
Now, prepare the data for linkedin post:
$data = array (
'author' => 'author-id',
'lifecycleState' => 'PUBLISHED',
'specificContent' =>
array (
'com.linkedin.ugc.ShareContent' =>
array (
'media' =>
array (
0 =>
array (
'media' => $contents->location,
'status' => 'READY'
),
),
'shareCommentary' =>
array (
'attributes' => [],
'text' => 'Some Comments',
),
'shareMediaCategory' => 'IMAGE',
),
),
'visibility' =>
array (
'com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC',
),
);
Next, we can use this data to post in linkedin as below:
$linkedInClient->post("/ugcPosts", $data);
I hope this helps. We can see the post in the linkedin. However, in my case the post will be visible but the image only gets displayed after some time of upload. But you can see the image on popup after clicking the blank image block.
Thanks.
Work For Me
$curl = curl_init(); //CURL version: 7.29, PHP version: 7.4.26
$imageData = array (
'registerUploadRequest' =>
array (
'recipes' =>
array (
0 => 'urn:li:digitalmediaRecipe:feedshare-image',
),
'owner' => 'urn:li:person:'.$linkedin_id,
'serviceRelationships' =>
array (
0 =>
array (
'relationshipType' => 'OWNER',
'identifier' => 'urn:li:userGeneratedContent',
),
),
),
);
$image_request = json_encode($imageData);
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.linkedin.com/v2/assets?action=registerUpload',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_TIMEOUT => 300,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $image_request,
CURLOPT_HTTPHEADER => array('content-type: application/json', "Accept: application/json",
"Authorization: Bearer ".$access_token)
));
$response = json_decode(curl_exec($curl),true);
echo "<pre>";
print_r($response);

HTTP 400 error when trying to do a PayPal payment request. (file_get_contents)

Trying to make a test cURL-less Paypal payment request but getting an error.
I am using the Sample request from the paypal Payment API docs.
$data = array (
0 =>
array (
'op' => 'replace',
'path' => '/transactions/0/amount',
'value' =>
array (
'total' => '18.37',
'currency' => 'EUR',
'details' =>
array (
'subtotal' => '13.37',
'shipping' => '5.00',
),
),
),
1 =>
array (
'op' => 'add',
'path' => '/transactions/0/item_list/shipping_address',
'value' =>
array (
'recipient_name' => 'Anna Gruneberg',
'line1' => 'Kathwarinenhof 1',
'city' => 'Flensburg',
'postal_code' => '24939',
'country_code' => 'DE',
),
),
);
$url = 'https://api.sandbox.paypal.com/v1/payments/payment';
$options = array(
'http' => array(
'header' => array(
"Content-type: application/json",
"Authorization: Bearer $access_token"
),
'method' => 'POST',
'content' => http_build_query($data)
)
);
print_r($options);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
Return: Warning: file_get_contents(https://api.sandbox.paypal.com/v1/payments/payment): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /storage/ssd5/910/7954910/public_html/paypal.php on line 48
bool(false)
Add
'protocol_version' => '1.1'
to the 'http' => array().
e.g. Change the line
'method' => 'POST',
to
'protocol_version' => '1.1',
'method' => 'POST',
This changes the HTTP protocol used by file_get_contents() from HTTP/1.0 to HTTP/1.1, and HTTP/1.1 is required by the PayPal REST API server.

Yammer ID from Email (Wordpress PHP)

I'm trying to get the yammer ID of a user based on an email address, I wrote this
$emailx="email#email.com";
function get_yammer_id($email){
$url = 'https://www.yammer.com/api/v1/users/by_email.json';
$response = wp_remote_get( $url, array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Host' => 'www.yammer.com', 'Authorization' => 'Bearer ********-**********************' ),
'body' => array( 'email' => $email),
'cookies' => array()
)
);
$return = $response;
return $return;
}
$result = get_yammer_id($emailx);
echo $result;
The last echo greets me with "Array" though.
If I try to swap it for
echo $result[0];
I'll get nothing. Any ideas?
It may not be the best solution but I found one
$emailx="email#email.com";
function get_yammer_id($email){
$url = 'https://www.yammer.com/api/v1/users/by_email.json';
$response = wp_remote_get( $url, array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Host' => 'www.yammer.com', 'Authorization' => 'Bearer *******-*********************' ),
'body' => array( 'email' => $email),
'cookies' => array()
)
);
$return = (explode(",",$response['body']));
return (int)str_replace('"id":', '', $return[1]);
}
$result = get_yammer_id($emailx);
echo $result;
Does anyone have a better one?

Is it possible to mock a variable value for a method for CakePHP tests (PHP Unit)?

I'm testing my API and there's a login method for OAuth that I can't seem to properly test due to how it will not read $_GET values of a variable when POSTing.
The login method. Basically $OAuthParams doesn't get set when using POST because getAuthorizeParams() uses $_GET. So I want to fill/mock either $_GET or $OAuthParams.
public function login () {
$OAuthParams = $this->OAuth->getAuthorizeParams();
if ($this->request->is('post')) {
$this->validateRequest();
$loginData = array('User' => array(
'username' => $this->request->data['User']['username'],
'passwd' => $this->request->data['User']['passwd']
));
//Attempted login
if ($this->Auth->login($loginData['User'])) {
unset($loginData);
$userData = $this->User->find('first',array(
'conditions' => array(
'User.username' => $this->request->data['User']['username']
),
'fields' => array('username','name','id','banned','active','role','private'),
'recursive' => -1
));
$this->Session->write('Auth.User',$userData['User']); //Update the session
//Write this to session so we can log them out after authenticating
$this->Session->write('OAuth.logout', true);
//Write the auth params to the session for later
$this->Session->write('OAuth.params', $OAuthParams);
//Off we go
return $this->redirect(array('action' => 'authorize'));
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
$appName = $this->applicationDetails['name'];
$this->set(compact('OAuthParams','appName'));
}
The current test method.
/**
* testAccessToken method
* 1. Get the authorization code (/oauth/authorize?response_type=code&client_id=CLIENT_ID&client_secret=CLIENT_SECRET)
* 2. Retrieve the token (/oauth/token?grant_type=authorization_code&code=CODE_RETURNED&client_id=CLIENT_ID&client_secret=CLIENT_SECRET)
* 3. Parse the token from the returned data
* #return void
*/
public function testAccessToken(){
//#link http://stackoverflow.com/questions/8183396/dealing-with-security-component-in-a-cakephp-2-test-case
$this->OAuth = $this->generate('OAuth', array(
'components' => array(
'Security' => array('_validatePost'),
)
));
$this->OAuth->Security->expects($this->any())
->method('_validatePost')
->will($this->returnValue(true));
$get_data = array(
'response_type' => 'code',
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
);
$post_data = array(
'User' => array(
'username' => 'test_user_1',
'passwd' => 'tester'
)
);
$resultPost = $this->testAction(
'/oauth/login',
array(
'method' => 'post',
'data' => $post_data
)
);
debug($resultPost);
$data_for_code = array(
'accept' => 'Yep',
'Authorize' => array(
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
'response_type' => 'code',
'state' => '',
'scope' => ''
)
);
$code = $this->testAction(
'/oauth/authorize',
array(
'data' => $data_for_code,
'method' => 'post'
)
);
debug($code);
/*$data_for_token = array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY')
);
$token = $this->testAction(
'/oauth/token',
array(
'data' => $data_for_token,
'method' => 'post'
)
);*/
//debug($token);
}
Tried the following with no luck.
$this->OAuth = $this->generate(
'OAuth',
array(
'components' => array(
'Security' => array( '_validatePost' ),
'Auth' => array('loggedIn','user')
),
'methods' => array(
'getAuthorizeParams'
)
)
);
$data = array(
'response_type' => 'code',
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY')
);
$this->OAuth->expects($this->any())
->method('getAuthorizeParams')
->will($this->returnValue($data));
$loginData = array(
'User' => array(
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
'response_type' => 'code',
'state' => '',
'scope' => '',
'redirect_uri' => 'https://myurl.com/api/myCallbackMethod',
'username' => 'test_user_1',
'passwd' => 'tester'
)
);
//test login action
$resultPost = $this->testAction(
'/oauth/login?response_type=code&client_id=' . getenv('THREE_SCALE_APP_ID') . '&client_secret=' . getenv('THREE_SCALE_APP_KEY'),
array(
'method' => 'post',
'data' => $loginData
)
);
debug($resultPost);
$data = array(
'accept' => 'Yep',
'Authorize' => array(
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
'response_type' => 'code',
'state' => '',
'scope' => ''
)
);
$result = $this->testAction(
'/oauth/authorize',
array(
'data' => $data,
'method' => 'post'
)
);
debug($result);
Mock the getAuthorizeParams() function to return the values you want.
The functions inside OAuth that you want to mock are an array of strings with the 'methods' key, ie:
$this->generate(
'OAuth',
array(
'methods' => array(
'getAuthorizeParams'
),
'components' => array(
...
)
)
);
Then before you call your testAction() method:
$this->OAuth->expects($this->once())
->method('getAuthorizeParams')
->will($this->returnValue($YOUR_EXPECTED_VALUE));

Categories