The following PHP code working perfect in development environment but on production environment returns error :
{"uuid":"xxxxx", "serverErrorCode":"AUTHENTICATION_FAILED", "reason":"Authentication failed"}
any idea ?
function cloudKitRequest($requestType, $jsonbody)
{
$KEY_ID = '97659598759875987508750875087087608785987585985';
$CONTAINER = 'xyz.zz.zzyyxx.xyz';
$PRIVATE_PEM_LOCATION = 'eckey.pem';
//$Environment = 'development';
$Environment = 'production';
$dbtype = 'public';
$result = NULL;
$url = 'https://api.apple-cloudkit.com/database/1/' . $CONTAINER . '/'. $Environment . '/' . $dbtype . '/records/'.$requestType;
// Set cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
// Create signature
date_default_timezone_set('UTC');
$explode_date = explode('+', date("c", time()));
$time = $explode_date[0] . 'Z';
$signature = $time . ":" . base64_encode(hash("sha256", $jsonbody, true)) . ":" . explode('cloudkit.com', $url)[1];
// Get private key
$pkeyid = openssl_pkey_get_private("file://" . $PRIVATE_PEM_LOCATION);
// Sign signature with private key
if(openssl_sign($signature, $signed_signature, $pkeyid, "sha256WithRSAEncryption")) {
openssl_free_key($pkeyid);
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER,
[
"Content-Type: text/plain",
"X-Apple-CloudKit-Request-KeyID: " . $KEY_ID,
"X-Apple-CloudKit-Request-ISO8601Date: " . $time,
"X-Apple-CloudKit-Request-SignatureV1: " . base64_encode($signed_signature),
]
);
// Set body
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonbody);
// Send the request & save response to $resp
$resp = curl_exec($ch);
if($resp === false) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
} else {
//echo $resp;
// $result = json_decode($resp, true);
$result = $resp;
}
curl_close($ch);
} else {
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
}
return $result;
}
any idea
Related
I have to add file in Drive. I have tried following code but give an error.
Purpose :
I have to use an api to add file to google drive.
Code
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
Error :
Notice: Undefined index: code in
/opt/lampp/htdocs/uploadtodrive/index.php on line 18
Fatal error: Uncaught RuntimeException: google api error: { "error": {
"errors": [ { "domain": "global", "reason": "authError", "message":
"Invalid Credentials", "locationType": "header", "location":
"Authorization" } ], "code": 401, "message": "Invalid Credentials" } }
in /opt/lampp/htdocs/uploadtodrive/index.php:19 Stack trace: #0 {main}
thrown in /opt/lampp/htdocs/uploadtodrive/index.php on line 19
You have create a webapplication and client ID ,Secrete as well as redirect URL. redirect URL is missing.
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-t19mhuuvq0nqtxxxxim8.apps.googleusercontent.com';
$CLIENT_SECRET = 'K8YxRshxxxx-5Sh3jKa';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'my_file.txt', 'vasim.txt');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
I have done google api integration code as well as file is upload to a drive. I have issue regarding a uploaded file name is "Untitled". Please review code and guide me what is missing.
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-t19mhuuvq0nqtng5ogg8XXXXXX0im8.apps.googleusercontent.com';
$CLIENT_SECRET = 'XXXXXXXXKa';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
//$content = { title "mypdf.pdf", description = "mypdf.pdf", mimeType = "application/pdf" };
$contentArry = array('title' =>'veridoc' );
$contentArry = json_encode($contentArry);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$contentArry);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf','Content-Length:' . filesize($filename),'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'veridoc.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
`
going by the documentation at https://developers.google.com/drive/api/v3/reference/files/update , to rename a file, do a PATCH request to https://www.googleapis.com/drive/v3/files/<fileId> with the new name, in your case, i guess that would be
$postResult = curl_exec ( $ch );
$parsed = json_decode ( $postResult, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $postResult );
}
$id = $parsed ['id']; // ?? wait, is it id or fileId?
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => basename ( $filename )
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
curl_exec($ch);
ps, don't set the Content-Length header manually when using CURLOPT_POSTFIELDS, because curl will do it for you, and if you're using multipart/form-data, the length you set yourself is very likely to be wrong even (doesn't concern your code as you're not using multipart/form-data, but it's a good habit to learn nonetheless, get rid of it.)
I had completed setting for ngrok and webhook on facebook.
this is very simple webhook by PHP
$access_token = "my_access_token";
$verify_token = "my_verify_token";
$hub_verify_token = "";
if (isset($_REQUEST['hub_challenge'])) {
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token) {
echo $challenge;
exit();
}
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$message_to_reply = 'I could see your message';
$myjsondata = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"' . $message_to_reply . '"
}
}';
send("me/messages", $mydata, $input, $access_token);
function send($type, $data, $input, $access_token) {
$url = 'https://graph.facebook.com/v2.11/' . $type . '?access_token=' . $access_token;
$ch = curl_init($url);
$jsonDataEncoded = $data;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
// **this $result is always NULL**
}
}
Result, i could receive json info from user typing in my localhost envirment. But when excuting curl, this $result is always NULL and having no error ,so weird.
What's wrong with this ?
PS: If i change webhook to cloud host, Operation is normal but hard to debug :(
I have a project were i need to pull up to 50,000 records from a database and create a csv file with that data. My problem is that the server will only return 300 records at a time. How can i effectively run this script apx 166 times while storing each response from the server in an array without running out of memory?
Once the last call request the server has been made, i will run the function (not shown) to create the CSV from the array.
class RetrieveData {
public $fields = array("Name1", "Name2", "Name3", "Name4");// List of names to pull from database
public $batchSize; //max 300 records returned at a time
public $NextPage;
public $nextPageToken; //token returned from previous call for paging
public function getData(){
$url = $this->host . "/rest/v1/list/" . $this->listId . "/leads.json?access_token=" . $this->getToken();
if (isset($this->fields)){
$url = $url . "&fields=" . $this::csvString($this->fields);
}
if (isset($this->batchSize)){
$url = $url . "&batchSize=" . $this->batchSize;
}
if (isset($this->nextPageToken)){
$url = $url . "&nextPageToken=" . $this->nextPageToken;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = curl_exec($ch);
return $response;
}
private function getToken(){
$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
$response = json_decode(curl_exec($ch));
curl_close($ch);
$token = $response->access_token;
return $token;
}
private static function csvString($fields){
$csvString = "";
$rr= implode(",",$fields);
$FF = str_replace(' ', '', $rr);
$csvString = $FF;
$csvString = rtrim($csvString,',');
}
return $csvString;
}
}
I am building a plagiarsm checking tool for my company but have problems on calculating the uniqueness factor.
Calculation works by searching the snippet into Google using GSERP. The script then checks if there where results then snippet is not unique.
This is my code;
. . .
$snippet = '"' . join(" ", array_slice($contentArray, $start, $limit)) . '"';
$start += $limit;
$end += $limit;
$counter++;
$url = '';
$lang = 'en';
$gserp = (g_serp($snippet, $url, $lang));
$gserpCount = count($gserp);
. . .
. . .
error_reporting(E_ALL ^ E_NOTICE);
//helper function -- file_get_contents using curl
function file_get_contents_curl($url, $referer = '', $ua = '') {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ($referer != '') {
curl_setopt($ch, CURLOPT_REFERER, $referer);
}
if ($ua != '') {
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//this is the main function
function g_serp($keyword, $url, $lang = 'en') {
$results = array();
$g_url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' . urlencode($keyword) .
'&rsz=large&userip=' . $_SERVER['REMOTE_DDR'] . '&hl=' . $lang;
for ($i = 0; $i < 64; $i+=8) {
$start = $i;
$referer = $_SERVER['HTTP_REFERER']; //change this into your real domain
$rawdata = file_get_contents_curl($g_url . '&start=' . $start, $referer, $_SERVER['HTTP_USER_AGENT']);
$decoded = json_decode($rawdata, TRUE); //decode as assoc array
if (is_array($decoded['responseData']['results'])) {
$pos = $start;
foreach ($decoded['responseData']['results'] as $result) {
//if (substr_count(strtolower($result['url']), $url)) {
// $GLOBALS['index'] = $pos + 1;
// }
$res['position'] = $pos + 1;
$res['title'] = $result['titleNoFormatting'];
$res['url'] = $result['unescapedUrl'];
array_push($results, $res);
$pos++;
}
}
}
return $results;
}
. . .
Anyone have any idea what I may be doing wrong or how best I can go about this?