Using google places service with php curl - google-maps

im trying to use the google places service with php curl
in my for loop (2 laps) , i send my url,
at the 1 lap, i can get json informations but the 2nd lap give me "REQUEST_DENIED" status. Here is my code :
<?php
//header("content-type: application/json");
//header("content-type: Access-Control-Allow-Origin: *");
//header("content-type: Access-Control-Allow-Methods: GET");
set_time_limit(0);
ini_set("memory_limit","12000M");
error_reporting(E_ALL);
ini_set('display_errors', True);
$cumulResults = array();
$pagenext="";
for($i=0;$i<2;$i++)
{
try{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.859294,2.347589&radius=50000&sensor=false&keyword=doctor&key=myapikeysecret'.$pagenext,
));
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
$resp = curl_exec($curl);
$result = json_decode($resp, true) ;
if(array_key_exists( 'status', $result ) )
{
switch ($result['status'])
{
case "OK":
break;
case "OVER_QUERY_LIMIT":
case "INVALID_REQUEST":
case "REQUEST_DENIED":
//echo $result['status'];
//exit;
break;
}
}
print_r($result );
if (array_key_exists('next_page_token', $result ) )
{
$pagenext = "&pagenex="+$result['next_page_token'];
}else{
$pagenext = "";
}
if($curl){curl_close($curl);}
sleep(5);
} catch (Exception $e) {
if($curl){curl_close($curl);}
}
}
?>
thanks

I would suggest using sleep to wait the thread between calls? Perhaps they are executing too quickly and hitting the request speed limit. Most Google maps services have them but they're not very well documented.
Hope this helps.

Related

vimeo direct upload form

According to Vimeo it is possible to send the upload directly to their server, without having to use the hosting server of the site.
https://help.vimeo.com/hc/en-us/articles/224970068-Can-I-upload-directly-to-Vimeo-and-skip-my-server-entirely-
With documentation:
https://developer.vimeo.com/api/upload/videos#http-post-uploading
But, I did not find any examples or I could understand how to do this
Resolved
Download API Vimeo: API Vimeo
Load API: File: vimeo_init.php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Load the autoloader
if (file_exists('/vimeo/autoload.php')) {
// Composer
require_once('/vimeo/autoload.php');
} else {
// Custom
require_once(__DIR__ . '/vimeo/autoload.php');
}
// Load the configuration file.
if (!function_exists('json_decode')) {
throw new Exception(
'We could not find `json_decode`. `json_decode` is found in PHP 5.2 and up, but not found on many Linux ' .
'systems due to licensing conflicts. If you are running Ubuntu try `sudo apt-get install php5-json`.'
);
}
$config = json_decode(file_get_contents(__DIR__ . '/vimeo_config.json'), true);
if (empty($config['client_id']) || empty($config['client_secret'])) {
throw new Exception(
'We could not locate your client id or client secret in "' . __DIR__ . '/vimeo_config.json". Please create one, ' .
'and reference config.json.example'
);
}
return $config;
Config API KEY: File vimeo_config.json
{
"client_id" : "",
"client_secret" : "",
"access_token" : ""
}
File POST PHP: File Upload Video
use Vimeo\Vimeo;
use Vimeo\Exceptions\VimeoUploadException;
$config = require(__DIR__ . '/vimeo_init.php');
$files = array($_FILES['video_arquivo']['tmp_name']); //array_shift($files);
if (empty($config['access_token'])) {
throw new Exception(
'You can not upload a file without an access token. You can find this token on your app page, or generate ' .
'one using `auth.php`.'
);
}
$lib = new Vimeo($config['client_id'], $config['client_secret'], $config['access_token']);
$uploaded = array();
foreach ($files as $file_name) {
try {
$uri = $lib->upload($file_name, array(
'name' => 'titulo',
'description' => 'descricao'
));
$video_data = $lib->request($uri);
if ($video_data['status'] == 200) {
$video_vimeo = $video_data['body']['link'];
}
$uploaded[] = array('file' => $file_name, 'api_video_uri' => $uri, 'link' => $link);
} catch (VimeoUploadException $e) {
$result["is_valid"] = false;
$result["message"] = $e->getMessage();
}
}

How can I validate an nonce passed to another domain and back trough URL?

I'm creating an Wordpress nonce on an user api login (domain1) and then send this nonce back to the domain (domain2) where the request came from. From domain2 there is another call made to domain1 for retrieving data, again through api, with the nonce created on login. This nonce is used for verifying this action.
Is this the right thing to do, if correct; Why is the result of wp_verify_nonce false?
My code:
function login() {
$creds = array();
$creds['user_login'] = $_GET["username"];
$creds['user_password'] = $_GET["password"];
$user = wp_signon($creds, false);
if (!is_wp_error($user))
{
$nonce = wp_create_nonce('wp_rest');
$url = "http://hongarijestek2/view/login.html?nonce=" . $nonce;
wp_redirect( $url );
exit;
}
}
function get_visitors( $data ) {
global $wpdb;
$nonce = $_GET['nonce'];
if( wp_verify_nonce( $_GET['nonce'], 'wp-rest' ) ) {
echo "Nonce is ok!";
} else {
echo "Nonce is not ok!";
die();
}
$visitors = $wpdb->get_results("SELECT * FROM cp_visitors_present");
if ( empty( $visitors ) ) {
return null;
}
return $visitors;
}

Yii2 swiftmailer foreach multiple email

I want to run a code to send email to all users. At first i used this code to run a test.
->setTo([
'john.doe#gmail.com' => 'John Doe',
'jane.doe#gmail.com' => 'Jane Doe',
])
I found out that the mail is 1 mail sent to multiple recipents, while i need to 2 emails to 2 recipients. Because in reality i need to send to over hundred people at once. SO i try foreach loop.
public function contact($email)
{
$users = Users::find()->all();
$content = $this->body;
foreach($users as $user){
if ($this->validate()) {
Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
return true;
}
}
return false;
}
But it only run 1 loop and end.
Please tell me where i'm wrong.
Thank you
the reason just one mail is sent is the
return true
it returns after the first email is sent, you should use try{}catch(){} like below
public function contact($email) {
$users = Users::find()->all();
$content = $this->body;
try {
foreach ($users as $user) {
if ($this->validate()) {
$r = Yii::$app->mailer->compose("#app/mail/layouts/html", ["content" => $content])
->setTo($user->email)
->setFrom($email)
->setSubject($user->fullname . ' - ' . $user->employee_id . ': ' . $this->subject)
->setTextBody($this->body)
->send();
if (!$r) {
throw new \Exception('Error sending the email to '.$user->email);
}
}
}
return true;
} catch (\Exception $ex) {
//display messgae
echo $ex->getMessage();
//or display error in flash message
//Yii::$app->session->setFlash('error',$ex->getMessage());
return false;
}
}
You can either return false in the catch part or return the error message rather than returning false and where ever you are calling the contact function check it the following way.
if(($r=$this->contact($email))!==true){
//this will display the error message
echo $r;
}

How do I write a single function in laravel that will be usable for different controllers or schedule commands and access different facades of models

I have this public function below but I will have to write a similar code in about 60 other places, I don't want to repeat myself rather, I want to be able to write a single function such that all I need change is 'Dailysaving::', and '00:00:00' each time I use the function. And please note that I will be creating several other schedule commands which this function should work for. How do I go about this please and where am I supposed to place the function I write And how do I access different models from the function. Thanks in advance for anyone that will help me out.
public function handle()
{
$users= Dailysaving::where('debit_time', '00:00:00')->where('status', 'Active')->get();
//die($users);
foreach ($users as $user) {
$email = $user->email;
$amount = $user->amount_daily * 100;
//Let's know where the payment is on the db
$user_id = $user->user_id;
$savings_id = $user->id;
$auth_code= $user->authorization_code;
//
$metastring = '{"custom_fields":[{"user_id":'. $user_id. '}, {"action": "activatedaily"},{"savings_id": '.$savings_id.'},{"savingstype": "dailysavings"}]}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.paystack.co/transaction/charge_authorization",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'amount'=>$amount,
'email'=>$email,
'authorization_code' =>$auth_code,
'metadata' => $metastring,
]),
CURLOPT_HTTPHEADER => [
"authorization:Bearer sk_test_656456h454545",
"content-type: application/json",
"cache-control: no-cache"
],
));
$response = curl_exec($curl);
$err = curl_error($curl);
if($err){
$failedtranx = new Failedtransaction;
$failedtranx->error = $err;
$failedtranx->save();
}
if($response) {
$tranx = json_decode($response);
if (!$tranx->status) {
// there was an error contacting the Paystack API
//register in failed transaction table
$failedtranx = new Failedtransaction;
$failedtranx->error = $err;
$failedtranx->save();
}
if ('success' == $tranx->data->status) {
$auth_code = $tranx->data->authorization->authorization_code;
$amount = ($tranx->data->amount) / 100;
$last_transaction = $tranx->data->transaction_date;
$payment_ref = $tranx->data->reference;
$record = new Transactionrecord;
$record->payment_ref = $payment_ref;
$record->save();
//saving complete
//die('saved');
$item = Dailysaving::find($savings_id);
$total_deposit = $item->total_deposit + $amount;
$item->total_deposit = $total_deposit;
$item->last_transaction_date = date('Y-m-d H:i:s');
$target = $item->day_target;
if ($target == $total_deposit) {
$item->status = 'Completed';
}
$item->save();
}
echo 'done';
}
else{
echo 'failed';
}
}
}
As I understand you are trying to make custom helper functions.
So you need create helpers.php with your functions and follow instructions in the below answer: https://stackoverflow.com/a/28290359/5407558

UPS php api - create order

I am trying to integrate UPS php api to generate online order for sending stuff.
I am able to validate address and get rates for stuff transfer but i am not able to find any solution for generating order and labels for courir, can somebody help me in getting that.
UPS Developer Kit and API is quite a good reference to all API related development, including in PHP. It can be downloaded from here: https://www.ups.com/upsdeveloperkit/downloadresource?loc=en_US
Here is some code example, for the PHP ship accept code (from the API zip):
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$accessSchemaFile = " Add AccessRequest Schema File";
$requestSchemaFile = " Add ShipAcceptRequest Schema File";
$responseSchemaFile = "Add ShipAcceptResponse Schema File";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
try
{
//create AccessRequest data object
$das = SDO_DAS_XML::create("$accessSchemaFile");
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->AccessLicenseNumber=$access;
$root->UserId=$userid;
$root->Password=$passwd;
$security = $das->saveString($doc);
//create ShipAcceptRequest data oject
$das = SDO_DAS_XML::create("$requestSchemaFile");
$requestDO = $das->createDataObject('','RequestType');
$requestDO->RequestAction='01';
//$requestDO->RequestOption='01';
$doc = $das->createDocument();
$root = $doc->getRootDataObject();
$root->Request = $requestDO;
$root->ShipmentDigest = 'test-Invalid-digest';
$request = $das->saveString($doc);
//create Post request
$form = array
(
'http' => array
(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => "$security$request"
)
);
//print form request
print_r($form);
$request = stream_context_create($form);
$browser = fopen($endpointurl , 'rb' , false , $request);
if(!$browser)
{
throw new Exception("Connection failed.");
}
//get response
$response = stream_get_contents($browser);
fclose($browser);
if($response == false)
{
throw new Exception("Bad data.");
}
else
{
//save request and response to file
$fw = fopen($outputFileName,'w');
fwrite($fw , "Response: \n" . $response . "\n");
fclose($fw);
//get response status
$resp = new SimpleXMLElement($response);
echo $resp->Response->ResponseStatusDescription . "\n";
}
}
catch(SDOException $sdo)
{
echo $sdo;
}
catch(Exception $ex)
{
echo $ex;
}
?>