@@ -60,6 +60,42 @@ public static function sanitizeShopDomain(string $shop, ?string $myshopifyDomain
6060 }
6161 }
6262
63+ /**
64+ * Builds query strings that are compatible with Shopify's format for array handling
65+ * Example: IDs = [1,2,3]
66+ * PHP would generate: ids[]=1&IDs[]=2&IDs[]=3
67+ * Shopify expects: ids=["1","2","3"] (URL encoded)
68+ *
69+ * @param array $params Array of query parameters
70+ *
71+ * @return string The URL encoded query string ("foo=bar&bar=foo")
72+ */
73+ public static function buildQueryString (array $ params ): string
74+ {
75+ // Exclude HMAC from query string
76+ $ params = array_filter ($ params , function ($ key ) {
77+ return $ key !== 'hmac ' ;
78+ }, ARRAY_FILTER_USE_KEY );
79+
80+ // Concatenate arrays to conform with Shopify
81+ array_walk ($ params , function (&$ value , $ key ) {
82+ if (!is_array ($ value )) {
83+ return ;
84+ }
85+
86+ $ escapedValues = array_map (function ($ value ) {
87+ return sprintf ('"%s" ' , $ value );
88+ }, $ value );
89+ $ concatenatedValues = implode (', ' , $ escapedValues );
90+ $ encapsulatedValues = sprintf ('[%s] ' , $ concatenatedValues );
91+
92+ $ value = $ encapsulatedValues ;
93+ });
94+
95+ // Building the actual query using PHP's native function
96+ return http_build_query ($ params );
97+ }
98+
6399 /**
64100 * Determines if request is valid by processing secret key through an HMAC-SHA256 hash function
65101 *
@@ -70,12 +106,14 @@ public static function sanitizeShopDomain(string $shop, ?string $myshopifyDomain
70106 */
71107 public static function validateHmac (array $ params , string $ secret ): bool
72108 {
73- $ hmac = $ params ['hmac ' ] ?? '' ;
74- unset($ params ['hmac ' ]);
75-
76- $ computedHmac = hash_hmac ('sha256 ' , http_build_query ($ params ), $ secret );
109+ if (empty ($ params ['hmac ' ]) || empty ($ secret )) {
110+ return false ;
111+ }
77112
78- return hash_equals ($ hmac , $ computedHmac );
113+ return hash_equals (
114+ $ params ['hmac ' ],
115+ hash_hmac ('sha256 ' , self ::buildQueryString ($ params ), $ secret )
116+ );
79117 }
80118
81119 /**
0 commit comments