I am trying to integrate an eBay SDK developed by David Sadler which is in GitHub. But I got stuck on connection part itself. I am getting app token with http://localhost/ebay-sdk-examples/oauth-tokens/01-get-app-token.php with my production credentials.
But when I hit, http://localhost/ebay-sdk-examples/oauth-tokens/02-get-user-token.php it gives me this error:
[error] => invalid_grant
[error_description] => the provided authorization grant code is invalid or was issued to another client
all The codes are available in the SDK link. Incase you need here is the code snippet
<?php
/**
* Copyright 2017 David T. Sadler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Include the SDK by using the autoloader from Composer.
*/
require __DIR__ . '/../vendor/autoload.php';
/**
* Include the configuration values.
*
* Ensure that you have edited the configuration.php file
* to include your application keys.
*/
$config = require __DIR__ . '/../configuration.php';
/**
* The namespaces provided by the SDK.
*/
use \DTS\eBaySDK\OAuth\Services;
use \DTS\eBaySDK\OAuth\Types;
/**
* Create the service object.
*/
$service = new Services\OAuthService([
'credentials' => $config['production']['credentials'],
'ruName' => $config['production']['ruName'],
'sandbox' => false,
]);
$token = $config['production']['testToken']; ** This is the app token I get with http://localhost/ebay-sdk-examples/oauth-tokens/01-get-app-token.php **
/**
* Create the request object.
*/
$request = new Types\GetUserTokenRestRequest();
$request->code = $token;
// $request->code = 'v^1.1#i^1#I^3#r^1#p^3#f^0#t^Ul41XzA6MkIzRjJFRjA1MENDMzZCQjlGMjVERkYyMkMxMTRBM0VfMV8xI0VeMjYw';
/**
* Send the request.
*/
$response = $service->getUserToken($request);
echo '<pre>';
print_r($response);
echo '<pre>';
exit;
/**
* Output the result of calling the service operation.
*/
printf("\nStatus Code: %s\n\n", $response->getStatusCode());
if ($response->getStatusCode() !== 200) {
printf(
"%s: %s\n\n",
$response->error,
$response->error_description
);
} else {
printf(
"%s\n%s\n%s\n%s\n\n",
$response->access_token,
$response->token_type,
$response->expires_in,
$response->refresh_token
);
}
If there are simple codes to without using any SDK to connect to eBay with OAuth, its what I am searching for.
I am also currently working with this SDK.
My understanding is you should place the url:
http://localhost/ebay-sdk-examples/oauth-tokens/02-get-user-token.php
As your Your auth accepted URL1 in the developer.ebay.com, under Get a Token from eBay via Your Application.
Where you are setting $token this should be set to $_GET['code'] as when testing the sign-in and accepting you should be redirected to the above URL with a ?code=xxxx parsed back to it.
The value your currently setting to $token should be set as the value of your authToken within your credentials.
Hope that helps.
eBay Token generation can be achieved using our custom PHP/.NET scripts. eBay API documentation having many references
https://viewdotnet.wordpress.com/2011/12/20/ebay-token-generation/
The above link includes all the required details to generate eBay Auth. token
Related
I have an ASP.NET MVC application. When I start the application I get the error here:
SignalR: Connection must be started before data can be sent. Call .start() before .send()
No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.
I am not at all using SignalR but I get that error related to SignalR. I am not sure why ...
But when I start my application, it loads browserlink file (please see below) which has references to SignalR. Is this creating problem? Please help.
typeof JSON!="undefined"&&(window._vwdJSON=JSON),typeof define!="undefined"&&(window._vwdDefine=define,define=null),typeof window.onbeforeunload!="undefined"&&(window._vwdonbeforeunload=window.onbeforeunload)
;
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
var JSON;JSON||(JSON={}),(function(){"use strict";function i(n){return n<10?"0"+n:n}function f(n){return o.lastIndex=0,o.test(n)?'"'+n.replace(o,function(n){var t=s[n];return typeof t=="string"?t:"\\u"+("0000"+n.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+n+'"'}function r(i,e){var h,l,c,a,v=n,s,o=e[i];o&&typeof o=="object"&&typeof o.toJSON=="function"&&(o=o.toJSON(i)),typeof t=="function"&&(o=t.call(e,i,o));switch(typeof o){case"string":return f(o);case"number":return isFinite(o)?String(o):"null";case"boolean":case"null":return String(o);case"object":if(!o)return"null";n+=u,s=[];if(Object.prototype.toString.apply(o)==="[object Array]"){for(a=o.length,h=0;h<a;h+=1)s[h]=r(h,o)||"null";return c=s.length===0?"[]":n?"[\n"+n+s.join(",\n"+n)+"\n"+v+"]":"["+s.join(",")+"]",n=v,c}if(t&&typeof t=="object")for(a=t.length,h=0;h<a;h+=1)typeof t[h]=="string"&&(l=t[h],c=r(l,o),c&&s.push(f(l)+(n?": ":":")+c));else for(l in o)Object.prototype.hasOwnProperty.call(o,l)&&(c=r(l,o),c&&s.push(f(l)+(n?": ":":")+c));return c=s.length===0?"{}":n?"{\n"+n+s.join(",\n"+n)+"\n"+v+"}":"{"+s.join(",")+"}",n=v,c}}typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+i(this.getUTCMonth()+1)+"-"+i(this.getUTCDate())+"T"+i(this.getUTCHours())+":"+i(this.getUTCMinutes())+":"+i(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,u,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},t;typeof JSON.stringify!="function"&&(JSON.stringify=function(i,f,e){var o;n="",u="";if(typeof e=="number")for(o=0;o<e;o+=1)u+=" ";else typeof e=="string"&&(u=e);t=f;if(f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return r("",{"":i})}),typeof JSON.parse!="function"&&(JSON.parse=function(n,t){function r(n,i){var f,e,u=n[i];if(u&&typeof u=="object")for(f in u)Object.prototype.hasOwnProperty.call(u,f)&&(e=r(u,f),e!==undefined?u[f]=e:delete u[f]);return t.call(n,i,u)}var i;n=String(n),e.lastIndex=0,e.test(n)&&(n=n.replace(e,function(n){return"\\u"+("0000"+n.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(n.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"#").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return i=eval("("+n+")"),typeof t=="function"?r({"":i},""):i;throw new SyntaxError("JSON.parse");})})()
;
* ASP.NET SignalR JavaScript Library v2.0.2; Copyright (C) Microsoft Corporation; https://github.com/SignalR/SignalR/blob/master/LICENSE.md
*
* NUGET: END LICENSE TEXT */
/*!
* ASP.NET SignalR JavaScript Library v2.0.2
* http://signalr.net/
*
* Copyright (C) Microsoft Corporation. All rights reserved.
*
*/
You may not be using SignalR, but yes, browser link uses SignalR.
According to the documentation:
Browser Link is enabled by default. There are several ways to disable
it: In the Browser Link dropdown menu, uncheck Enable Browser Link.
I am developing a Google Adwords app. I tried using the API libraries available in PHP. I found, I need "clientCustomerId" in "adsapi_php.ini". I don't see anyway to get this "clientCustomerId" using API with OAuth. Am I trying something wrong?
This really depends on your application design.
My setup is using a top-level manager account that has access to all the client accounts.
clientCustomerID is set to that manager id.
With that, you can grab a list of your clients using the ManagedCustomerService->get() method provided by the PHP library. You can look at the example code here:
https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201710/AccountManagement/GetAccountHierarchy.php
That repo is now depreciated. As of Oct 2018 you should use this documentation: https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201802/AccountManagement/GetAccountHierarchy.php
Try CustomerService
CustomerService provides information about your accounts. It has a
getCustomers() method that takes no arguments and returns a list of
Customer objects containing fields such as customerId, currencyCode,
and dateTimeZone. CustomerService
Reference: Managing Accounts
Google Adwords Authencation code ( Using PHP Client Lib )
You may check code samples from Google Adwords PHP sample
Get Credentials for API use
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => 'http://localhost/adwordsWork/index.php',
'clientId' => '1139632-xxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'clientSecret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'scope' => 'https://www.googleapis.com/auth/adwords'
]);
if (!isset($_GET['code'])) {
$oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
$_SESSION['oauth2state'] = $oauth2->getState();
$config = [
'access_type' => 'offline'
];
header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
exit;
}
elseif (empty($_GET['state'])
|| ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state.');
} else {
$oauth2->setCode($_GET['code']);
$authToken = $oauth2->fetchAuthToken();
$refresh_token = $authToken['refresh_token'];
}
/* --------------------------- Authencation section End --------------------------------*/
// echo "<pre>";
// print_r($authToken);
// die;
/*---------------------------- Session Builder -----------------------------------------*/
$session = (new AdWordsSessionBuilder())
->fromFile('adsapi_php.ini')
->withOAuth2Credential($oauth2)
->build();
/* ------------------------- Session build ---------------------------------------------*/
/* -------------------------------- Adwords Services section ----------------------------*/
/* Creating object of Adwords services */
$adWordsServices = new AdWordsServices();
/* Adwords Customer services */
$customerService = $adWordsServices->get($session, CustomerService::class);
$customers = $customerService->getCustomers();
$customerId = $customers[0]->getCustomerId(); // Getting main customer client id
echo $customerId; // customer id from adwords account
So I'm using the exact-online XML-api to retrieve some user-related data.
This works fine so far, but since it is using oauth 2.0, I am being redirected after 600 sec and the login-prompt appears again.
This function refreshes the access-token:
/**
* #param string $refreshToken
* #return array {access_token, expires_in, refresh_token}
*/
public function refreshAccessToken($refreshToken)
{
$params = array(
'refresh_token' => $refreshToken,
'grant_type' => self::GRANT_REFRESH_TOKEN,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
);
$url = sprintf(self::URL_TOKEN, $this->countryCode);
return $this->getResponse($url, $params);
}
I debuged into it and the expires_in is set to 600. I guess this is the cause I'm being logged after after a short amount. My question: how can I disable this 600 sec timeout?
Also I found this function:
/**
* #param int $expiresInTime
*/
protected function setExpiresIn($expiresInTime)
{
$this->expiresIn = time() + $expiresInTime;
}
I modified the function and added a *1000 so it doesn't run out, but that didn't affect the outcome.
Is this an oauth-specific thing? Is it somehow managable to don't be kicked off after 10 mins?
There is no such thing in the backend of exact-online, which could change this value. Also, since this is a request I recieve, I don't think I can manipulate it, right?
Update 1
Due to the good feedback, I think I got a start with that problem, but no solution yet. I'll provide the code I'm currently using. I also asked the support of exact, but didn't got too much help there unfortunatly.
Please see this code:
<?php
require_once($sShopHomeDir . "modules/" . $sModulePath . "/library//exact/ExactApi.php");
$this->_exactApi = new ExactApi('de', $this->_sClientId, $this->_sClientSecret, $this->_sDivision);
$this->_exactApi->getOAuthClient()->setRedirectUri($this->_sRedirectUri.$param);
if (!isset($_GET['code']))
{
// Redirect to Auth-endpoint
$authUrl = $this->_exactApi->getOAuthClient()->getAuthenticationUrl();
header('Location: ' . $authUrl, true, 302);
die('Redirect');
}
else
{
$tokenResult = $this->_exactApi->getOAuthClient()->getAccessToken($_GET['code']);
$this->_exactApi->setRefreshToken($tokenResult['refresh_token']);
}
From the comments and answer, I'm convinced that this is the way to go. I'm retrieving a code and store/set the refresh-token - which, from my understanding, is correct that way.
For a better readabilty, I'll provide links to the two files which Exact online provides in their examples:
ExactApi.php
ExactOAuth.php
You have two OAuth flows supported by Exact Online. From the information and the timeout you give I am pretty sure you are using the implicit grant flow, which is not documented by Exact, but it does work.
The only other option you have is to use the token based authentication flow, which requires an extra step, namely exchanging your response code for an access token. That token is valid for a year and can be refreshed afterwards to extend the period for another year. The token based authentication flow is only useful in environments you can control, like web applications.
That token based authentication flow doesn't work with two phase authentication, so you can't refresh a token after that one year period.
I'm currently developing an iOS app along with a Wordpress site with the bbPress plugin.
I would like to allow any user to easily post links with custom schemes in the forum like :
myappname://badebidobudy/fdjlkqsfj
I saw that in bbPress an admin can indeed post a link like this :
Da link
and bbPress tells me why :
Your account has the ability to post unrestricted HTML content.
But when an anonymous user wants to do this, the custom scheme is removed and the resulting html code is :
Da link
So my question is : how can I configure (or tweak) Wordpress to at least accept my url scheme or even recognize a raw link with a custom scheme ?
After reading the comments of : https://developer.wordpress.org/reference/functions/esc_url/
I ended implementing a small plugin, here is its php code (the protocol I add is "newzik") :
<?php
/**
* Plugin Name: NZK links support
* Plugin URI: http://newzik.com/
* Description: Adds support to newzik:// links
* Version: 1.0
* Author: Pierre Mardon
* Author URI: http://newzik.com/
* License: None
*/
/**
* Extend list of allowed protocols.
*
* #param array $protocols List of default protocols allowed by WordPress.
*
* #return array $protocols Updated list including new protocols.
*/
function wporg_extend_allowed_protocols( $protocols ){
$protocols[] = 'newzik';
return $protocols;
}
add_filter( 'kses_allowed_protocols' , 'wporg_extend_allowed_protocols' );
?>
Afer tried a lot of times with abraham's code and other, I will read about tmhOauth, but I couldn't update the statuses with a picture. I modified with the 1.1 url this one and it doesn't works. Please somebody could help me? Thanks.
<?php
/**
* Tweets a Twitter photo along with a message from the user whose oauth_token
* and oauth_secret you use.
*
* Although this example uses your user token/secret, you can use
* the oauth_token/secret of any user who has authorised your application.
*
* This example is intended to be run from the command line.
*
* Instructions:
* 1) If you don't have one already, create a Twitter application on
* https://dev.twitter.com/apps
* 2) From the application details page copy the consumer key and consumer
* secret into the place in this code marked with (YOUR_CONSUMER_KEY
* and YOUR_CONSUMER_SECRET)
* 3) From the application details page copy the access token and access token
* secret into the place in this code marked with (A_USER_TOKEN
* and A_USER_SECRET)
* 4) Update $image to point to a real image file on your computer.
* 5) In a terminal or server type:
* php /path/to/here/photo_tweet.php
*
* #author themattharris
*/
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => '*',
'consumer_secret' => '*',
'user_token' => '*',
'user_secret' => '*',
));
// we're using a hardcoded image path here. You can easily replace this with
// an uploaded image - see images.php in the examples folder for how to do this
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
// this is the jpeg file to upload. It should be in the same directory as this file.
$image = '1594816618.jpg';
$code = $tmhOAuth->request(
'POST',
'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$image};type=image/jpeg;filename={$image}",
'status' => 'Picture time',
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
?>
I had the same problem. I found that on my server, I had to specify the full file system path (NOT the URL) to the image.
For example, '/home/mydomain/public_html/image.jpg'
As soon as I did that it worked fine.