Etsy PHP Oauth: Cant get access token - php

I have followed etsy guide to authenticate my app and connect to a user, and I was able to get through the first process to get a oauth_token, token secret and verifier. But after setting token for the oauth it fails the getAccessToken function with this message
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)bad
this is my code, as you can tell i tried many options, my ultimate goal is to have all credentials stored in file then in a database but first i want to learn whats wrong with my app
<?php
header('Content-type: text/plain');
ini_set('max_execution_time', 600);
$ksecrFile = fopen("key_secret.txt", "r") or die("Unable to open file!");
$key = trim(fgets($ksecrFile),"\n");
$secret = trim(fgets($ksecrFile),"\n");
$verifier = "";
fclose($ksecrFile);
$lines = file("key_secret.txt");
$oauth = new OAuth($key, $secret);
//$oauth->setAuthType(OAUTH_AUTH_TYPE_URI);
$oauth->disableSSLChecks();
function getToken($oauth, $verifier){
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r", "http://localhost/ksec.php");
if (!empty($_GET))
{
print_r($req_token);
$verifier = $_GET["oauth_verifier"];
$token = $req_token['oauth_token'];
$token_secret = $req_token['oauth_token_secret'];
//$tokenFile = fopen("token.txt", "w");
//fwrite($tokenFile, $verifier . "\r\n");
//fwrite($tokenFile, $token . "\r\n");
//fwrite($tokenFile, $token_secret);
//fclose($tokenFile);
//header("Location: http://localhost/ksec.php");
echo $verifier . " " . $token . " " . $token_secret . "\n";
$ksecrFile = fopen("key_secret.txt", "r") or die("Unable to open file!");
$key = trim(fgets($ksecrFile),"\n");
$secret = trim(fgets($ksecrFile),"\n");
$oauth1 = new OAuth($key, $secret);
$oauth1->disableSSLChecks();
$oauth1->setToken($req_token['oauth_token'], $req_token['oauth_token_secret']);
try {
// set the verifier and request Etsy's token credentials url
$acc_token = $oauth1->getAccessToken("https://openapi.etsy.com/v2/oauth/access_token", null, $_GET["oauth_verifier"]);
echo "good";
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "bad";
}
}
else
{
$login_url = sprintf(
"%s?oauth_consumer_key=%s&oauth_token=%s",
$req_token['login_url'],
$req_token['oauth_consumer_key'],
$req_token['oauth_token']
);
header("Location: " . $login_url);
}
}
$tokenFile = fopen("token.txt", "r") or die(getToken($oauth, $verifier));
//$verifier = trim(fgets($tokenFile),"\n");
//$token = trim(fgets($tokenFile),"\n");
//$tokenSecret = trim(fgets($tokenFile),"\n");
//fclose($tokenFile);
//echo $verifier . " " . $token . " " . $tokenSecret . "\n";
//echo $verifier . " " . $token;
?>

Ok i figured it out, i just dont know how to explain but having the code
<?php
header('Content-type: text/plain');
ini_set('max_execution_time', 600);
$ksecrFile = fopen("key_secret.txt", "r") or die("Unable to open file!");
$key = trim(fgets($ksecrFile),"\n");
$secret = trim(fgets($ksecrFile),"\n");
fclose($ksecrFile);
$oauth = new OAuth($key, $secret);
$oauth->disableSSLChecks();
$tokenFile = fopen("token.txt", "r") or die(getToken($oauth, $key, $secret));
function getToken($oauth, $key, $secret){
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r", "http://localhost/ksec.php");
$tokenFile = fopen("token.txt", "w") or die("Unable to open file!");
fwrite($tokenFile, $req_token['oauth_token'] . "\n");
fwrite($tokenFile, $req_token['oauth_token_secret'] . "\n");
$login_url = sprintf(
"%s?oauth_consumer_key=%s&oauth_token=%s",
$req_token['login_url'],
$req_token['oauth_consumer_key'],
$req_token['oauth_token']
);
header("Location: " . $login_url);
}
if (empty($_GET))
{
getToken($oauth, $key, $secret);
}
else
{
$tokenFile = fopen("token.txt", "r") or die("Unable to open file!");
$token = trim(fgets($tokenFile),"\n");
$tokenSecret = trim(fgets($tokenFile),"\n");
fclose($tokenFile);
$oauth1 = new OAuth($key, $secret);
$oauth1->disableSSLChecks();
$oauth1->setToken($token, $tokenSecret);
try {
// set the verifier and request Etsy's token credentials url
$acc_token = $oauth1->getAccessToken("https://openapi.etsy.com/v2/oauth/access_token", null, $_GET["oauth_verifier"]);
echo "good";
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "bad";
}
}
?>

Related

Que API calls in function

I'm doing two calls to an API. The only thing that differ the two calls is the URL. What i basically wonder is how i can structure this a little (or alot) better? Maybe run them after each other in a que? Sometimes the second calls returns a "critical error" on the Wordpress page where it gets called.
Any suggestions?
private $oauth_Key = 'xxx';
private $oauth_consumer = 'xxx';
private $api_url = 'xxx';
private $cat_url = 'xxx';
try {
$oauth = new OAuth($this->oauth_Key, $this->oauth_consumer, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->fetch($this->api_url);
$response_info = $oauth->getLastResponseInfo();
header("Content-Type: {$response_info["content_type"]}");
$res = $oauth->getLastResponse();
$oauth2 = new OAuth($this->oauth_Key, $this->oauth_consumer, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oaut2->fetch($this->cat_url);
$response_info2 = $oauth2->getLastResponseInfo();
header("Content-Type: {$response_info2["content_type"]}");
$res2 = $oauth2->getLastResponse();
} catch(OAuthException $e) {
echo "Exception caught!\n";
echo "Response: ". $e->lastResponse . "\n";
}
Just figured it out. Re structured the code a bit. See below:
private $oauth_Key = 'xxx';
private $oauth_consumer = 'xxx';
private $api_url = 'xxx';
private $cat_url = 'xxx';
try {
$oauth = new OAuth($this->oauth_Key, $this->oauth_consumer, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->fetch($this->api_url);
$response_info = $oauth->getLastResponseInfo();
header("Content-Type: {$response_info["content_type"]}");
$res = $oauth->getLastResponse();
$oauth2 = new OAuth($this->oauth_Key, $this->oauth_consumer, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth2->fetch($this->cat_url);
$response_info2 = $oauth2->getLastResponseInfo();
header("Content-Type: {$response_info2["content_type"]}");
$res2 = $oauth2->getLastResponse();
} catch(OAuthException $e) {
echo "Exception caught!\n";
echo "Response: ". $e->lastResponse . "\n";
}

issue in Apple Passwallete integration with php

I have generated PASS with my code and also get device id, pushtoken in response from device.
here is code by which I am store all device and Pass information in database.
$params = array(
"get"=>$_GET,
"request"=>$_REQUEST,
"post"=>$_POST,
"server"=>$_SERVER
);
$url = $_SERVER['SCRIPT_URI'];
$myfile = file_put_contents('callback.txt', json_encode($params).PHP_EOL , FILE_APPEND | LOCK_EX);
$content = trim(file_get_contents("php://input"));
$myfile = file_put_contents('log.txt', $content.PHP_EOL , FILE_APPEND | LOCK_EX);
$header = json_encode(getallheaders());
$myfile = file_put_contents('header.txt', $header.PHP_EOL , FILE_APPEND | LOCK_EX);
/*
* store registered device data
* */
$str = $_SERVER['SCRIPT_URI'];
$str = stripslashes($str);
$url_slot = parse_url($str);
$urlArray = explode('/',$url_slot['path']);
$passid = $urlArray['11']; // serial no
$deviceId = $urlArray['8'];
$passtype = $urlArray['10'];
try {
$dbh = new PDO('mysql:host=localhost;dbname=''', 'yyyy', 'zzzz');
$stmt = $dbh->prepare("INSERT INTO devices_passes (device_id, pass_id, pass_type, created, modified) VALUES
(:device_id,:pass_id,:pass_type,:created,:modified)");
$stmt->bindParam(':device_id', $device_id);
$stmt->bindParam(':pass_id', $pass_id);
$stmt->bindParam(':pass_type', $pass_type);
$stmt->bindParam(':created', date('d-m-y'));
$stmt->bindParam(':modified', date('d-m-y'));
$device_id = $deviceId;
$pass_id = $passid;
$pass_type = $passtype;
$stmt->execute();
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
try {
$dbh = new PDO('mysql:host=localhost;dbname=yyyy', 'uuuuu', 'yyyyyy');
$stmt = $dbh->prepare("INSERT INTO devices (push_token) VALUES
(:push_token)");
$stmt->bindParam(':push_token', $push_token);
$push_token = $content['pushToken'];
$stmt->execute();
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
But when I send push notification to device , it will not reflect anything in device.
here is code of sending push notification to device.
<?php
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apple_push_notification_production.pem';
$push_token = 'my token';
$passIdentify = 'pass.yyyyy.xxxx';
$payload = '{}';
$msg = chr(0) . pack('n', 32) . pack('H*', $push_token) . pack('n', strlen($payload)) . $payload . pack('n', strlen($passIdentify)) . $passIdentify;
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
fwrite($apns, $msg);
#socket_close($apns);
fclose($apns);
?>
Can you please help me when I am going wrong ??

BigQuery: Permission denied while globbing file pattern

I have the error saying that permission denied. I already tried this (giving view access to the google credential), and this. And everything doesnt work. I already enable the API for the google drive and also did this :
gcloud components update
gcloud auth login --enable-gdrive-access
I'm using PHP.
Here's the Code
<?php
ini_set("memory_limit", "2048M");
ini_set('max_execution_time', 7200); //3600 seconds = 60 minutes
if (!defined('BASEPATH'))
exit('No direct script access allowed');
use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;
use Google\Cloud\ExponentialBackoff;
require 'assets/SDK/vendor/autoload.php';
//require 'assets/library/vendor/autoload.php';
require_once 'assets/library/google-api-php-client/vendor/autoload.php';
define('APPLICATION_NAME', 'asd');
define('CLIENT_SECRET_PATH', 'assets/library/auth/asd.json');
define('PROJECT_ID','qwe');
define('SCOPES', implode(' ', array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.metadata',
'https://www.googleapis.com/auth/drive.readonly')
));
public function index(){
$myFile = "assets/library/auth/session_bq2.txt";
if(file_exists($myFile)){
#$fh = fopen($myFile, 'r');
// echo 'filesize '.filesize($myFile);
$session = fread($fh, filesize($myFile));
fclose($fh);
//echo '--refreshToken index '.$session;
}
$client = new Google_Client();
$client->setAccessType('offline');
$client->setClientId('asd.apps.googleusercontent.com');
$client->setClientSecret('asds');
$client->setState('asd');
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
if (isset($session) && $session) {
//Set the new access token after authentication
$client->setAccessToken($session);
//json decode the session token and save it in a variable as object
$sessionToken = json_decode($session);
//Save the refresh token (object->refresh_token) into a cookie called 'token' and make last for 1 month
setcookie('access_token', $sessionToken->refresh_token , time()+2678400);
$cookie = isset($_COOKIE['access_token']) ? $_COOKIE['access_token'] : "";
if(!empty($cookie)){
$client->refreshToken($cookie);
}
$client->setAccessToken($session);
}
else{
$tes = $client->getRefreshToken();
$client = new Google_Client();
$client->setAccessType('offline');
$client->setClientId('asd.apps.googleusercontent.com');
$client->setRedirectUri('qwe');
$client->setClientSecret('asd');
$client->setState('asd');
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$myfile = fopen("assets/library/auth/session_bq2.txt", "w") or die("Unable to open file!");
$txt = json_encode($client->getAccessToken());
fwrite($myfile, $txt);
fclose($myfile);
header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
}
else{
$oauth2_client_id = 'asd.apps.googleusercontent.com';
// $oauth2_redirect = 'asd';
$oauth2_redirect = 'http://' . $_SERVER['HTTP_HOST'] . 'asd';
$oauth2_server_url = 'https://accounts.google.com/o/oauth2/auth';
$query_params = array(
'response_type' => 'code',
'access_type' => 'offline',
'client_id' => $oauth2_client_id,
'scope' => SCOPES,
'redirect_uri' => $oauth2_redirect,
'state' => 'asd',
'approval_prompt' => 'force'
);
$forward_url = $oauth2_server_url . '?' . http_build_query($query_params);
header('Location: ' . $forward_url);
}
}
$service = new Google_Service_Bigquery($client);
$query="SELECT * FROM [queryspreadsheet] LIMIT 10";
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__) . '/assets/library/auth/MyProject-f0b4007b2f57.json');//this can be created with other ENV mode server side
$client->useApplicationDefaultCredentials();
$builder = new ServiceBuilder([
'projectId' => 'asd',
]);
$bigQuery = $builder->bigQuery();
$job = $bigQuery->runQueryAsJob($query);
$info=$job->info();
$queryResults = $job->queryResults();
/*$queryResults = $bigQuery->runQuery(
$query,
['useLegacySql' => true]);*/
// var_dump($queryResults);die;
if ($queryResults->isComplete())
{
$i = 0;
$rows = $queryResults->rows();
foreach ($rows as $row)
{
$i++;
$result[$i] = $row;
}
}
else
{
throw new Exception('The query failed to complete');
}
$i = 0;
$i++;
var_dump($result);die;
return $result;
}
Does anyone have any idea what did I miss? Thanks.

PhoneGap Push notification APN not play sound

i setup Push Notification service "device and Server" for my App , Application received notification in iPhone correctly but with out Sound not play any Advice ??
phone Gap Code
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
try {
initPushNotification();
navigator.notification.vibrate(1000);
} catch (ex) {
alert('error: ' + ex);
}
}
function initPushNotification () {
var pushNotification = window.plugins.pushNotification;
pushNotification.register(
app.successHandler,
app.errorHandler,{
"badge" : "true" ,
"sound" : "ture",
"alert" : "true",
"ecb": "onNotificationAPN"
});
// pushNotification.unregister(app.successHandler, app.errorHandler);
};
server Side Code :
$deviceToken = '**********************3ac58cb70891e04b28';
// Passphrase for the private key (ck.pem file)
// $pass =******* ;
// Get the parameters from http get or from command line
$message = (!empty($_GET['message']))?$_GET['message'] : 'Message text ' ;
$message .= #date("H:i:s d/M/Y", mktime());
$badge = 1;
$sound = 'default';
// Construct the notification payload
$body = array();
$body['aps'] = array('alert' => $message);
if ($badge)
$body['aps']['badge'] = $badge;
if ($sound)
$body['aps']['sound'] = $sound;
/* End of Configurable Items */
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'push/pushcert.pem');
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) {
print "Failed to connect $err $errstr\n";
return;
} else {
print "Connection OK";
}
$payload = json_encode($body);
// request one
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "\n";
fwrite($fp, $msg);
fclose($fp);
Plugin List :
com.phonegap.plugins.PushPlugin
org.apache.cordova.dialogs
org.apache.cordova.file
org.apache.cordova.media
org.apache.cordova.vibration
thanks for support ...

About the apple Enhanced notification format

I use php to send push message to apns , i use "Enhanced notification format" to sent .. but i can not get the return" Codes in error-response packet" anyone can help me ?? here is my code
<?php
header("Content-Type: text/html; charset=UTF-8");
$deviceToken = "123";
$content = "testing";
if(isset($content))
{
$newContent=substr($content,0,30)."...";
$re_content=iconv("GB2312","UTF-8",$newContent);
$pass = 'Ladder';
$body = array("aps" => array("alert" => $re_content, "badge" => 1, "sound" => 'received5.caf'));
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'dev.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
//$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
stream_set_blocking ($fp, 0);
if (!$fp)
{
print "Failed to connect $err $errstrn";
return;
}
else
{
print "Connection OK\n<br/>";
}
$payload = json_encode($body);
$msg =
// new: Command "1"
chr(1)
// new: Identifier "1111"
. chr(1) . chr(1) . chr(1) . chr(1)
// new: Expiry "tomorrow"
. pack('N', time() + 86400)
// old
. chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
//print "sending message :" . $payload . "\n";
fwrite($fp, $msg);
//checkAppleErrorResponse($fp);
echo 'Done\n';
fclose($fp);
echo $apple_error_response = fread($fp, 6);
/* return false;
exit(); */
}
?>
I call this function after fwrite and before close commands
function error_response($fp)
{
$read = array($fp);
$null = null;
$changedStreams = stream_select($read, $null, $null, 0, 1000000);
if ($changedStreams === false)
{
echo ("Error: Unabled to wait for a stream availability");
}
elseif ($changedStreams > 0)
{
$responseBinary = fread($fp, 6);
if ($responseBinary !== false || strlen($responseBinary) == 6)
{
$response = unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
var_dump($response);
}
}
}
It works when I sending a notification in the enhanced format. But doesn't work with notification in the simple format. I don't have idea why... Any clue?

Categories