Как я могу создать приложение из настроек своего локального веб-сайта и развернуть файлы в учетной записи партнера по шопифи? - PullRequest
2 голосов
/ 19 марта 2020

Я хочу создать приложение из настроек локальной системы. Но процедура, которой я следую, не работает должным образом. Я видел несколько видеоуроков, но они не дали нужного результата. Я создал четыре файла с именем: generate_token. php, install. php, api_call_write_products. php, в папке c, включая один файл функций. php. Я создал одно частное приложение с сайта администратора учетной записи партнера, но оно все еще не работает. Как я могу загрузить эти файлы в свои учетные записи партнеров. Существует ли какой-либо сторонний инструмент для загрузки / развертывания этих четырех файлов, в том числе в папках c? Как я могу интегрировать свои локальные файлы в учетную запись партнера, чтобы я мог видеть мое приложение в учетной записи партнера. Я добавил ключи API и ключ Shared_secret в файлы, где это было необходимо. Я добавил файлы ниже -

install. php

<?php

// Set variables for our request
$shop = $_GET['shop'];
$api_key = "***************";
$scopes = "read_orders,write_products";
$redirect_uri = "https://dd351ab1814cec97dcb5e8d919887c2a:abb65451f1f5c828011242c806971e2b@bahlultechstore.myshopify.com/admin/api/2020-01/orders.json/generate_token.php";

// Build install/approval URL to redirect to
$install_url = "https://" . $shop . ".myshopify.com/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);

// Redirect
header("Location: " . $install_url);
die();

generate_token. php

  <?php

 // Get our helper functions
 require_once("inc/functions.php");

 // Set variables for our request
 $api_key = "**********************";
 $shared_secret = "***********************";
 $params = $_GET; // Retrieve all request parameters
 $hmac = $_GET['hmac']; // Retrieve HMAC request parameter

 $params = array_diff_key($params, array('hmac' => '')); // Remove hmac from params
 ksort($params); // Sort params lexographically

 $computed_hmac = hash_hmac('sha256', http_build_query($params), $shared_secret);

// Use hmac data to check that the response is from Shopify or not
if (hash_equals($hmac, $computed_hmac)) {

// Set variables for our request
$query = array(
    "client_id" => $api_key, // Your API key
    "client_secret" => $shared_secret, // Your app credentials (secret key)
    "code" => $params['code'] // Grab the access key from the URL
);

// Generate access token URL
$access_token_url = "https://" . $params['shop'] . "/admin/oauth/access_token";

// Configure curl client and execute request
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $access_token_url);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
$result = curl_exec($ch);
curl_close($ch);

// Store the access token
$result = json_decode($result, true);
$access_token = $result['access_token'];

// Show the access token (don't do this in production!)
echo $access_token;

} else {
// Someone is trying to be shady!
die('This request is NOT from Shopify!');
}

api_call_write_products. php

// Get our helper functions
require_once("inc/functions.php");

// Set variables for our request
$shop = "demo-shop";
$token = "*******************";
$query = array(
    "Content-type" => "application/json" // Tell Shopify that we're expecting a response in JSON format
);

// Run API call to get products
$products = shopify_call($token, $shop, "/admin/products.json", array(), 'GET');

// Convert product JSON information into an array
$products = json_decode($products['response'], TRUE);

// Get the ID of the first product
$product_id = $products['products'][0]['id'];

// Modify product data
$modify_data = array(
    "product" => array(
        "id" => $product_id,
        "title" => "My New Title"
    )
);

// Run API call to modify the product
$modified_product = shopify_call($token, $shop, "/admin/products/" . $product_id . ".json", $modify_data, 'PUT');

// Storage response
$modified_product_response = $modified_product['response'];

функция. php

<?php

function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', 
$request_headers = array()) {

// Build URL
$url = "https://" . $shop . ".myshopify.com" . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET',  'DELETE'))) $url = $url . "?" . http_build_query($query);

// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);

// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);

if ($method != 'GET' && in_array($method, array('POST', 'PUT'))) {
    if (is_array($query)) $query = http_build_query($query);
    curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}

// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);

// Close cURL to be nice
curl_close($curl);

// Return an error is cURL has a problem
if ($error_number) {
    return $error_message;
} else {

    // No error, return Shopify's response by parsing out the body and the headers
    $response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);

    // Convert headers into an array
    $headers = array();
    $header_data = explode("\n",$response[0]);
    $headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
    array_shift($header_data); // Remove status, we've already set it above
    foreach($header_data as $part) {
        $h = explode(":", $part);
        $headers[trim($h[0])] = trim($h[1]);
    }

    // Return headers and Shopify's response
    return array('headers' => $headers, 'response' => $response[1]);

}

}

1 Ответ

0 голосов
/ 20 марта 2020

Вы не загружаете свои файлы в Shopify, вы размещаете их на своем собственном сервере.

Если вы хотите проверить свой код локально, используйте ngrok. Вы можете найти шаги, как это сделать здесь .

Если вы хотите, чтобы среда prod посмотрела на heroku для размещения вашего кода.

...