Я создаю частное веб-приложение для своего магазина shopify, которое больше отвечает потребностям нашего бизнеса. Хотя я могу сделать дамп «все заказы» или «все продукты» и т. д. В Mysql, я не смог понять, как выполнить веб-перехватчик создания заказа shopify, чтобы вставить новый заказ при создании в Shopify в базу данных Mysql.
Вместо этого мне нужно будет запускать мой скрипт каждые «x» раз, чтобы увидеть, есть ли новый заказ (это может, если я не ошибаюсь, привести к превышению моего лимита API, если я одновременно выполняю другие вызовы API).
Я понимаю процесс событий, но я изо всех сил пытаюсь выполнить!
1. New order created in Shopify by Customer &or Admin.
2. Triggers webhook and sends Json to desired url i.e(https://mydomain//new-order.php). -> [Struggling]
3. When this happens the Json is decoded. -> [Struggling]
4. Assigned to a variable. -> [This i can do]
5. Inserted into a Mysql database. -> [This i can do]
=> Question:
How do you once you have created the webhook (in Shopify) get it to trigger your code to run thereafter and execute?
ниже приведен код, который я собрал, но когда я отправил тестовую ловушку, база данных не обновляется.
Все в файле [new-orders.php] (разбит, чтобы показать ход моих мыслей):
[1] Учетные данные частного приложения для подключения к магазину Shopify.
<?php
$api_url = https://apikey:[email protected]';
$shopify = $api_url . '/admin/webhooks.json';
[2] Создайте массив для аргументов веб-перехватчика, когда срабатывает перехватчик, и назначьте его переменной $ webhooks.
$arguments = array(
'topic' => 'order/creation',
'address' => 'https://mydomain//new-order.php'
);
$webhooks = $api_url . '/admin/webhooks.json', $arguments;
[3] Расшифровать данные веб-перехватчика.
$webhook_content = '';
$webhook = fopen('php://input' , 'rb');
while(!feof($webhook)){ //loop through the input stream while the end of file is not reached
$webhook_content .= fread($webhook, 4096); //append the content on the current iteration
}
fclose($webhook); //close the resource
$orders = json_decode($webhook_content, true); //convert the json to array
[4] Добавьте новый заказ в таблицу базы данных Mysql.
// not sure if a foreach loop is necessary in this case?
foreach($orders as $order){
$servername = "mysql.servername.com";
$database = "database_name";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$order_id = $order['id'];
$order_number = $order['name'];
$f_name = $order['billing_address']['name'];
$payment_gateway = $order['gateway'];
$financial_status = $order['financial_status'];
$order_value = $order['total_price'];
$order_status = $order['#'];
$shipping_province = $order['shipping_address']['province'];
$created_at = $order['created_at'];
$updated_at = $order['updated_at'];
$shipping_method = $order['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id, order_number, cust_fname, payment_gateway, financial_status, order_value, order_status, ship_to, created_at, updated_at, shipping_method)
VALUES ('$created_at', '$order_id', '$order_number', '$f_name', '$payment_gateway', '$financial_status', '$order_value', '$order_status', '$shipping_province', '$created_at', '$updated_at', '$shipping_method')");
}
?>
Любая помощь будет принята с благодарностью, и я надеюсь, что дал достаточно контекста для проблемы, с которой я сейчас сталкиваюсь. Если потребуется какая-либо другая информация, я постараюсь изо всех сил объяснить, почему я сделал что-то именно так.
С уважением,
@BRroe, спасибо за внимание! Я недавно начал «разрабатывать», так что многое из того, что вы упомянули, я знаю, что мне нужно делать, но пока не оборудован для этого. Я сосредоточусь на реализации этого.






Обновление, удалось выяснить это, и для тех из вас, кто потенциально борется со следующим, вот как я решил.
Здесь есть 2 аспекта!
1. Setting up the webhook [Shopify -> Notifications -> webhooks].
2. The php file that processes the webhook.
1. -> Create Webhook in shopify and point to where you php url [example.com/Process-webhook.php]
2. -> Process-webhook.php
PHP код
// Load variables
$webhook_content = NULL;
// Get webhook content from the POST
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhook_content .= fread($webhook, 4096);
}
fclose($webhook);
// Decode Shopify POST
$webhook_content = json_decode($webhook_content, TRUE);
$servername = "server_name";
$database = "database";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
//Assign to variable
$order_id = $webhook_content['id'];
$order_number = $webhook_content['name'];
$f_name = $webhook_content['billing_address']['name'];
$payment_gateway = $webhook_content['gateway'];
$financial_status = $webhook_content['financial_status'];
$pick_status = $webhook_content['NULL'];
$pack_status = $webhook_content['NULL'];
$fulfill_status = $webhook_content['NULL'];
$order_value = $webhook_content['total_price'];
$order_status = $webhook_content['NULL'];
$shipping_province = $webhook_content['shipping_address']['province'];
// I wanted to insert the variant_id's and quantity as a string in one column. With this i can unserialise and use when needed
$items = [];
foreach($webhook_content["line_items"] as $item) {
$items[$item["variant_id"]]['quantity'] = $item["quantity"];
}
$items = serialize($items);
$created_at = $webhook_content['created_at'];
$updated_at = $webhook_content['updated_at'];
$shipping_method = $webhook_content['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id,
order_number,
cust_fname,
payment_gateway,
financial_status,
order_value,
order_status,
ship_to,
items,
created_at,
updated_at,
shipping_method)
VALUES ('$order_id',
'$order_number',
'$f_name',
'$payment_gateway',
'$financial_status',
'$order_value',
'$order_status',
'$shipping_province',
'$items',
'$created_at',
'$updated_at',
'$shipping_method')");
?>
Спасибо - это сводило меня с ума. Получение JSON немного запутано!
Начните с регистрации потенциальных ошибок в файле ... когда этот сценарий вызывается удаленным сервером, очевидно, что некому «наблюдать» за этими выходными данными отладки. А также внедрите надлежащий контроль ошибок - прямо сейчас, например, вас даже не интересует, успешен ли этот запрос в конце или нет.