-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.php
67 lines (56 loc) · 2.06 KB
/
app.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
require 'vendor/autoload.php';
require 'classes/Authenticator.php';
require 'classes/ShopifyRequest.php';
// Some basic auth.
$access = false;
// Authenticate the user.
try {
$auth = new Authenticator();
// First check if we have a valid session.
$access = $auth->checkSession();
// Failing that, authenticate as normal.
if (!empty($_POST['submit']) && $_POST['submit'] === 'login' && !$access) {
$user = !empty($_POST['user']) ? $_POST['user'] : '';
$pass = !empty($_POST['pass']) ? $_POST['pass'] : '';
$access = $auth->setCredentials($user, $pass)->checkCredentials();
}
} catch (Exception $e) {
$status = ['level' => 'danger', 'message' => $e->getMessage()];
}
// ...We're authenticated
if (!empty($_POST['submit']) && $_POST['submit'] === 'add_product') {
try {
$shopify = new ShopifyRequest();
// Build the payload.
$payload = ['product' => []];
// Keep control over posted values.
$allowable_values = [
'title' => ['title' => 'Title', 'required' => true],
'product_type' => ['title' => 'Type', 'required' => true],
'vendor' => ['title' => 'Vendor', 'required' => true],
'body_html' => ['title' => 'Description'],
'images' => ['title' => 'Image']
];
foreach ($allowable_values as $field => $value) {
if ((isset($value['required']) && $value['required']) && empty($_POST[$field])) {
$status = ['level' => 'danger', 'message' => "{$value['title']} is a required field."];
break;
}
// Images are stored as an array of arrays.
if ($field === 'images') {
$payload['product'][$field][]['attachment'] = !empty($_POST[$field]) ? $_POST[$field] : null;
} else {
$payload['product'][$field] = !empty($_POST[$field]) ? $_POST[$field] : null;
}
}
// If nothing went awry, do the request.
if (empty($status)) {
$shopify->doRequest('POST', 'admin/products.json', $payload);
$status = ['level' => 'success', 'message' => 'Product added successfully.'];
}
} catch (Exception $e) {
$status = ['level' => 'danger', 'message' => $e->getMessage()];
}
}
?>