Unable to get oAuth token for BigCommerce once click app - php

I am a complete noob to BigCommerce as well as plugins. And recently planned to develop a one click app which could be installed by the users of any store on their store. I have good hand on php. So, i can code but dont know the flow for plugins.
To create a draft app i went to devtools.bigcommerce.com and created an app defined Auth Callback url as https://amanangira.com/bCommerce/oauth.php
and Load Callback url as https://amanangira.com/bCommerce/callBack.php
in oauth.php i inserted the following code
<?php
$data = array( "client_id" => "123456789",
"client_secret" => "123456789",
"redirect_uri" => "https://amanangira.com/bCommerce/callBack.php",
"grant_type" => "authorization_code",
"code" => $_GET["code"], "scope" => $_REQUEST["scope"], "context" => $_GET["context"], );
$postfields = http_build_query($data);
$ch = curl_init();
//$url = "https://api.bigcommerce.com/stores/wky4s3lfef/v3/";
$url = "https://login.bigcommerce.com/oauth2/token";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);
$obj = json_decode($output);
var_dump($obj);
?>
Now whenever i install the app in my test store it says following.
/var/www/html/angira/bCommerce/oauth.php:37:
object(stdClass)[3]
public 'error' => string 'redirect_uri_mismatch' (length=21)
public 'error_description' => string 'Parameter redirect_uri does not match registered URI' (length=52)
Please help with the above in as much as simple terms.
Thank you.

After some hit and trials and i finally stumbled upon the solution. Which was to update the redirect_uri in the oauth.php to that which was the Auth Callback uri in the application configuration.
"redirect_uri" => "https://amanangira.com/bCommerce/oauth.php"

Related

Send informations via Firebase Cloud Messaging

I am currently trying to make use of cloud messaging for my Android app. The server is sending messages via PHP using php-curl.
The problem is that the server's response is always:
401: Unauthorized
I use the WebAPI Access key from the Firebase Console for my App, so this is definitively the right one. Below is the code I use to send the data:
<?php
$fields = array(
'to' => "<MY-RECIPIENT-TOKEN>",
'notification' => array(
'body' => 'Test message :)',
'title' => 'Test',
'icon' => 'myicon',
'sound' => 'mySound'
)
);
$headers = array(
'Authorization:key=<MY AUTH KEY IS HERE>',
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
The MY-RECIPIENT-TOKEN is received from the App and the MY AUTH KEY IS HERE is the key from the Firebase Console.
What am I missing here?
Nevermind. The Problem is not in the code, the code is fine. If someone stumbles upon this: There are 2 keys in your FCM Console. When you go to your Project Settings you will find the Web-API-Key. This is not the key you are looking for! You need to go to Settings -> Cloud Messaging. There you will see a much longer Server key. THIS is the key you want to use!

Bitshares API - Create an account under a registrar using PHP

I've been trying to create an account under a registrar account on Bitshares Test Net programatically using Graphene API and its blockchain. I read the API documentation and have concluded that the PHP code bellow is what I need to execute to be able to create a new account.
<?php
$url = 'https://testnet.bitshares.eu/';
$array = array(
'jsonrpc' => '2.0',
'method' => 'register_account',
'params' => array(
'name' => 'NEW_ACCOUNT_NAME',
'owner_key' => 'OWNER_KEY',
'active_key' => 'ACTIVE_KEY',
'registrar_account' => 'REGISTRAR_ACCOUNT',
'referrer_account' => 'REGISTRAR_ACCOUNT',
'referrer_percent' => 1,
'broadcast' => 1
),
'id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'GraphenePHP/1.0');
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($array));
$response = curl_exec($ch);
curl_close($ch);
echo '<pre>';
print_r($response);
echo '</pre>';
The code above is not working. Also I am not getting any response. I have a feeling that I am missing something or the value of $url is incorrect.
Please help?
This Bitshares testnet link https://testnet.bitshares.eu/ sometimes does not work.
You can simply use real net or install testnet on your side for this.

403 forbidden error while sending messages to facebook connector through Unification Engine API

I am using unification engine #unificationengine API to post message on facebook.
I followed all the steps and created connections to use connectors. All the curl requests are working fine till send message.
In every curl from create user, create connection, connection refresh I am getting
{'status':200,'info':'ok'}
And now I want to use the connector to post message on facebook.
Below is my Curl code:
$post_msg = json_encode(
array(
'message' =>
array(
'receivers' =>
array(
array(
'name' => 'Me',
'address' =>'https://graph.facebook.com/'.$request->profile_id.'/feed?access_token='.$request->access_token.'&message=Hello&method=post',
'Connector' => 'facebook'
),
),
'sender' =>
array('address' => 'sender address'),
'subject' => 'Hello',
'parts' =>
array(
array(
'id' => '1',
'contentType' => 'binary',
'data' => 'Hi welcome to UE',
'size' => 100,
'type' => 'body',
'sort' => 0
),
),
),
)
);
$ch = curl_init('https://apiv2.unificationengine.com/v2/message/send');
curl_setopt($ch, CURLOPT_USERPWD, "0a7f4444-ae4445-45444-449-d9b7daa63984:8755b446-6726-444-b34545d-713643437560");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_msg);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump($response);
return ['label' => $response];
and I am getting:
status: 403 and info: forbidden in response.
I have tried everything available in documentation and on stack overflow or any other website. But hard luck.
Please suggest why I am getting this error?
Refrence SO Questions:
SO question 1
SO question 2
Thanks.
Update
I added these three options in curl request:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
and now I am getting 498, invalid access token error:
"{\"Status\":{\"facebook\":{\"status\":498,\"info\":\"Invalid Token:
\"}},\"URIs\":[] }
please use this as per php
public function facebookSharing($access_token) {
$app = new UEApp(env('UNIFICATION_APP_KEY'), env('UNIFICATION_APP_SECRATE'));
$user = new UEUser('unification_userkey', 'unification_usersecret');
$connection = $user->add_connection('FACEBOOK', "facebook", $access_token);
$options = array(
"receivers" => array(
array(
"name"=> "Me"
)
),
"message"=>array(
"subject"=>'testing',
"body"=> 'description',
"image"=> 'use any image url',
"link"=>array(
"uri"=> 'any web site url',
"description"=> "",
"title"=>"Title"
)
)
);
$uris = $connection->send_message($options);
}
The access token might have expired. Please reconnect the facebook connection again or refresh the connection.
The facebook access tokens have a lifetime of about two hours. For longer lived web apps, especially server side, need to generate long lived tokens. Long lived tokens generally lasts about 60 days.
UE has a capability to refresh facebook tokens. After adding connection using "apiv2.unificationengine.com/v2/connection/add"; api call, then you should call "apiv2.unificationengine.com/v2/connection/refresh"; api to make the short lived token to long lived.

How to use Instagram Real-time subscriptions for geography?

I have successfully created a Real-Time subscription for geography in Instagram for my location:
lat 1.436629
long 38.438239
Radius: 1000
The subscription call gave this geography id: 12932150
After this, I posted a picture on Instagram by tagging my current location with a custom name. I then noticed that Instagram did not ping my call-back-url. If Instagram did ping the call-back-url, the geography id is to be picked up from the ping, and used in calling the media/recent endpoint on geographies.
I did this manually. A call to "https://api.instagram.com/v1/geographies/12932150/media/recent?client_id=XXXXX" returns empty results:
{"pagination":{},"meta":{"code":200},"data":[]}
That means the post was not registered for the geography id within 1000 meters of the center.
But, calling media/search endpoint: "https://api.instagram.com/v1/media/search?lat=1.436629&lng=38.438239&client_id=XXXX&count=200&distance=1000" gave 69 results with my post at the top.
Is there something wrong in my code for Real-time subscription?
Or am I missing something important here. Please help.
This is the code for subscription:
<?php
$client_id = 'XXXX';
$client_secret = 'XXXX';
$redirect_uri = 'http://XXXX/igcallback.php';
$apiData = array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'aspect' => "media",
'object' => "geography",
'lat' => "1.436629",
'lng' => "38.438239",
'radius' => '1000',
'callback_url' => $redirect_uri
);
$apiHost = 'https://api.instagram.com/v1/subscriptions/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonData = curl_exec($ch);
curl_close($ch);
var_dump($jsonData);

Google API OAuth 2.0 CURL returning "Required parameter is missing: grant_type"

I'm trying to implement Google's OAuth 2.0 authentication for a web server application.
I can obtain the code from Google ok, but when I post this back to try and get an access token, it always give me the error "Required parameter is missing: grant_type. Error 400" even though the grant_type is there.
Also if I specify the content-length to be anything other than 0, it throws other errors.
Here's the code that's doing this curl post:
$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-length: 0'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code='. urlencode($code),
'client_id=' . urlencode($clientID),
'client_secret=' . urlencode($clientSecret),
'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type=authorization_code'
));
try
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type' => 'authorization_code'
));
or
curl_setopt($ch, CURLOPT_POSTFIELDS,
'code=' . urlencode($code) . '&' .
'client_id=' . urlencode($clientID) . '&' .
'client_secret=' . urlencode($clientSecret) . '&' .
'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php' . '&' .
'grant_type=authorization_code'
);
I was trying to use the PHP code in the original question plus answers provided here and kept getting complaints from the Google token server about a missing "grant_type", even though it was definitely being passed in. It turns out the issue was the CURLOPT_HTTPHEADER didn't like/need the 'Content-length: 0'. Hopefully this complete working code will save someone else the same headache...
// This is what Google's OAUTH server sends to you
$code = $_GET['code'];
// These come from your client_secret.json file
$clientID = "your client id.apps.googleusercontent.com";
$clientSecret = "your client secret";
$redirectURI = "your redirect URI";
$token_uri = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($token_uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
// Build the URLEncoded post data
$postFields = http_build_query(array(
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectURI,
'client_id' => $clientID,
'code' => $code
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);
// Save response, especially the "refresh_token"
$pathToAccessToken = "/your/path/to/access_token.json";
file_put_contents($pathToAccessToken, $response);
FYI, the response JSON looks something like this:
{
"access_token" : "xxxWhateverGibberish",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "yyyMoreGibberish"
}
After that I could successfully query the Calendar (the API scope my original OAuth request called for) using code like the following:
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$pathToAccessToken = "/your/path/to/access_token.json";
$accessToken = file_get_contents($pathToAccessToken);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($pathToAccessToken, $client->getAccessToken());
}
return $client;
}
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
After researching into this problem, it seems like the grant_type is not accepted in the array format. (Yes, the query string method works but it's messy to build.)
Adding http_build_query() to the array works if you are keen on keeping the POST fields in an array.
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type' => 'authorization_code'
)));
Please read the documentation for CURLOPT_POSTFIELDS carefully:
... as an array with the field name as key and field data as value
You do just something but not that. Try:
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
...
You don't need to urlencode in this case.
I didn't want to believe it, but strangely enough, simply switching from CURLOPT_POSTFIELDS from an array to a '&' concatenated string (with the same data!) let my OAuth server finally recognize the grant_type.
The core issue with the original question and some of the answers is the different values accepted in the curl_setopt call when using the key CURLOPT_POSTFIELDS.
When the input is an array the resulting Content-Type will be multipart/form-data which is not compliant with the OAuth 2.0 spec and the server will ignore it. When the input is a query-encoded string (e.g built using http_build_query) the Content-Type: will be application/x-www-form-urlencoded, which is what the spec requires.
See the "Notes" section at: http://php.net/manual/en/function.curl-setopt.php

Categories