I am trying to get the latitude and longitude of an address but don't know how to put a variable in http build query.
I basically want to get the lat and long of place and get figure out how to put a variable in http_build_query.
This is what I tried:
$queryString = http_build_query([
'access_key' => 'API_KEY',
'query' => $place,
'country' => 'US',
'region' => 'California',
'output' => 'json',
'limit' => 1,
]);
$ch = curl_init(sprintf('%s?%s', 'http://api.positionstack.com/v1/forward', $queryString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$apiResult = json_decode($json, true);
print_r($apiResult);
foreach($apiResult as $result) {
foreach($result as $answer) {
$pickuplat = htmlspecialchars($answer['latitude']);
$pickuplong = htmlspecialchars($answer['longitude']);
}
}
Example without the var
$queryString = http_build_query([
'access_key' => 'API_KEY',
'query' => '1600 Pennsylvania Ave NW',
'country' => 'US',
'region' => 'California',
'output' => 'json',
'limit' => 1,
]);
$ch = curl_init(sprintf('%s?%s', 'http://api.positionstack.com/v1/forward', $queryString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$apiResult = json_decode($json, true);
print_r($apiResult);
foreach($apiResult as $result) {
foreach($result as $answer) {
$pickuplat = htmlspecialchars($answer['latitude']);
$pickuplong = htmlspecialchars($answer['longitude']);
}
}
Please help!
Related
In my laravel vue application I'm trying to fetch some data from Shopify Admin REST API and display them on the vuejs front end.
Following is my laravel controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
class ShopifyStatsController extends Controller
{
public function fetchStats(Request $request)
{
$startDate = $request->input('start_date');
$endDate = Carbon::parse($request->input('end_date'))->addDay()->format('Y-m-d');
if (!$startDate) {
$startDate = Carbon::now()->format('Y-m-d');
}
if(!$endDate) {
$endDate = Carbon::parse($startDate)->addDay()->format('Y-m-d');
}
// Set up cURL request
$access_token = 'ACCESS_TOKEN';
$apiKey = 'API_KEY';
$storeName = 'STROE_NAME';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN#STROE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=$startDate&created_at_max=$endDate");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($ch);
curl_close($ch);
$orders = json_decode($response);
//dd($orders);die;
$total_orders = ($orders->orders != null && !empty($orders->orders)) ? count($orders->orders) : 0;
$total_sales = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
$total_items = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
$completed_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
$to_be_fulfilled_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
foreach ($orders->orders as $order) {
$total_sales += $order->total_price;
$total_items += count($order->line_items);
if ($order->financial_status == "paid") {
$completed_orders++;
}
if ($order->fulfillment_status == null) {
$to_be_fulfilled_orders++;
}
}
$average_order_value = $total_orders > 0 ? $total_sales / $total_orders : 0;
// Bar chart for the best selling days
$start_date = date('Y-m-d', strtotime('-7 days'));
$end_date = date('Y-m-d');
$url = "https://API_KEY:ACCESS_TOKEN#STROE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=".date('Y-m-d', strtotime('-7 days'))."&created_at_max=".date('Y-m-d').""; // append the query to the URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Shopify-Access-Token:ACCESS_TOKEN', // access token
]);
// Send the request
$response = curl_exec($ch);
$response = json_decode($response, true);
curl_close($ch);
// Extract the data for each day from the response
$day_totals = array();
if (!empty($response['orders'])) {
foreach ($response['orders'] as $order) {
$order_date = date('Y-m-d', strtotime($order['created_at']));
if (!isset($day_totals[$order_date])) {
$day_totals[$order_date] = 0;
}
$day_totals[$order_date]++;
}
}
// Set 0 for days with no sales data
for ($date = $start_date; $date <= $end_date; $date = date('Y-m-d', strtotime($date . ' +1 day'))) {
if (!isset($day_totals[$date])) {
$day_totals[$date] = 0;
}
}
// Find the most selling day of the week
$most_sales_day = max($day_totals);
$most_selling_day = array_search($most_sales_day, $day_totals);
// Return the total sales value
return response()->json([
'total_sales' => $total_sales,
'total_orders' => $total_orders,
'total_items' => $total_items,
'completed_orders' => $completed_orders,
'average_order_value' => $average_order_value,
'day_totals' => $day_totals,
'most_selling_day' => $most_selling_day,
'most_sales_day' => $most_sales_day
]);
}
}
Here $day_totals will give me an array with day wise sales for a week, something like follows
array:8 [
"2023-01-09" => 1
"2023-01-04" => 0
"2023-01-05" => 0
"2023-01-06" => 0
"2023-01-07" => 0
"2023-01-08" => 0
"2023-01-10" => 0
"2023-01-11" => 0
]
Now I have created a reusable vue component called, ShopifyDayWiseSales.vue and this needs to show day wise sales for the week in a bar chart.
Following is my ShopifyDayWiseSales.vue component.
<template>
<div>
<apexchart type="bar" :options="chartOptions" :series="chartData"></apexchart>
</div>
</template>
<script>
import axios from 'axios';
import moment from 'moment';
export default {
data() {
return {
chartOptions: {
xaxis: {
categories: [],
},
yaxis: {
labels: {
formatter: function(val) {
return "$" + val;
},
},
},
},
chartData: [
{
name: "Total Sales",
data: [],
},
],
};
},
created() {
axios.get(`/shopify-stats`).then(response => {
console.log(response.data);
let chartData = {};
Object.entries(response.data.day_totals).forEach(([day, total]) => {
chartData[day] = total;
});
this.chartOptions.xaxis.categories = Object.keys(chartData);
this.chartData[0].data = Object.values(chartData);
console.log(chartData);
});
},
};
</script>
Here I'm using module to draw the graph.
My console log gives me this out put
2023-01-04: 0
2023-01-05: 0
2023-01-06: 0
2023-01-07: 0
2023-01-08: 0
2023-01-09: 1
2023-01-10: 0
2023-01-11: 0
Then I tried to use that component In my index.vue
<div >
<ShopifyDayWiseStats></ShopifyDayWiseStats>
</div>
But when I run this, It gives me an empty chart with not populated x and y axis.
In short word, my chart has not been drawn, I'm just wondering what's I'm doing wrong...
This what I'm currently getting
I am working on wordpress website with custom code , i am using pixel your site plugin to fire the facebook events but it is not working on the custom events so i tried to fire it on my one
here is the Code :
In Main.js file
fbq('trackCustom', 'View Review Page' , {
content_ids: ALL_Salad_Items ,
content_category: 'Salad',
content_type: 'product' ,
value: Selected_Salad_Full_Price ,
currency: 'EGP',} ,
{eventID: 'lychee.23'}); // Facebook Event for Browser
//console.log("Current Browser is " + navigator.userAgent);
//Facebook Event for Server
$.ajax({
type:'POST' ,
url: $('meta[name=ajax_url]').attr('content'),
data:{
action: 'fb_review_your_salad_event' ,
content_ids: ALL_Salad_Items ,
content_category: 'Salad',
content_type: 'product',
value: Selected_Salad_Full_Price ,
currency: 'EGP',
em: current_logged_in_user_email,
fn: current_logged_in_user_fname ,
ln: current_logged_in_user_lname ,
ph: current_logged_in_user_phone,
country: 'EG' ,
event_source_url: window.location.href ,
user_agent : navigator.userAgent
}
});
in the function.php file here is the ajax request :
add_action('wp_ajax_nopriv_fb_review_your_salad_event', 'fb_review_your_salad_event');
add_action('wp_ajax_fb_review_your_salad_event', 'fb_review_your_salad_event');
function fb_review_your_salad_event(){
global $pixel_id, $token, $event_id;
$curl = curl_init();
//Parameters
//Parameters
$event_source_url = $_POST['event_source_url'];
$content_category = $_POST['content_category'];
$content_type = $_POST['content_type'];
$User_agent = $_POST['user_agent'] ;
$content_ids = $_POST['content_ids'];
$value = $_POST['value'];
$currency = $_POST['currency'];
$em = $_POST['em'];
$fn = $_POST['fn'];
$ln = $_POST['ln'];
$ph = $_POST['ph'];
$data = json_encode(array(
"data" => array(
array(
// "event_id" => "gc.2-".$event_id."-".$content_ids,
"event_name" => "View Review Page",
"event_time" => strtotime(date('Y-m-d H:i:s')),
"event_id" => 'lychee.23' ,
"custom_data" => array(
"content_ids" => $content_ids ,
"content_type" => $content_type ,
"content_category" => $content_category,
"value" => $value ,
"currency" => $currency
),
"user_data" => array(
"client_ip_address" => $_SERVER['REMOTE_ADDR'],
"client_user_agent" => $User_agent ,
"em" => $em ,
"ph" => $ph ,
"fn" => $fn ,
"ln" => $ln ,
"country" => "EG" ,
"ct" => "cairo"
),
"event_source_url" => $event_source_url,
"action_source" => "website"
),
),
// "test_event_code" => "TEST10756"
));
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.facebook.com/v9.0/".$pixel_id."/events?access_token=".$token,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
return "cURL Error #:" . $err;
}else{
$response = json_decode($response,true);
var_dump($response);
}
wp_die();
}
it is currently working but gives me very low matching quality [Poor] despite of sending the advanced matching parameters to the server
I have run all my code to be active the subscription but its didn't, still is in authenticated process, please help me how can i active razorpay subscription. I created a plan using the api and get a response of planid
$key_id = '';
$key_secret = '';
$startTime = (time()+300);
$amount = '400';
$currency_code = 'INR';
//Create plan for user
$planReqdata = array(
'period' => 'daily',
'interval' => 7,
'item' => array(
'name' => 'Test daily 1 plan',
'description' => 'Description for the daily 1 plan',
'amount' => $amount,
'currency' => $currency_code
)
);
$planurl = 'https://api.razorpay.com/v1/plans';
$palnparams = http_build_query($planReqdata);
//cURL Request
$planch = curl_init();
//set the url, number of POST vars, POST planReqdata
curl_setopt($planch, CURLOPT_URL, $planurl);
curl_setopt($planch, CURLOPT_USERPWD, $key_id . ':' . $key_secret);
curl_setopt($planch, CURLOPT_TIMEOUT, 60);
curl_setopt($planch, CURLOPT_POST, 1);
curl_setopt($planch, CURLOPT_POSTFIELDS, $palnparams);
curl_setopt($planch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($planch, CURLOPT_SSL_VERIFYPEER, true);
$planResult = curl_exec($planch);
$planRes = json_decode($planResult);
//echo $planRes->id;
Using the plan id i have created a subscription and get a response of subscription id
//Create subscription for user
$subdata = array(
'plan_id' => $planRes->id,
'customer_notify' => 1,
'total_count' => 6,
'start_at' => $startTime,
'addons' => array(
array(
'item' => array(
'name' => 'Delivery charges',
'amount' => $amount,
'currency' => $currency_code
)
)
)
);
$suburl = 'https://api.razorpay.com/v1/subscriptions';
$subparams = http_build_query($subdata);
//cURL Request
$subch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($subch, CURLOPT_URL, $suburl);
curl_setopt($subch, CURLOPT_USERPWD, $key_id . ':' . $key_secret);
curl_setopt($subch, CURLOPT_TIMEOUT, 60);
curl_setopt($subch, CURLOPT_POST, 1);
curl_setopt($subch, CURLOPT_POSTFIELDS, $subparams);
curl_setopt($subch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($subch, CURLOPT_SSL_VERIFYPEER, true);
$subResult = curl_exec($subch);
$subres = json_decode($subResult);
//echo $subres->id;
Using the subscription id i have call checkout script
<button id = "rzp-button1">Pay</button>
<script src = "https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var options = {
"key": "<?php echo $key_id; ?>",
"subscription_id": "<?php echo $subres->id; ?>",
"name": "Test.",
"description": "Daily Test Plan",
"image": "http://localhost/iac/images/logo.png",
"callback_url": "http://localhost/iac/subres.php",
"prefill": {
"name": "Atanu",
"email": "atanu#example.com",
"contact": "+919876543210"
},
"notes": {
"note_key_1": "Tea. Earl Grey. Hot",
"note_key_2": "Make it so."
},
"theme": {
"color": "#F37254"
}
};
var rzp1 = new Razorpay(options);
document.getElementById('rzp-button1').onclick = function(e) {
rzp1.open();
e.preventDefault();
}
</script>
And pass the response to the below code to fulfill the payment
$razorpayPaymentId = $_POST['razorpay_payment_id'];
$subscriptionId= $_POST['razorpay_subscription_id'];
$secret = '########';
$razorpaySignature = $_POST['razorpay_signature'];
$expectedSignature = hash_hmac('SHA256', $razorpayPaymentId . '|' . $subscriptionId, $secret);
//$expectedSignature = hash_hmac(self::SHA256, $razorpayPaymentId . '|' . $subscriptionId, $secret);
if ($expectedSignature === $razorpaySignature)
{
echo "Payment is successful!";
}
There is no issue, it's just that when you specify a start date, it will not charge an immediate subscription, so creating a subscription without a start date would immediately make an active subscription.
For further information on why, follow the section Make an Authorized Payment on the following link. There it explains the format of Subscription A which is an instant payment subscription format.
Razorpay Subscription: Make an Authorized Payment
I'm using the master card checkout.js method version 57.
There are two types of payments ways.
I want to use only showLightbox() but unfortunately completeCallback() function is not working.
I have tried to find solution but everyone is suggesting to send Interaction.returnUrl parameter in session request but I don't want redirection.
Here is my code,
<script src="https://dohabank.gateway.mastercard.com/checkout/version/57/checkout.js"
data-error="errorCallback"
data-cancel="cancelCallback"
data-beforeRedirect="beforeRedirect"
data-afterRedirect="afterRedirect"
data-complete="completeCallback"
></script>
function completeCallback(resultIndicator, sessionVersion) {
alert(resultIndicator);
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://dohabank.gateway.mastercard.com/api/rest/version/57/merchant/TESTDB95810/session",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"apiOperation\": \"CREATE_CHECKOUT_SESSION\",\r\n \"interaction\": {\r\n \"operation\": \"PURCHASE\"\r\n },\r\n \"order\" : {\r\n \"amount\" : \"5.10\",\r\n \"currency\" : \"QAR\",\r\n \"description\": \"Ordered goods\",\r\n \"id\": \"5\"\r\n }\r\n}",
CURLOPT_HTTPHEADER => array(
"authorization: Basic Auth Token",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
// if ($err) {
// echo "cURL Error #:" . $err;
// } else {
// echo $response;
// }
// echo $response;
$object = json_decode($response);
$sessionId = $object->{'session'}->id;
//$sessionSuccess = $object->{'successIndicator'};
//echo $sessionId;
echo $sessionId;
I Found the solution. MerchantId was missing in **Checkout.configure()** method.
I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))