Twitter api 1.1 update_with_media - php

i'm changing my php code to be compatible with new API and i'm stuck with update_with_media.
This is my code:
$image = constant('PATH_UPLOAD').$db_data['post_image'];
$connection = new TwitterOAuth(constant('CONSUMER_KEY'), constant('CONSUMER_SECRET'), $db_data['tw_oauth_token'], $db_data['tw_oauth_secret']);
$content = $connection->OAuthRequest('https://api.twitter.com/1.1/account/verify_credentials.json', 'GET', array());
$twitterInfo = json_decode($content);
$resp_tw = $connection->OAuthRequest('https://api.twitter.com/1.1/statuses/update_with_media.json', 'POST',
array(
'status' => html_entity_decode($db_data['post_text'],ENT_QUOTES,'UTF-8'),
'media[]' => "#{$image}"
)
);
And it returns
{"errors":[{"code":189,"message":"Error creating status"}]}
What might be the problem / what i'm doing wrong?

you can try like this :
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'abc',
'consumer_secret' => 'abc',
'user_token' => 'abc',
'user_secret' => 'abc',
));
$response = $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update_with_media'),
array(
'status' => $message,
'media[]' => file_get_contents($image)
));
if ($response != 200) {
//Do something if the request was unsuccessful
}
there is my code test https://twitter.com/wallapps/status/357137553691906048

Though the question is a few months old, I thought I'd answer it since I spent several hours on making update_with_media work and could not find satisfactory answers online.
Twitter API error messages unfortunately are not that specific. I was able to figure out the foll twitter errors:
"error could not authenticate you" - probably means your OAuth signature base string is not correct
"error incorrect or missing uri" - probably means you are not strictly following the format expected by Twitter in the request body. Could be something as simple as missing a \n in your request body
"error creating status - probably means your status text is encoded when it should not be in the request body of a multipart / form-data request
"Error internal error" - this one indicates nothing useful. It probably means that you have some data that is not encoded when twitter expects it to be or vice versa. It could also mean that you have not included the encoding type in the request body
To make update_with_media work, these tips may help:
The request should have content-type of multipart/form-data
The request body should contain the two elements twitter expects media[] and status in the correct format (RFC 2388)
In addition Twitter server expects \r\n (CR LF) after each portion of the request body. Skipping this causes Twitter to return an error
The media[] data should be base64 encoded and the content-disposition section in the request body should have Content-Transfer-Encoding
OAuth signature base string should be: (see OAuth 1.0A spec for signature) &All oauth_ parameters(name=value) in the Auth header of your request object in alphabetic order, separated by & and encoded

Related

Azure/Microsoft Identity Platform - Cannot Retrieve Access Token from Token Endpoint (PHP)

I'm trying to write a custom web app that utilizes the Microsoft Identity Platform to authenticate and authorize users. I'm able to successfully authenticate when calling the /authorize endpoint, and I have access to the "code" token that is returned.
I am now trying to retrieve my access token so that I can make calls to the APIs. Whenever I submit a POST request to the /token endpoint, the server returns a 400 Bad Request error. The header information that is provided contains no valuable information for troubleshooting and there is no JSON response returned so I have no idea where or what the issue is.
I'm making my call as follows:
$clientId = '00000000-0000-0000....'; // Omitted
$tenantId = '00000000-0000-0000....'; // Omitted
$grantType = 'authorization_code';
$scope = urlencode('User.Read');
$code = '......' // Obtained from authentication
$redirect_uri = 'http://localhost/smp/auth/handle';
$clientSecret = '...' // Omitted, set up in Azure App registrations under Certificates and secrets
$resource = 'api://00000000-0000-0000....'; // Omitted, set up in Azure App registrations under Overview -> App ID URI
$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
$parameters = [
'client_id' => $clientId,
'grant_type' => $grantType,
'scope' => $scope,
'code' => $code,
'redirect_uri' => $redirectUri,
'client_secret' => $clientSecret,
'resource' => $resource
];
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($parameters)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if (!$result) {
exit('an error has occured');
}
PHP returns a warning that reads the following: (tenant id has been omitted):
Warning: file_get_contents(https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\xampp\htdocs\smp\application\models\user-model.php on line 261
I've verified everything I can possibly think of.
The client and tenant ids are working (based on the successful authentication request).
The "code" is correctly retrieved from the authentication request.
Redirect Uri is the same as the one used for the authentication request.
I've tried with and without the client_secret variable. It is my understanding that this is actually required in my case.
I've tried with and without the resource variable, which is setup using the default Azure naming convention of "api://".
Please assist! I know I must be missing something but cannot figure it out. Perhaps permissions or additional setup within Azure? I'm not really sure what's wrong with my code/approach but Microsoft Identity Platform/OAuth isn't returning anything for me to work with and/or troubleshoot.
I've figured this out.
Firstly, I modified by $options variable to include the following:
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($parameters),
'ignore_errors' => true
]
];
Adding ignore_errors allowed me to see the returned JSON.
Next, it became apparent that my parameters were not being accepted because I was url-encoding all of them. My client secret, redirect uri, and client ids were all url encoded (this detail was hidden in my original post because it was just a small snippet of a much larger system). By undoing this encoding, my parameters all ended up being accepted. I suppose it makes sense because these values weren't being appended to a url but rather passed as POST values.
Lastly, the "resource" variable was not accepted (indeed, it wasn't required). Not sure if any of this is going to help anyone else but just in case, this was my fix.

PHP Soap Client to handle multipart/related

I am developing an application that needs to access a SOAP api. The soap API should return a base64 encoded zip file, and it does so when being fired from SOAPUI. However I am trying to read this result programatically therefore I would need to get the file with a request fired from PHP.
$client = new MTOMSoapClient($url, array("soap_version" => SOAP_1_1,"trace" => 1));
$user_param = array (
'DealerCode' => "1234",
'Hash' => "asjdfasjda1231231231",
'Password' => "somerandompassword",
'UserName' => "somerandomusername"
);
var_dump(
$client->__soapCall(
"DownloadOffer",
array($user_param)
)
);
var_dump($client->__getLastRequest());
I also extended PHP's soap client like shown here without the proper results: https://gist.github.com/pkmishra/2243055
The same error is shown in postman:
SoapFault: Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'multipart/related; type="application/xop+xml"'. in file /app/app/Http/Middleware/MTOMSoapClient.php on line 8
Any advice, library, way to get the response or at least the reason behind the error is greatly apreciated.

DocuSign API (PHP SDK) - Why do I get this response? "Error while requesting server, received a non successful HTTP code [302] with response Body:"

I'm trying to use the DocuSign PHP SDK to send a signing request based on a template. I am attempting to follow the steps outlined in this example: https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-template-remote
To authenticate, I am using a JWT. I assembled a header and payload signed with RSA256 private key generated by DocuSign, and the access token I received in response is in this format:
eyJ0eXAiOiJ-----.yyyyyy-----.zzzzzz-----
(Example, actual token is much longer).
When I try to run this code here (putting in the above access token and my DocuSign credentials as the arguments):
private function worker($args)
{
$envelope_args = $args["envelope_args"];
# Create the envelope request object
$envelope_definition = $this->make_envelope($envelope_args);
# Call Envelopes::create API method
# Exceptions will be caught by the calling function
$config = new \DocuSign\eSign\Configuration();
$config->setHost($args['base_path']);
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$api_client = new \DocuSign\eSign\client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
try {
$results = $envelope_api->createEnvelope($args['account_id'], $envelope_definition);
$envelope_id = $results->getEnvelopeId();
}
catch(ApiException $apiException) {
echo $apiException->getMessage();
}
return ['envelope_id' => $envelope_id];
}
Then I end up catching an exception:
Error while requesting server, received a non successful HTTP code [302] with response Body:
Digging a little deeper and var_dumping the response, the body is indeed empty and here are the response headers:
array(
0 => string 'HTTP/1.1 302 Found'
'Cache-Control' => string 'no-cache'
'Content-length' => string '0'
'Location' => string 'https://account-d.docusign.com/v2.1/accounts/6d7dc630-xxxx-xxxx-xxxx-xxxxxxxxxxxx/envelopes'
'Connection' => string 'close'
)
I have blocked out the the number in the Location section of the response in case it's anything sensitive. Being new to the DS API, I am unclear what this number is. It's not anything I have defined in my configuration for the project.
Does anyone have any idea what this error message indicates? Am I trying to access an incorrect API endpoint? Does this indicate my JWT access token is invalid? Something else?
Thanks for any help you can provide.
A better technique is to use the php quickstart and then copy the example that creates an envelope from a template
Re your current code: I'd check your base path.
Also check your access token. Your software is being redirected to the account server

PHP Twitter api New direct messages with event type (change september 2018)

Use the twitter API to send direct messages, with the following method: "POST direct_messages / new" with php, tmhOAuth library.
Since a few days ago they changed (as indicated in migration documentation
) by the method: "POST direct_messages / events / new", where the structure of the post parameters changes, which are json.
Making the changes that indicate, when testing get response code 415: "Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings" (twitter help)
Adding a url callback to the app, keeps giving the same error. Did someone have the same problem when they migrated? any suggestions?
I detail the changes implemented, with some code:
$options = array(
"event" => array(
"type" => 'message_create',
"message_create" => array(
"target" => array('recipient_id' => $id_usuario),
"message_data" => array('text' => $texto),
),
)
);
$json_options = json_encode($options);
$headers_extra = array('Content-Type' => 'application/json');
$code = $this->_tmhOAuth->request('POST', $this->_tmhOAuth->url('1.1/direct_messages/events/new'), $json_options, $headers_extra);
1) In "options" the format is changed, by the requested json,
2) "json_encode" function is used before sending in request method.
3) Headers "Content-Type" are added to be taken by the tmhOAuth library.
Thanks for any comments or help
tmhOauth is too old and hasn't been updated for a while. I lost some time trying to adjust it and finally switched to https://twitteroauth.com/
I was able to send DM in 1 min and 4 lines of codes just following their example in section JSON data.

Salesforce creates record but responds with a 405

I've written a Wordpress Plug-in that interacts with Salesforce via the REST API. It successfully gets an Instance URL and an Authentication Token using a username/password.
I'm able to submit queries and create objects using wp_remote_post with GET and POST respectively.
However, when creating objects, though successfully created in the Salesforce instance, I get the following in response to my POST:
{"message":"HTTP Method 'POST' not allowed. Allowed are HEAD,GET,PATCH,DELETE","errorCode":"METHOD_NOT_ALLOWED"}
Using the same json body content from these requests, I am able to submit and create via the Salesforce Workbench with no problems at all. I get a proper response that looks like this:
{
"id" : "003E000000OubjkIAB",
"success" : true,
"errors" : [ ]
}
Is there something in the Headers that I'm sending that Salesforce only partially disagrees with? Here are some other arguments that are getting sent as a result of using wp_remote_post - http://codex.wordpress.org/HTTP_API#Other_Arguments
Here's the php code that's calling it:
$connInfo['access_token'] = get_transient('npsf_access_token');
$connInfo['instance_url'] = get_transient('npsf_instance_url');
$url = $connInfo['instance_url'] . $service;
$sfResponse = wp_remote_post($url, array(
'method' => $method,
'timeout' => 5,
'redirection' => 5,
'httpversion' => 1.0,
'blocking' => true,
'headers' => array("Authorization" => "OAuth ". $connInfo['access_token'], "Content-type" => "application/json"),
'body' => $content,
'cookies' => array()
)
);
The $content is being encoded via json_encode before it gets to this point.
Update:
It is specific to one of the extra CURL options being sent by the WP_Http_Curl class. I haven't yet narrowed down which one Salesforce is having a problem with.
The solution is disable redirection in the request. You have it as 5 (the default) -- it needs to be set to 0 for this to work.
The initial request works but Salesforce sends a location header as a part of the response (the URL of the newly created object). WordPress thinks it is being told that the URL moved and that it should try again at this new URL. The response you're seeing is the result of that second request to the actual object you just created. That URL doesn't accept POST requests apparently.
It's a bit odd for Salesforce to be sending such a header, but there's also some discussion going on on the WordPress side that WordPress shouldn't follow location headers for non-301/302 responses which would solve this.
Thanks for posting this by the way. You update made me start debugging WP_Http_Curl which made me realize it was actually making a second HTTP request.

Categories