“Non-200 response code during CRC GET request” - php

I want t register a webhook. I have this PHP code in my webhook endpoint URL:
<?php
// Example app consumer secret found in apps.twitter.com
const APP_CONSUMER_SECRET = 'xxx';
// Example token provided by incoming GET request
$token = $_GET['crc_token'];
/**
* Creates a HMAC SHA-256 hash created from the app TOKEN and
* your app Consumer Secret.
* #param token the token provided by the incoming GET request
* #return string
*/
function get_challenge_response($token) {
$hash = hash_hmac('sha256', $token, APP_CONSUMER_SECRET, true);
$response = array(
'response_token' => 'sha256=' . base64_encode($hash)
);
return json_encode($response);
}
// prints result
echo get_challenge_response($token);
If I try it directly (with the browser itself, i.e.) I get this response:
{"response_token":"sha256=VvHK6oEH4CHfnP9ImMmidtjTHGy48DuACxR6TSYyCcQ="}
Which makes me think it works properly, I also receive a 200 status code. But when I try to call the Twitter API to register the webhook I always get this error message:
{
"errors": [
{
"code": 214,
"message": "Non-200 response code during CRC GET request (i.e. 404, 500, etc)."
}
]
}
Whether I try it with Insomnia, Postman, or even the Account Activity Dashboard. It makes no sense because if I go to my browser and go to my PHP script, I receive good response.
Anyone know what is going on and how can I fix it?
Thanks!

Twitter is saying that your script is returning something other than a HTTP 200 response code. It might indicate there is an error happening during the Twitter request.
Make sure the webhook URL is correct.
Log the request coming from Twitter and make sure you are getting the expected input.
Check your logs for errors.
Try forcing the response code:
http_response_code(200);

Related

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

Can only get access token for QuickBooks API once

I'm using PHPoAuthLib in order to connect to the QuickBooks API per their example
When I follow their example, the first request that I make to the API works perfectly:
$result = json_decode($quickbooksService->request($url));
echo 'result: <pre>' . print_r($result, true) . '</pre>';
However in their example they use $_GET['oauth_token'] and $_GET['oauth_verifier'] to request an access token, and these values are only available on the $_GET server variable during the single callback from QuickBooks Online immediately after my app has been authorized.
For future requests there are no such examples on PHPoAuthLib's docs, so I tried a quick homebrew solution:
Save the response from QBO somewhere
if (!empty($_GET['oauth_token']) {
file_put_contents("token.txt", json_encode([
'oauth_token' => $_GET['oauth_token'],
'oauth_verifier' => $_GET['oauth_verifier'],
'realm_id' => $_GET['realmId']
]));
}
Use that response again later
$token = json_decode(file_get_contents("token.txt"));
$quickbooksService->requestAccessToken(
$token->oauth_token,
$token->oauth_verifier
// $token->getRequestTokenSecret() is not necessary - it will be automatically populated
);
// At this point my app crashes and return a 500 error
// Further code does not run
The error I receive is:
TokenResponseException in StreamClient.php line 68:
Failed to request resource. HTTP Code: HTTP/1.1 401 Unauthorized
Remember that the token and verifier work perfectly if I use them immediately after the app is authorized. If I save them to a file and attempt to re-use them 30 seconds later, this happens.
I think it might be a fundamental misconception about OAuth 1.0
I don't think what you have is a correct OAuth implementation. Have you read the OAuth spec and implemented as it's defined there?
Once you have a request token and a verifier, you use those to get an access token.
That access token is then good for 6 months.
It looks like you're trying to use a short-lived request token to continually fetch access tokens instead. That won't work.
i.e. If you're doing this everytime you want to make another request:
$quickbooksService->requestAccessToken(
Then you're doing something wrong. You should be doing that ONCE every 6 months, and that's it.
Working code here:
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/IntuitAnywhere.php
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/OAuth.php
https://github.com/consolibyte/quickbooks-php
Spec is here:
http://oauth.net/core/1.0a/#auth_step3

Why am I getting error when I use Postman and oauth2 for login access case in apiagility?

I am new to Zend Framework 2. I am trying to get the login access scenario working with Postman (chrome extension). I have gone through the forum but I'm not sure if I'm missing something or not. So here are the steps that I have taken so far:
In MYSQL I have set up the tables accordingly and there is a user with the following fields in the oauth_clients table:
client_id : testclient
client_secret : testpass
redirect_uri : /oauth/receivecode (I'm not sure about the value of
this one could someone please shed some light on this?)
grant_type : password ( I want to use the service for authentication
and authorization to access a website or login access scenario)
The rest of the fields are NULL. No other entries in other tables.
I set the parameters in Postman like this:
Authorization : Oauth2
Headers:
Accept : application/json
Content-Type : application/json
The raw body is like:
{
"client_id":"testclient",
"client_secret":"testpass",
"grant_type":"password"
}
I post the request to:
www.dummy.dev/oauth/authorize
When I post the request this is what I get:
{
"type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
"title": "invalid_request",
"status": 302,
"detail": "Invalid or missing response type"
}
Why do I get this error message?
This error is triggered here in the OAuth2 AuthorizeController.
The controller checks whether the $response_type is valid. If not it returns this error message.
On line 313 you see:
protected function getValidResponseTypes()
{
return array(
self::RESPONSE_TYPE_ACCESS_TOKEN,
self::RESPONSE_TYPE_AUTHORIZATION_CODE,
);
}
Those constants are defined in the AuthorizeControllerInterface:
const RESPONSE_TYPE_AUTHORIZATION_CODE = 'code';
const RESPONSE_TYPE_ACCESS_TOKEN = 'token';
So somewhere during the handling of your request this $response_type value is not set correctly. It should either be set as token or code for the request to validate correctly. Not sure where in your config you did something wrong but with this information you should be able to find the problem.
redirect uri is not necessary and could be left null in the database as well. The correct uri to POST is www.dummy.dev/oauth and the raw parameters in Postman are:
{
"client_id":"dev.dummy",
"username":"testclient",
"password":"testpass",
"grant_type":"password"
}
The value of password is stored and encoded (with bcrypt) in the database. client_id and client_secret are not important in this scenario as my own website is the client of my API.

Magento oAuth authorisation failed

I got a problem with oAuth authentification in magento.
I used following guide to create connection:
http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
First of all I granted all privileges for all accounts in magento / System / WebServices / REST ... Also I created oAuth Consumer. I got with it two variables (key and secret).
According the guide (Getting an Unauthorized Request Token) I configured RESTClient for Firefox. Selected oAuth 1.0 option, inserted data from magento and added them to headers.
And now I have something like that:
http://www.mg19.local/oauth/initiate
OAuth oauth_version="1.0",
oauth_signature_method="PLAINTEXT",
oauth_nonce="pzmp8IZuroEP6gf",
oauth_timestamp="1410271763",
oauth_consumer_key="9ad2067e70a4c3b799ab2799203b3e3b",
oauth_signature="a37633084e79432568181ef00410140e%26"
Then if I submit this, I will get following error:
Status Code: 400 Bad Request
oauth_problem=parameter_absent&oauth_parameters_absent=oauth_callback
I don't know the main purpose of the callback link, therefore I used random link. For example: http://www.mg19.local
When i submit
http://www.mg19.local/oauth/initiate/?oauth_callback=http://www.mg19.local
I got following result:
oauth_token=e00fc8386ba523bdd1d79a2fe61d59cb&oauth_token_secret=ca0d999010b2b149e2d51feefc328722&oauth_callback_confirmed=true
According the guide I moved to the 2nd step (User Authorization):
I copied data from the response to request. And forward the link:
http://www.mg19.local/oauth/authorize
I redirected to the following page:
Authorize application
Postman requests access to your account
After authorization application will have access to you account.
Authorize | Reject
And when I select Authorize I'm getting the following error:
An error occurred. Your authorization request is invalid.
Using xDebug I have found that the problem is near:
/**
* Load token object, validate it depending on request type, set access data and save
*
* #return Mage_Oauth_Model_Server
* #throws Mage_Oauth_Exception
*/
protected function _initToken()
{
....
} elseif (self::REQUEST_AUTHORIZE == $this->_requestType) {
if ($this->_token->getAuthorized()) {
$this->_throwException('', self::ERR_TOKEN_USED);
...
I'm not sure, but I think, once autorization finished successfully, then I moved from index to account area page and when authorization start again - it fail and I move on index again.
Please give any advice.
For what I see, the callback URL is the one that is messing up the whole thing. Callback is the most important link in OAuth. The callback should be a valid URL pointing to you site.
Once the user logs in auth server (Magneto in your case) Magneto will do a callback to the Callback URI you provided with the oauth_verifier. Like below:
/callback?oauth_token=tz2kmxyf3lagl3o95xnox9ia15k6mpt3&oauth_verifier=cbwwh03alr5huiz5c76wi4l21zf05eb0
Then your server should all the token API /oauth/token with the all the required Authorization headers below. Pasted from Magneto document link you provided
oauth_consumer_key - the Consumer Key value provided after the registration of the application.
oauth_nonce - a random value, uniquely generated by the application.
oauth_signature_method - name of the signature method used to sign the request. Can have one of the following values: HMAC-SHA1, RSA-SHA1, and PLAINTEXT.
oauth_signature - a generated value (signature).
oauth_timestamp - a positive integer, expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
oauth_token - the oauth_token value (Request Token) received from the previous steps.
oauth_verifier - the verification code that is tied to the Request Token.
oauth_version - OAuth version.
Hope this makes it clear. Please read the sections User Authorization and Getting Access Token sections of the link you pasted.
I'm using Guzzle and had a real hard time with it. In my case it was failing because I was using oauth_callback instead of callback, it worked when I changed it to:
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
$stack = HandlerStack::create();
$middleware = new Oauth1([
'consumer_key' => $key,
'consumer_secret' => $secret,
'token' => null,
'token_secret' => null,
'callback' => 'https://callback.co.uk'
]);
$stack->push($middleware);
$client = new Client([
'base_uri' => $magentoCredentials->shopUrl,
'handler' => $stack
]);
$res = $client->post('/oauth/initiate?oauth_callback', ['auth' => 'oauth']);

Receiving HTTP 401 Unauthorized when making a Google plus API call

I'm trying to get the list of all my friends from the Google plus via API. The user on whose behalf I'm doing this operation previously authorized my request and I got the auth token. I've tried the following code in php:
function CallAPI() {
$opts = array(
"http" => array(
"method" => "GET"
)
);
$url = 'https://www.googleapis.com/plus/v1/people/me/people/visible?key=XXXX';
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
var_dump($response);
}
but I keep receiving HTTP request failed! HTTP/1.0 401 Unauthorized. How can I prove that the user authorized my operations or what am I doing wrong?
Any help is much appreciated.
You need to authenticate the user to use the special keyword "me" so using your simple API key will not work (assuming the key passed is your simple key). Instead, you need to get an access token and pass that.
For a great example of how to do this in PHP using the PHP client library, try the quickstart:
https://developers.google.com/+/quickstart/php
If you are already getting an access token, you can call tokeninfo passing access token to get more information about who the user is associated with it:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.xxxxxxxx...
At this point, you could call:
'https://www.googleapis.com/plus/v1/people/[useridfromaccesstoken]/people/visible?key=XXXX';
To verify that your API key is correct but I would recommend using the client library as demonstrated in the quickstart sample.

Categories