phpish / shopify_app-skeleton

Skeleton Shopify App project using phpish/shopify
94 stars 41 forks source link

shopify_app-skeleton-create-webhhok-api #30

Closed karunyaBobby closed 7 years ago

karunyaBobby commented 7 years ago

I created a custom app form shopify partner account. Used this as my application https://github.com/phpish/shopify_app-skeleton.git configured the Callback URL : myapplicationLink/oauth.php Redirection URl : myapplicationLInk/install.php Changed my myapplicationLInk/conf.php configuretion based on my app.

So i able to install the app in shopify store with some scope like ('read_customers', 'read_orders').

Problem : create webhook through PHP api call, as soon as my app is installed in shopify store. (Not able to know how to do ?)

Question : if my problem is resovled can i see the result in ( https://MYSTORE.myshopify.com/admin/webhook.json ) or not once app is installed ??

Sorry for trouble. I very new to shopify API..

myjanky commented 7 years ago

@karunyaBobby Yes, if your webhook was sent correctly from your app during install it should show up with the /admin/webhook.json url. Alternatively you can manually set up a webhook following these directions https://help.shopify.com/manual/sell-online/notifications/webhooks and you can see the webhook at /admin/webhooks.json

Not sure if there is a function to verify but here ya go,

`<?php

define('SHOPIFY_APP_SECRET', 'my_shared_secret');

function verify_webhook($data, $hmac_header) { $calculated_hmac = base64_encode(hash_hmac('sha256', $data, SHOPIFY_APP_SECRET, true)); return ($hmac_header == $calculated_hmac); }

$hmac_header = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256']; $data = file_get_contents('php://input'); $verified = verify_webhook($data, $hmac_header); error_log('Webhook verified: '.var_export($verified, true)); //check error.log to see the result

?>`

karunyaBobby commented 7 years ago

thank you for response . @myjanky

I dont to create manually in shopify store.

I want my custom app need to to create during app install process.

So I dont know what exactly the PHP code to create WEBHOOK during install of my custom app.

Please any one can help me. what should be exact code to create webhook.

karunyaBobby commented 7 years ago

can you please tell me, how to create webhook during my custom app install.

In my install.php file i modified to like this: (its not creating any webhook) `<?php

require __DIR__.'/vendor/autoload.php';
use phpish\shopify;
require __DIR__.'/conf.php';
isset($_GET['shop']) or die ('Query parameter "shop" missing.');
preg_match('/^[a-zA-Z0-9\-]+.myshopify.com$/', $_GET['shop']) or die('Invalid myshopify.com store URL.');
$install_url = shopify\install_url($_GET['shop'], SHOPIFY_APP_API_KEY);
    try {
             $oauth_token = shopify\access_token($_GET['shop'], SHOPIFY_APP_API_KEY,  SHOPIFY_APP_SHARED_SECRET, $_GET['code']);
      $_SESSION['oauth_token'] = $oauth_token;
      $_SESSION['shop'] = $_GET['shop'];
      $shopify = shopify\client($_SESSION['shop'], SHOPIFY_APP_API_KEY, $_SESSION['oauth_token']);
      $shop = $_GET['shop'];
      $token = $oauth_token;
      $query = `array(`
        "Content-type" => "application/json" // Tell Shopify that we're expecting a response in JSON format
      );
      $webhooks = $shopify('POST', '/admin/webhook.json', array
                               (
                               "webhook" => array
                                                        (
                                                        "topic" => "orders/create",
                                                        "address" => "MY callback url",
                                                        "format" => "json"
                               ),

      ));

      echo 'App Successfully Installed!'; exit;
 } catch (shopify\ApiException $e) {
      # HTTP status code was >= 400 or response contained the key 'errors'
      echo $e;
      print_R($e->getRequest());
      print_R($e->getResponse());

      } catch (shopify\CurlException $e) {
      # cURL error
      echo $e;
      print_R($e->getRequest());
      print_R($e->getResponse());
 }

echo "<script> top.location.href='$install_url'</script>";

?>`

myjanky commented 7 years ago

you should do the webhook creation after install.php

For example, where the echo 'app successfully installed'; change to header('location: your script for webhook use get_product.php as example.')

karunyaBobby commented 7 years ago

ok Thank you. i have done by taking ohShopify API. i installed the app too.

`<?php require 'shopify.php'; require 'defines.php'; if (isset($_GET['code'])) { $shopifyClient = new ShopifyClient($_GET['shop'], "", SHOPIFY_API_KEY, SHOPIFY_SECRET); session_unset();

 // Now, request the token and store it in your session.
 $_SESSION['token'] = $shopifyClient->getAccessToken($_GET['code']);
 if ($_SESSION['token'] != '')
      $_SESSION['shop'] = $_GET['shop'];

 header("Location: index.php/");
 exit;

} else if (isset($_POST['shop'])) { $shop = isset($_POST['shop']) ? $_POST['shop'] : $_GET['shop']; $shopifyClient = new ShopifyClient($shop, "", SHOPIFY_API_KEY, SHOPIFY_SECRET); $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") { $pageURL .= "s"; } $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["SCRIPT_NAME"]; } else { $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["SCRIPT_NAME"]; } header("Location: " . $shopifyClient->getAuthorizeUrl(SHOPIFY_SCOPE, $pageURL)); exit; } ?>

Install this app in a shop to get access to its private admin data.

Don’t have a shop to install your app in handy? Create a test shop.

` **its location header to index.php after insall. and my index.php containing** `call('POST', '/admin/webhook.json', array ( "webhook" => array ( "topic" => "customers/create", // "address" => "https://control.msg91.com/api/sendhttp.php?authkey=149477AfEa6LjoMIPV58f709c4&mobiles=9980272940&message=HelloMsg91&sender=NewUsr&route=4&country=91&response=json", "address" => "http://msg91.pagekite.me/ohShopify/customerWebhook.php", "format" => "json" ), )); print_r('success'); } catch (ShopifyApiException $e) { print_r($e); } catch (ShopifyCurlException $e) { print_r($e); print_r($e->getMessage()); // $e->getMessage() returns value of curl_errno() and $e->getCode() returns value of curl_ error() }` Bug : its not created any webhook in my store (sending ShopifyApiException Object )
karunyaBobby commented 7 years ago

I tried with the shopify_app-skeleton-create-webhhok-api Getting response like :phpish\shopify\CurlException ShopifyApiException Object

myjanky commented 7 years ago

would need to know what object it is passing back. can you var_dump()

karunyaBobby commented 7 years ago

ok i will do

myjanky commented 7 years ago

http://stackoverflow.com/questions/14251851/what-is-406-not-acceptable-response-in-http

it is a status code. 406 header issue.

Array ( [http_status_message] => Not Acceptable [http_status_code] => 406 [server] => nginx [date] => Thu, 11 May 2017 12:39:05 GMT [content-type] => application/json [transfer-encoding] => chunked [connection] => keep-alive [referrer-policy] => origin-when-cross-origin [x-frame-options] => DENY [x-shopid] => 19804811 [x-shardid] => 8 [x-shopify-shop-api-call-limit] => 1/40 [http_x_shopify_shop_api_call_limit] => 1/40 [x-stats-userid] => 0 [x-stats-apiclientid] => 1626373 [x-stats-apipermissionid] => 50719753 [content-security-policy] => default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https:// shopify-pos://; block-all-mixed-content; child-src 'self' https:// shopify-pos://; connect-src 'self' wss:// https://

karunyaBobby commented 7 years ago

yes

karunyaBobby commented 7 years ago

ShopifyApiException Object ( [method:protected] => POST [path:protected] => /admin/webhook.json [params:protected] => Array ( [webhook] => Array ( [topic] => customers/create [address] => http://msg91.pagekite.me/ohShopify/CustomerWebhook.php [format] => json ) ) [response_headers:protected] => Array ( [http_status_message] => Not Acceptable [http_status_code] => 406 [server] => nginx [date] => Thu, 11 May 2017 12:39:05 GMT [content-type] => application/json [transfer-encoding] => chunked [connection] => keep-alive [referrer-policy] => origin-when-cross-origin [x-frame-options] => DENY [x-shopid] => 19804811 [x-shardid] => 8 [x-shopify-shop-api-call-limit] => 1/40 [http_x_shopify_shop_api_call_limit] => 1/40 [x-stats-userid] => 0 [x-stats-apiclientid] => 1626373 [x-stats-apipermissionid] => 50719753 [content-security-policy] => default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https:// shopify-pos://; block-all-mixed-content; child-src 'self' https:// shopify-pos://; connect-src 'self' wss:// https://; script-src https://cdn.shopify.com https://checkout.shopifycs.com https://js-agent.newrelic.com https://bam.nr-data.net https://dme0ih8comzn4.cloudfront.net https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://maps.googleapis.com https://stats.g.doubleclick.net https://www.google-analytics.com https://visitors.shopify.com https://v.shopify.com https://widget.intercom.io https://js.intercomcdn.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; report-uri /csp-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin&source%5Buuid%5D=8109e0a4-9b1d-4cd4-8aae-2706b6e3ac79 [x-content-type-options] => nosniff [x-download-options] => noopen [x-permitted-cross-domain-policies] => none [x-xss-protection] => 1; mode=block; report=/xss-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin&source%5Buuid%5D=8109e0a4-9b1d-4cd4-8aae-2706b6e3ac79 [x-dc] => ash,chi2 [x-request-id] => 8109e0a4-9b1d-4cd4-8aae-2706b6e3ac79 ) [response:protected] => [message:protected] => Not Acceptable [string:Exception:private] => [code:protected] => 406 [file:protected] => /var/www/ohShopify/shopify.php [line:protected] => 70 [trace:Exception:private] => Array ( [0] => Array ( [file] => /var/www/ohShopify/index.php [line] => 24 [function] => call [class] => ShopifyClient [type] => -> [args] => Array ( [0] => POST [1] => /admin/webhook.json [2] => Array ( [webhook] => Array ( [topic] => customers/create [address] => http://msg91.pagekite.me/ohShopify/CustomerWebhook.php [format] => json ) ) ) ) ) [previous:Exception:private] => )

myjanky commented 7 years ago

should probably open issue in ohShopify github.

this is phpish which is not been updated in a while.

karunyaBobby commented 7 years ago

ok . how will i go further . any solution you suggest?

karunyaBobby commented 7 years ago

Ok Thank you. i will post this in ohShopify github.

myjanky commented 7 years ago

Your server setup is causing the issue and not ohShopify. If you can configure your server response headers. what are your origin policies? http://stackoverflow.com/questions/14251851/what-is-406-not-acceptable-response-in-http

karunyaBobby commented 7 years ago

hello sir, What response header i need to configured in my server??

karunyaBobby commented 7 years ago

This is my ShopifyApiException error. how to resolved that . i am using ohShopify.php-master api `ShopifyApiException Object ( [method:protected] => POST [path:protected] => /admin/webhook.json [params:protected] => Array ( [webhook] => Array ( [topic] => customers/create [address] => http://msg91.pagekite.me/ohShopify/customerWebhook.php [format] => json )

    )

[response_headers:protected] => Array
    (
        [http_status_message] => Not Acceptable
        [http_status_code] => 406
        [server] => nginx
        [date] => Fri, 12 May 2017 07:49:40 GMT
        [content-type] => application/json
        [transfer-encoding] => chunked
        [connection] => keep-alive
        [referrer-policy] => origin-when-cross-origin
        [x-frame-options] => DENY
        [x-shopid] => 19804811
        [x-shardid] => 8
        [x-shopify-shop-api-call-limit] => 1/40
        [http_x_shopify_shop_api_call_limit] => 1/40
        [x-stats-userid] => 0
        [x-stats-apiclientid] => 1626373
        [x-stats-apipermissionid] => 50808249
        [content-security-policy] => default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; script-src https://cdn.shopify.com https://checkout.shopifycs.com https://js-agent.newrelic.com https://bam.nr-data.net https://dme0ih8comzn4.cloudfront.net https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://maps.googleapis.com https://stats.g.doubleclick.net https://www.google-analytics.com https://visitors.shopify.com https://v.shopify.com https://widget.intercom.io https://js.intercomcdn.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; report-uri /csp-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin&source%5Buuid%5D=cda9adf2-b0e8-434d-9137-85f6df33b107
        [x-content-type-options] => nosniff
        [x-download-options] => noopen
        [x-permitted-cross-domain-policies] => none
        [x-xss-protection] => 1; mode=block; report=/xss-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin&source%5Buuid%5D=cda9adf2-b0e8-434d-9137-85f6df33b107
        [x-dc] => ash,chi2
        [x-request-id] => cda9adf2-b0e8-434d-9137-85f6df33b107
    )

[response:protected] => 
[message:protected] => Not Acceptable
[string:Exception:private] => 
[code:protected] => 406
[file:protected] => /var/www/ohShopify/shopify.php
[line:protected] => 70
[trace:Exception:private] => Array
    (
        [0] => Array
            (
                [file] => /var/www/ohShopify/index.php
                [line] => 24
                [function] => call
                [class] => ShopifyClient
                [type] => ->
                [args] => Array
                    (
                        [0] => POST
                        [1] => /admin/webhook.json
                        [2] => Array
                            (
                                [webhook] => Array
                                    (
                                        [topic] => customers/create
                                        [address] => http://msg91.pagekite.me/ohShopify/customerWebhook.php
                                        [format] => json
                                    )

                            )

                    )

            )

    )

[previous:Exception:private] => 

)`

karunyaBobby commented 7 years ago

hello everyone,

To POST or GET mothod of webhook.json

what should be the scpoe ??

myjanky commented 7 years ago

should be post to create, put to modify and get to retrieve. all documented here.https://help.shopify.com/api/reference/webhook

are you only using ohShopify and not phpish? or do you have a mixture of the libs? I know some users of phpish have taken snippets from ohShopify due to the hmac change

I do not think you need a scope to publish a webhook. https://help.shopify.com/api/getting-started/authentication/oauth#scopes

karunyaBobby commented 7 years ago

ok its resolved. i was getting 406 non-acceptance because of not proper scope. if i dont have write scope for any event of web hook, i cant do the POST request. Thank you for your valuable time.