John Rogerson
John Rogerson

Reputation: 1183

Integrating Oauth With eBay Browse API

eBay is making changes to their APIs, shutting down the finding API at the end of the year. I'm using a very simple application on my WordPress site that displays products based on a specific query I hard code. I am able to replicate my page using the Browse API, but I'm really struggling with the Oauth part of things. From what I understand, the Browse get requests only require an application access token (not a user access token). I'm just still struggling to get my head around all of this. I'm trying to add a function that generates an auth token, but it's not working and I don't think I'm calling the function correctly...so looking for help on a few things here. Most importantly--can i do it this way? And am i entering the variables correctly and how exactly do i call the Oauth function?

<?php 
/* Template Name: XXXX */ 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

function getOAuthCreds() {
    $endpoint = 'https://api.ebay.com/identity/v1/oauth2/token';
     
    $request = "grant_type=client_credentials";
    $request .= "scope=https://api.ebay.com/oauth/api_scope"; 

    $session = curl_init($endpoint);
     
    curl_setopt($session, CURLOPT_POST, true);
    curl_setopt($session, CURLOPT_POSTFIELDS, $request);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
     
    $headers = [
    'Content-Type: application/json',
    'Authorization = Bearer CODE HERE// I'm using the auth code generated from the application access token (not sure if thats' right?
    ];
     
    curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($session);
    curl_close($session);
    return $response;
    }

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.ebay.com/buy/browse/v1/item_summary/search?q=iphone&sort=-",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Content-Type:application/json",
        "Authorization:" getOAuthCreds(),///am i calling this correctly?
        "X-EBAY-C-MARKETPLACE-ID:EBAY_US",
        "X-EBAY-C-ENDUSERCTX:affiliateCampaignId=xx,affiliateReferenceId=xx",
    ),
  ));
  $response = curl_exec($curl);
  $err = curl_error($curl);
  curl_close($curl);

  
//print_r($response);

  if ($err) {
    if ($debug) echo "cURL Error #:" . $err;
    else echo "Oops, something went wrong.  Please try again later.";
  } else {
    //Create an array of objects from the JSON returned by the API
    $jsondata = json_decode($response);
    $resp = $jsondata->itemSummaries;

     //Create a simple grid style for the listings
     $pageCSS = "<style>
     .netflix-wrapper{
       display:grid;
       grid-template-columns: 200px 200px 200px;
     }
     .show-wrapper{padding:10px;}
     </style>";
//Create the WordPress page content HTML
$pageHTML="<h2>test</h2>";
$pageHTML.="<div class='test-wrapper'>";
//Loop through the API results
foreach($resp as $item) {
//Put each show into an html structure
//  Note: if your theme uses bootstrap use responsive classes here
$pageHTML.="<div class='show-wrapper'>";
//Not all items have a 'poster', so in that case use the img field
$pic = $item->image->imageUrl;
$itemID = $item->legacyItemId;
$link  = 'https://www.ebay.com/itm/'.$itemID.'?mkrid=ss-0&siteid=0&mkcid=1&campid=ss&toolid=ss&mkevt=1&customId=ss';
$title = $item->title;
$price = $item->price->value;
$bids =  $item->bidCount;
if(empty($bids)){
    $bids = 0;
}

// For each SearchResultItem node, build a link and append it to $results
$results .= "<div class=\"item\"><div class=\"ui small image\"><a href=\"$link\" target=\"_blank\"><img height=\"200px\" width=\"130px\" src=\"$pic\"></a></div><div class=\"content\"><div class=\"header\"><a href=\"$link\" target=\"_blank\">$title</a></div><div class=\"meta\" style=\"margin-top:1.1em\"><span class=\"price\"><a href=\"$link\" target=\"_blank\"><button class=\"ui teal button\">watch watchers</button></a></span><div class=\"extra\"><button class=\"ui button\"><a href=\"$link\" target=\"_blank\"><b>Current Bids:</b> $bids </a></button></div><div class=\"extra\"><a href=\"$link\" target=\"_blank\"><button class=\"ui orange button\">Current Price: $$price</button></a></div><div class=\"description\"></div></div></div></div>";
 
        
//Show the image first to keep the top edge of the grid level
$pageHTML.="<img style='max-width:166px;float:left;' src='".$pic."' />";
$pageHTML.="<h3>".$item->title."</h3>";
// $pageHTML.="<span>added to netflix ".$showObj->titledate."</span>";
// $pageHTML.="<div style='float:left;'>".$showObj->synopsis."</div>";
$pageHTML.="</div>";
}
$pageHTML.="</div>";
  }
?>

<?php get_header(); ?>
<!-- Build the HTML page with values from the call response -->
<html>
<head>
<div class="wrp cnt"><div class="spr"></div>
<section class="bSe fullWidth">
<article><div class="awr lnd">
<title>Most Watched <?php echo $query; ?> on eBay</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
<link
  rel="stylesheet"
  href="//cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css"
/>

</head>
<body>

Upvotes: 1

Views: 1401

Answers (1)

PeeBee101
PeeBee101

Reputation: 11

For reference: https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html

I do not know much about php but gathered from your code there are a few things that are not right.

1. The headers section

In function getOAuthCreds()

Headers should be:

Content-Type = application/x-www-form-urlencoded

Authorization = Basic [B64-encoded_oauth_credentials]

Content-Type = application/x-www-form-urlencoded header. eBay wants you to POST to its server so you will need this. Not sure if curl would automatically add to the header.

Authorization header. From eBay reference above, the header will use Basic authentication scheme. Then followed by the Base64 encoding of your "client_id":"client_secret".

[B64-encoded_oauth_credentials] = Base64Encode(client_id:client_secret)

Sample:

Authorization = Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=

In case you are not sure where to get "client_id" and "client_secret". Visit this page. https://developer.ebay.com/api-docs/static/creating-edp-account.html

If everything is correct, you will receive the following response from eBay

Sample:

{
"access_token": "v^1.1#i^1#p^1#r^0#I^3#f^0#t^H4s ... wu67e3xAhskz4DAAA",
"expires_in": 7200,
"token_type": "Application Access Token"
}

The access_token from the response will be valid for 7200 seconds. Cache and reuse it as the previous comment mentioned. When it is expired, get a new access_token.

2. When calling Browse API

You will use the access_token in the Authorization header (in Browse API call) as follow.

Sample:

Authorization: Bearer v^1.1#i^1#p^1#r^0#I^3#f^0#t^H4s ... wu67e3xAhskz4DAAA

Upvotes: 1

Related Questions