Shopify.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Shopify/Public.pm ↑ Summary
1 #!/usr/bin/perl
2  
3 =head1 NAME
4  
5 WWW::Shopify - Main object representing acess to a particular Shopify store.
6  
7 =cut
8  
9 =head1 DISCLAIMER
10  
11 WWW::Shopify is my first official CPAN module, so please bear with me as I try to sort out all the bugs, and deal with the unfamiliar CPAN infrastructure. Don't expect this to work out of the box as of yet, I'm still learning exactly how things are working. Hence some version problems I've been having.
12  
13 Thanks for your understanding.
14  
15 =cut
16  
17 =head1 DESCRIPTION
18  
19 WWW::Shopify represents a way to grab and upload data to a particular shopify store.
20 All that's required is the access token for a particular app, its url, and the API key, or altenratively, if you have a private app, you can substitue the app password for the api key.
21 If you want to use make a private app, use WWW::Shopify::Private. If you want to make a public app, use WWW::Shopify::Public.
22  
23 =cut
24  
25 =head1 EXAMPLES
26  
27 In order to get a list of all products, we can do the following:
28  
29 # Here we instantiate a copy of the public API object, with all the necessary fields.
30 my $sa = new WWW::Shopify::Public($shop_url, $api_key, $access_token);
31  
32 # Here we call get_all, OO style, and specify the entity we want to get.
33 my @products = $sa->get_all('Product');
34  
35 In this way, we can get and modify all the different types of shopify stuffs.
36  
37 If you don't want to be using a public app, and just want to make a private app, it's just as easy:
38  
39 # Here we instantiate a copy of the private API object this time, which means we don't need an access token, we just need a password.
40 my $sa = new WWW::Shopify::Private($shop_url, $api_key, $password);
41 my @products = $sa->get_all('Product');
42  
43 Easy enough.
44  
45 To insert a Webhook, we'd do the following.
46  
47 my $webhook = new WWW::Shopify::Model::Webhook({topic => "orders/create", address => $URL, format => "json"});
48 $sa->create($Webhook);
49  
50 And that's all there is to it. To delete all the webhooks in a store, we'd do:
51  
52 $sa->delete($_) for ($sa->get_all('Webhook'));
53  
54 Very easy.
55  
56 If we want to do something like update an existing product, without getting it, you can simply create a wrapper object to pass to the sub. Let's update a product's title, if all we have
57 is the product ID.
58  
59 $sa->update(WWW::Shopify::Model::Product->new({ id => $product_id, title => "My New Title!" }));
60  
61 That'll update the product title.
62  
63 Now, for another example. Let's say we want to get all products that have the letter "A" in their title, and double the weight of all their variants (randomly). This is also very easy.
64  
65 my @products = $sa->get_all("Product");
66 for my $variant (map { $_->variants } grep { $_->title =~ m/A/ } @products) {
67 $variant->weight($variant->weight*2);
68 $sa->update($variant);
69 }
70  
71 =cut
72  
73 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
74 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
75 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
76  
77 package WWW::Shopify;
78  
79 our $VERSION = '1.04';
80  
81 1 ▶use WWW::Shopify::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
82 1 ▶use WWW::Shopify::Field;
Subroutine BEGIN: called CC=1 SCAR=0.0
83 0 ▶use Module::Find;
Subroutine BEGIN: called CC=1 SCAR=2.6
84 use WWW::Shopify::URLHandler;
85 use WWW::Shopify::Query;
86 use WWW::Shopify::Login;
87 use WWW::Shopify::GraphQL;
88  
89  
90 # Make sure we include all our models so that when people call the model, we actually know what they're talking about.
91 BEGIN { eval(join("\n", map { "require $_;" } findallmod WWW::Shopify::Model)); if (my $exp = $@) { die $exp; } }
92  
93 package WWW::Shopify;
94  
95 use Date::Parse;
96  
97 =head1 METHODS
98  
99 =head2 new($shop_url, [$email, $pass])
100  
101 Creates a new shop, without using the actual API, uses automated form submission to log in.
102  
103 =cut
104  
105 sub new {
106 my ($package, $shop_url, $email, $password, $api_version) = @_;
107 die new WWW::Shopify::Exception("Can't create a shop without a shop url.") unless $shop_url;
108 $api_version = '2022-04' unless $api_version && ($api_version =~ m/\d\d\d\d-\d\d/ || $api_version =~ m/^unstable$/);
109 my $ua = LWP::UserAgent->new( ($^O eq' linux' ? (ssl_opts => {'SSL_version' => 'TLSv12' }) : ()) );
110 $ua->cookie_jar({ });
111 $ua->timeout(60);
112 $ua->agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
113 $package = "WWW::Shopify::Login" if $package eq "WWW::Shopify";
114 my $self = bless { _shop_url => $shop_url, _ua => $ua, _url_handler => undef, _api_calls => 0, _sleep_for_limit => 0, _retry_on_errors => 0, _last_timestamp => undef, _decode_entities => 1, _api_version => $api_version, _max_call_limit => 40 }, $package;
115 $self->{_ql} = new WWW::Shopify::GraphQL($self);
116 $self->url_handler(new WWW::Shopify::URLHandler($self));
117 return $self;
118 }
119  
120  
121 sub version { $_[0]->{_version} = $_[1] if defined $_[1]; return $_[0]->{_version}; }
122 sub api_calls { $_[0]->{_api_calls} = $_[1] if defined $_[1]; return $_[0]->{_api_calls}; }
123 sub max_api_calls { $_[0]->{_max_call_limit} = $_[1] if defined $_[1]; return $_[0]->{_max_call_limit}; }
124 sub url_handler { $_[0]->{_url_handler} = $_[1] if defined $_[1]; return $_[0]->{_url_handler}; }
125 sub sleep_for_limit { $_[0]->{_sleep_for_limit} = $_[1] if defined $_[1]; return $_[0]->{_sleep_for_limit}; }
126 sub retry_on_errors { $_[0]->{_retry_on_errors} = $_[1] if defined $_[1]; return $_[0]->{_retry_on_errors}; }
127 sub last_timestamp { $_[0]->{_last_timestamp} = $_[1] if defined $_[1]; return $_[0]->{_last_timestamp}; }
128 sub decode_entities { $_[0]->{_decode_entities} = $_[1] if defined $_[1]; return $_[0]->{_decode_entities}; }
129 sub api_version { $_[0]->{_api_version} = $_[1] if defined $_[1]; return $_[0]->{_api_version}; }
130 sub include_presentment_prices {
131 my ($self, $enabled) = @_;
132 if ($enabled) {
133 $self->url_handler->default_header('X-Shopify-Api-Features' => 'include-presentment-prices');
134 } else {
135 $self->url_handler->default_header('X-Shopify-Api-Features' => $self->url_handler->default_header('X-Shopify-Api-Features') =~ s/,\s*include\-presentment\-prices//ri);
136 }
137 }
138  
139 sub ql { $_[0]->{_ql} = $_[1] if defined $_[1]; return $_[0]->{_ql}; }
140  
141 =head2 encode_url($url)
142  
143 Basic url encoding, works the same for public apps or logged-in apps.
144  
145 =cut
146  
147 sub encode_url { return "https://" . $_[0]->shop_url . $_[1]; }
148  
149  
150 =head2 ua([$new_ua])
151  
152 Gets/sets the user agent we're using to access shopify's api. By default we use LWP::UserAgent, with a timeout of 5 seconds.
153  
154 PLEASE NOTE: At the very least, with LWP::UserAgent, at least, on my system, I had to force the SSL layer of the agent to use TLSv12, using the line
155  
156 LWP::UserAgent->new( ssl_opts => { SSL_version => 'TLSv12' } );
157  
158 Otherwise, Shopify does some very weird stuff, and some very weird errors are spit out. Just FYI.
159  
160 =cut
161  
162 sub ua { $_[0]->{_ua} = $_[1] if defined $_[1]; return $_[0]->{_ua}; }
163  
164  
165 =head2 shop_url([$shop_url])
166  
167 Gets/sets the shop url that we're going to be making calls to.
168  
169 =cut
170  
171 # Modifiable Attributes
172 sub shop_url { $_[0]->{_shop_url} = $_[1] if defined $_[1]; return $_[0]->{_shop_url}; }
173  
174 sub translate_model($) {
175 return $_[1] if $_[1] =~ m/WWW::Shopify::Model/;
176 return "WWW::Shopify::Model::" . $_[1];
177 }
178  
179 sub PULLING_ITEM_LIMIT { return 250; }
180 #sub CALL_LIMIT_REFRESH { return 60*5; }
181 #sub CALL_LIMIT_MAX { return 500; }
182 sub CALL_LIMIT_MAX { return 40; }
183 sub CALL_LIMIT_LEAK_TIME { return 1; }
184 sub CALL_LIMIT_LEAK_RATE { return 2; }
185  
186 sub get_url { return $_[0]->url_handler->get_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
187 sub post_url { return $_[0]->url_handler->post_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
188 sub put_url { return $_[0]->url_handler->put_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
189 sub delete_url { return $_[0]->url_handler->delete_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
190  
191 use Data::Dumper;
192 sub use_url {
193 my ($self, $type, $url, @args) = @_;
194 my $method = lc($type) . "_url";
195 my ($decoded, $response);
196 $url = $self->encode_url($url);
197 eval {
198 my $error_count = 0;
199 my $repeatable_error = undef;
200 do {
201 eval {
202 if ($self->sleep_for_limit) {
203 do {
204 eval { ($decoded, $response) = $self->$method($url, @args); };
205 if (my $exp = $@) {
206 die $exp if !ref($exp) || ref($exp) ne 'WWW::Shopify::Exception::CallLimit';
207 sleep(1);
208 }
209 } while (!$response);
210 } else {
211 ($decoded, $response) = $self->$method($url, @args);
212 }
213 };
214 if ($repeatable_error = $@) {
215 if (!$self->retry_on_errors || $error_count++ >= $self->retry_on_errors) {
216 die $repeatable_error;
217 }
218 }
219 } while ($repeatable_error);
220 };
221 if (my $exp = $@) {
222 print STDERR Dumper($exp->error) if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} > 1;
223 die $exp;
224 }
225 print STDERR uc($type) . " " . $response->request->uri . "\n" if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} == 1;
226 print STDERR Dumper($response) if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} > 1;
227 $self->last_timestamp(DateTime->from_epoch( epoch => str2time($response->header('Date'))) ) if $response && $response->header('Date');
228 return ($decoded, $response);
229 }
230  
231 use Devel::StackTrace;
232 sub resolve_trailing_url {
233 my ($self, $package, $action, $parent, $specs) = @_;
234 $package = ref($package) if ref($package);
235 my $method = lc($action) . "_through_parent";
236 if (($package eq 'WWW::Shopify::Model::Event' && $parent) || ($package->$method && (!$parent || !$parent->is_shop || $package ne "WWW::Shopify::Model::Metafield"))) {
237 die new WWW::Shopify::Exception("Cannot resolve URL, no parent specified.") unless $parent;
238 if ($package eq "WWW::Shopify::Model::Metafield" && ref($parent) eq 'WWW::Shopify::Model::Product::Image' && $specs) {
239 $specs->{"metafield[owner_id]"} = $parent->id;
240 $specs->{"metafield[owner_resource]"} = "product_image";
241 return "/admin/api/" . $self->api_version . $package->prefix . $package->url_plural;
242 }
243 # Should be made more generic when I'm sure this won't mess up any other of Shopfy's crazy API.
244 if ($package eq 'WWW::Shopify::Model::Order::Fulfillment::FulfillmentEvent') {
245 return "/admin/api/" . $self->api_version . $package->prefix . $parent->associated_parent->url_plural . '/' . $parent->associated_parent->id . '/' . $parent->url_plural . '/' . $parent->id . '/' . $package->url_plural;
246 } elsif ($package eq 'WWW::Shopify::Model::Event') {
247 return "/admin/api/" . $self->api_version . $package->prefix . $parent->associated_parent->url_plural . '/' . $parent->associated_parent->id . '/' . $parent->url_plural . '/' . $parent->id . '/' . $package->url_plural if $parent->associated_parent;
248 }
249 return "/admin/api/" . $self->api_version . $package->prefix . $parent->url_plural . "/" . $parent->id . "/" . $package->url_plural;
250 # I cannot believe that I'm doing this. I don't know why I'm surprised, but it just keeps on going.
251 } elsif ($package eq 'WWW::Shopify::Model::ShopifyPayment::Balance::Transaction' && $parent) {
252 $specs->{payout_id} = $parent->id;
253 return "/admin/api/" . $self->api_version . $package->prefix . $package->url_plural;
254 # What the acutal fuck.
255 } elsif ($package eq 'WWW::Shopify::Model::Product' && $parent && ref($parent) && ref($parent) =~ m/Collection$/) {
256 return "/admin/api/" . $self->api_version . "/collections/" . $parent->id . "/products";
257 }
258 return "/admin/api/" . $self->api_version . $package->prefix . $package->url_plural;
259 }
260  
261 sub get_all_limit {
262 my ($self, $package, $specs) = @_;
263 $package = $self->translate_model($package);
264 $specs->{"limit"} = $package->max_per_page unless exists $specs->{"limit"};
265 return () if (defined $specs->{limit} && $specs->{limit} == 0);
266 return $self->get_shop if $package->is_shop;
267 my $url = $self->resolve_trailing_url($package, "get", $specs->{parent}, $specs) . ".json";
268 my ($decoded, $response) = $self->use_url('get', $url, $specs);
269 my @return = $self->{_decode_entities} ? (map { my $object = $package->from_json($_, $self); $object->associated_parent($specs->{parent}); $object; } @{$decoded->{$package->plural}}) : @{$decoded->{$package->plural}};
270 # The links in the headers come in the form
271 #
272 # <https://gift-reggie.myshopify.com/admin/api/2019-10/customers.json?limit=75&page_info=eyJkaXJlY3Rpb24iOiJwcmV2IiwibGFzdF9pZCI6MTA0MTYyOTYxMDAyNywibGFzdF92YWx1ZSI6MTU0MTE4MTU3MzAwMH0>; rel="previous", <https://gift-reggie.myshopify.com/admin/api/2019-10/customers.json?limit=75&page_info=eyJkaXJlY3Rpb24iOiJuZXh0IiwibGFzdF9pZCI6MzM2MTU1NDc2MDA2LCJsYXN0X3ZhbHVlIjoxNTE2MDI3Mjk0MDAwfQ>; rel="next"
273 #
274 # and we want to extract the page_info string.
275 my ($next_page_info) = $response->headers->{link} =~ /.*page_info=([^>|&]*)[^>]*>; rel="next"/ if $response->headers->{link} ;
276 my ($prev_page_info) = $response->headers->{link} =~ /.*page_info=([^>|&]*)[^>]*>; rel="previous"/ if $response->headers->{link} ;
277
278 return (($next_page_info ? $next_page_info : undef), ($prev_page_info ? $prev_page_info : undef), @return);
279 }
280  
281 =head2 get_all($self, $package, $filters)
282  
283 Gets up to 249 * CALL_LIMIT objects (currently 124750) from Shopify at once. Goes in a loop until it's got everything. Performs a count first to see where it's at.
284  
285 @products = $sa->get_all("Product")
286  
287 If you don't want this behaviour, use the limit filter.
288  
289 =cut
290  
291 use POSIX qw/ceil/;
292 use List::Util qw(min);
293 sub get_all {
294 my ($self, $package, $specs) = @_;
295 # objects that still use pageination in 2019-07
296 my %v1907 = (
297 "AbandonedCheckout" => 1,
298 "Article" => 1,
299 "Asset" =>1,
300 "Blog" => 1,
301 "Comment" => 1,
302 "CustomCollection" => 1,
303 "CustomerAddress" => 1,
304 "Customer" => 1,
305 "DiscountCode" => 1,
306 "Dispute" => 1,
307 "DraftOrder" => 1,
308 "Fulfillment" => 1,
309 "GiftCard" => 1,
310 "InventoryItem" => 1,
311 "InventoryLevel" => 1,
312 "LocationLevel" => 1,
313 "MarketingEvent" => 1,
314 "Order" => 1,
315 "Risk" => 1,
316 "Payout" => 1,
317 "PriceRule" => 1,
318 "Refund" => 1,
319 "Report" => 1,
320 "SmartCollection" => 1,
321 "TenderTransaction" => 1,
322 "Transaction" => 1,
323 "Webhook" => 1
324 );
325 return get_all_page(@_) if $self->api_version eq '2019-04' || ($self->api_version eq '2019-07' && $v1907{$package});
326 return get_all_cursor(@_);
327 }
328  
329 sub get_all_cursor {
330 my ($self, $package, $specs, $next_ref, $prev_ref) = @_;
331 # We copy our specs so that we don't modify the original hash. Doesn't have to be a deep copy.
332 $specs = {%$specs} if $specs;
333 $package = $self->translate_model($package);
334 $self->validate_item($package);
335 return $self->get_shop if $package->is_shop;
336
337 my $limit = $specs->{limit};
338 $specs->{limit} = defined $limit && $limit < $package->max_per_page ? $limit : $package->max_per_page;
339
340 my @return;
341 my $callback = $specs->{callback} ? delete $specs->{callback} : undef;
342 my $counter = 0;
343 my $wantarray = wantarray;
344 eval {
345 #delete $specs->{page};
346 my @chunk;
347 my $next_page_info;
348 my $prev_page_info;
349 do {
350 my $real_specs = {%$specs} unless $specs->{page_info};
351 $real_specs->{page_info} = $specs->{page_info} if $specs->{page_info};
352 $real_specs->{parent} = $specs->{parent} if $specs->{page_info};
353 $real_specs->{limit} = $limit ? int($limit) - $counter : $package->max_per_page;
354 $real_specs->{limit} = $package->max_per_page if $package->max_per_page && $real_specs->{limit} > $package->max_per_page;
355 delete $real_specs->{page_info} unless $real_specs->{page_info};
356 ($next_page_info, $prev_page_info, @chunk) = $self->get_all_limit($package, $real_specs);
357 $callback->(undef, @chunk) if $callback;
358 if (defined $wantarray) {
359 if (!defined $limit || (int(@chunk) + int(@return) < $limit)) {
360 push(@return, @chunk);
361 } else {
362 push(@return, grep { defined $_ } @chunk[0..($limit - int(@return) - 1)]);
363 }
364 }
365 $specs->{page_info} = $next_page_info;
366 $$next_ref = $next_page_info if $next_ref;
367 $$prev_ref = $prev_page_info if $prev_ref;
368
369 $counter += int(scalar(@chunk));
370 } while ( (!defined $specs->{limit} || int(scalar(@chunk)) == $specs->{limit}) && (!defined $limit || $counter < $limit) && $specs->{page_info});
371 };
372 if (my $exception = $@) {
373 $exception->extra(\@return) if ref($exception) && $exception->isa('WWW::Shopify::Exception::CallLimit');
374 die $exception;
375 }
376 return @return if wantarray;
377 return $return[0];
378 }
379  
380 #Used for legacy page based pagination or non paginated objects like Assets
381 sub get_all_page {
382 my ($self, $package, $specs) = @_;
383 # We copy our specs so that we don't modify the original hash. Doesn't have to be a deep copy.
384 $specs = {%$specs} if $specs;
385 $package = $self->translate_model($package);
386 $self->validate_item($package);
387 return $self->get_shop if $package->is_shop;
388
389 my $limit = $specs->{limit};
390 $specs->{limit} = defined $limit && $limit < $package->max_per_page ? $limit : $package->max_per_page;
391
392 my @return;
393 my $page = $specs->{page};
394 my $callback = $specs->{callback} ? delete $specs->{callback} : undef;
395 my $counter = 0;
396 my $wantarray = wantarray;
397 my ($null_next_page_info,$null_prev_page_info);
398 eval {
399 $specs->{page} = $specs->{page} ? $specs->{page} : 1;
400 my @chunk;
401 do {
402 ($null_next_page_info,$null_prev_page_info,@chunk) = $self->get_all_limit($package, $specs);
403 $callback->($specs->{page}, @chunk) if $callback;
404 if (defined $wantarray) {
405 if (!defined $limit || (int(@chunk) + int(@return) < $limit)) {
406 push(@return, @chunk);
407 } else {
408 push(@return, grep { defined $_ } @chunk[0..($limit - int(@return) - 1)]);
409 }
410 }
411 $specs->{page}++;
412 $counter += int(@chunk);
413 } while (!defined $page && int(@chunk) == $specs->{limit} && (!defined $limit || $counter < $limit));
414 };
415 if (my $exception = $@) {
416 $exception->extra(\@return) if ref($exception) && $exception->isa('WWW::Shopify::Exception::CallLimit');
417 die $exception;
418 }
419 return @return if wantarray;
420 return $return[0];
421 }
422  
423 =head2 get_access_scopes($self)
424  
425 Returns a list of scopes that the token has access to.
426  
427 my @access_scopes = $sa->get_access_scopes;
428 $access_scopes[0]->{handle}
429  
430 =cut
431  
432 sub get_access_scopes {
433 my ($self) = @_;
434 my ($decoded, $response) = $self->use_url('get', "/admin/oauth/access_scopes.json");
435 return @{$decoded->{'access_scopes'}};
436 }
437  
438  
439 =head2 get_shop($self)
440  
441 Returns the actual shop object.
442  
443 my $shop = $sa->get_shop;
444  
445 =cut
446  
447 sub get_shop {
448 my ($self) = @_;
449 my $package = 'WWW::Shopify::Model::Shop';
450 my ($decoded, $response) = $self->use_url('get', "/admin/" . $package->singular() . ".json");
451 my $object = $package->from_json($decoded->{$package->singular()}, $self);
452 return $object;
453 }
454  
455 =head2 get_timestamp($self)
456  
457 Uses a call to Shopify to determine the DateTime on the shopify server. This can be used to synchronize things without worrying about the
458 local clock being out of sync with Shopify.
459  
460 =cut
461  
462 sub get_timestamp {
463 my ($self) = @_;
464 my $ua = $self->ua;
465 my ($decoded, $response) = $self->use_url('get', "/admin/shop.json");
466 my $date = $response->header('Date');
467 my $time = str2time($date);
468 return DateTime->from_epoch( epoch => $time );
469 }
470  
471 =head2 get_count($self, $package, $filters)
472  
473 Gets the item count from the shopify store. So if we wanted to count all our orders, we'd do:
474  
475 my $order = $sa->get_count('Order', { status => "any" });
476  
477 It's as easy as that. Keep in mind not all items are countable (who the hell knows why); a glaring exception is assets. Either check the shopify docs, or grep for the sub "countable".
478  
479 =cut
480  
481 sub get_count {
482 my ($self, $package, $specs) = @_;
483 $package = $self->translate_model($package);
484 $self->validate_item($package);
485 # If it's not countable (sigh), do a binary search to figure out what the count is. Should find it in ln(n), as opposed to n/250
486 # This is generally better for stores where this could become an issue.
487 # This used to use a binary search to count non-countable objects, but this is broken in cursor based implementation.
488 if (!$package->countable) {
489 die new WWW::Shopify::Exception("Unable to count $package; it is not marked as countable in Shopify's API.")
490 }
491 my ($decoded, $response) = $self->use_url('get', $self->resolve_trailing_url($package, "count", $specs->{parent}, $specs) . "/count.json", $specs);
492 return $decoded->{'count'};
493 }
494  
495 =head2 get($self, $package, $id)
496  
497 Gets the item from the shopify store. Returns it in local (classed up) form. In order to get an order for example:
498  
499 my $order = $sa->get('Order', 142345);
500  
501 It's as easy as that. If we don't retrieve anything, we return undef.
502  
503 =cut
504  
505 sub get {
506 my ($self, $package, $id, $specs) = @_;
507 $package = $self->translate_model($package);
508 $self->validate_item($package);
509 # We have a special case for asssets, for some arbitrary reason.
510 my ($decoded, $response);
511 eval {
512 if ($package !~ m/Asset/) {
513 ($decoded, $response) = $self->use_url('get', $self->resolve_trailing_url($package, "get", $specs->{parent}) . "/$id.json");
514 } else {
515 die new WWW::Shopify::Exception("MUST have a parent with assets.") unless $specs->{parent};
516 ($decoded, $response) = $self->use_url('get', "/admin/api/" . $self->api_version . "/themes/" . $specs->{parent}->id . "/assets.json", {'asset[key]' => $id, theme_id => $specs->{parent}->id});
517 }
518 };
519 if (my $exp = $@) {
520 return undef if ref($exp) && $exp->isa("WWW::Shopify::Exception::NotFound");
521 die $exp;
522 }
523 if ($self->{_decode_entities}) {
524 my $class = $package->from_json($decoded->{$package->singular()}, $self);
525 # Wow, this is straight up stupid that sometimes we don't get a 404.
526 return undef unless $class;
527 $class->associated_parent($specs->{parent});
528 return $class;
529 } else {
530 return $decoded->{$package->singular};
531 }
532 }
533  
534 =head2 search($self, $package, $item, { query => $query })
535  
536 Searches for the item from the shopify store. Not all items are searchable, check the API docs, or grep this module's source code and look for the "searchable" sub.
537  
538 A popular thing to search for is customers by email, you can do so like the following:
539  
540 my $customer = $sa->search("Customer", { query => "email:me@example.com" });
541  
542 =cut
543  
544 sub search {
545 my ($self, $package, $specs) = @_;
546 $package = $self->translate_model($package);
547 die new WWW::Shopify::Exception("Unable to search $package; it is not marked as searchable in Shopify's API.") unless $package->searchable;
548 die new WWW::Shopify::Exception("Must have a query to search.") unless $specs && $specs->{query};
549 $self->validate_item($package);
550  
551 my ($decoded, $response) = $self->use_url('get', $self->resolve_trailing_url($package, "get", $specs->{parent}) . "/search.json", $specs);
552  
553 my @return = ();
554 if ($self->{_decode_entities}) {
555 foreach my $element (@{$decoded->{$package->plural()}}) {
556 my $class = $package->from_json($element, $self);
557 $class->associated_parent($specs->{parent}) if $specs->{parent};
558 push(@return, $class);
559 }
560 } else {
561 @return = @{$decoded->{$package->plural()}}
562 }
563 return @return if wantarray;
564 return $return[0] if int(@return) > 0;
565 return undef;
566 }
567  
568 =head2 create($self, $item)
569  
570 Creates the item on the shopify store. Not all items are creatable, check the API docs, or grep this module's source code and look for the "creatable" sub.
571  
572 =cut
573  
574 use List::Util qw(first);
575 use HTTP::Request::Common;
576 sub create {
577 my ($self, $item, $options) = @_;
578
579 $self->validate_item(ref($item));
580 my $specs = {};
581 my $missing = first { !exists $item->{$_} } $item->creation_minimal;
582 die new WWW::Shopify::Exception("Missing minimal creation member: $missing in " . ref($item)) if $missing;
583 die new WWW::Shopify::Exception(ref($item) . " requires you to login with an admin account.") if ($item->needs_login && !$item->needs_plus) && !$self->logged_in_admin;
584 $specs = $item->to_json();
585 my ($decoded, $response) = $self->use_url($item->create_method, $self->resolve_trailing_url(ref($item), "create", $item->associated_parent) . ".json", {$item->singular() => $specs}, $item->needs_login);
586 my $element = $decoded->{$item->singular};
587 if ($self->{_decode_entities}) {
588 my $object = ref($item)->from_json($element, $self);
589 $object->associated_parent($item->associated_parent);
590 return $object;
591 } else {
592 return $element;
593 }
594 }
595  
596 =head2 update($self, $item)
597  
598 Updates the item from the shopify store. Not all items are updatable, check the API docs, or grep this module's source code and look for the "updatable" sub.
599  
600 =cut
601  
602 sub update {
603 my ($self, $class) = @_;
604 $self->validate_item(ref($class));
605 my %mods = map { $_ => 1 } $class->update_fields;
606 my $vars = $class->to_json();
607 $vars = { $class->singular => {map { $_ => $vars->{$_} } grep { exists $mods{$_} } keys(%$vars)} };
608  
609 my ($decoded, $response);
610 if (ref($class) =~ m/Asset/) {
611 my $url = $self->resolve_trailing_url(ref($class), "update", $class->associated_parent) . ".json";
612 ($decoded, $response) = $self->use_url($class->update_method, $url, $vars);
613 }
614 else {
615 ($decoded, $response) = $self->use_url($class->update_method, $self->resolve_trailing_url($class, "update", $class->associated_parent) . "/" . $class->id . ".json", $vars);
616 }
617  
618 my $element = $decoded->{$class->singular()};
619 if ($self->{_decode_entities}) {
620 my $object = ref($class)->from_json($element, $self);
621 $object->associated_parent($class->associated_parent);
622 return $object;
623 } else {
624 return $element;
625 }
626 }
627  
628 =head2 delete($self, $item)
629  
630 Deletes the item from the shopify store. Not all items are deletable, check the API docs, or grep this module's source code and look for the "deletable" sub.
631  
632 =cut
633  
634 sub delete {
635 my ($self, $class) = @_;
636 $self->validate_item(ref($class));
637 if (ref($class) =~ m/Asset/) {
638 my $url = $self->resolve_trailing_url(ref($class), "delete", $class->associated_parent) . ".json?asset[key]=" . $class->key;
639 $self->use_url($class->delete_method, $url);
640 }
641 else {
642 $self->use_url($class->delete_method, $self->resolve_trailing_url($class, "delete", $class->associated_parent) . "/" . $class->id . ".json");
643 }
644 return 1;
645 }
646  
647 # For simple things like activating, enabling, disabling, that are a simple post to a custom URL.
648 # Sometimes returns an object, sometimes returns a 1.
649 use List::Util qw(first);
650 sub custom_action {
651 my ($self, $object, $action) = @_;
652 die new WWW::Shopify::Exception("You can't $action " . $object->plural . ".") unless defined $object && first { $_ eq $action } $object->actions;
653 my $element;
654 my ($decoded, $response);
655 if ($object->can('id')) {
656 my $id = $object->id;
657 my $url = $self->resolve_trailing_url($object, $action, $object->associated_parent) . "/$id/$action.json";
658 ($decoded, $response) = $self->use_url('post', $url, {$object->singular() => $object->to_json});
659 return 1 if !$decoded;
660 $element = $decoded->{$object->singular()};
661 } else {
662 my $url = $self->resolve_trailing_url($object, $action, $object->associated_parent) . "/$action.json";
663 ($decoded, $response) = $self->use_url('post', $url, $object->to_json);
664 return 1 if !$decoded;
665 $element = $decoded->{$object->singular()};
666 }
667 if ($element) {
668 $object = ref($object)->from_json($element, $self);
669 return $object;
670 } else {
671 return $decoded;
672 }
673 }
674  
675 =head2 activate($self, $charge), disable($self, $discount), enable($self, $discount), open($self, $order), close($self, $order), cancel($self, $order)
676  
677 Special actions that do what they say.
678  
679 =cut
680  
681 sub adjust { return $_[0]->custom_action($_[1], "adjust"); }
682 sub connect { return $_[0]->custom_action($_[1], "connect"); }
683 sub set { return $_[0]->custom_action($_[1], "set"); }
684 sub activate { return $_[0]->custom_action($_[1], "activate"); }
685 sub disable { return $_[0]->custom_action($_[1], "disable"); }
686 sub enable { return $_[0]->custom_action($_[1], "enable"); }
687 sub open { return $_[0]->custom_action($_[1], "open"); }
688 sub close { return $_[0]->custom_action($_[1], "close"); }
689 sub cancel { return $_[0]->custom_action($_[1], "cancel"); }
690 sub approve { return $_[0]->custom_action($_[1], "approve"); }
691 sub remove { return $_[0]->custom_action($_[1], "remove"); }
692 sub spam { return $_[0]->custom_action($_[1], "spam"); }
693 sub not_spam { return $_[0]->custom_action($_[1], "not_spam"); }
694 sub complete { return $_[0]->custom_action($_[1], "complete"); }
695 sub account_activation_url { return $_[0]->custom_action($_[1], "account_activation_url"); }
696 sub order {
697 my ($self, $object, $hash) = @_;
698 die new WWW::Shopify::Exception("You can't order " . $object->plural . ".") unless defined $object && first { $_ eq "order" } $object->actions;
699 # Mainly for smart collections; no idea why Shopify decides to go against the grain and do something completely different for smart collections against literally everything else.
700 # It's a mystery.
701 my $url = $self->resolve_trailing_url($object, "order", $object->associated_parent) . "/" . $object->id . "/order.json?";
702 if ($hash->{products}) {
703 $url .= join("&", map { "products[]=" . (ref($_) ? $_->{id} : $_) } @{$hash->{products}});
704 }
705 if ($hash->{sort_order}) {
706 $url .= "&" if $url !~ m/\?$/;
707 $url .= "sort_order=" . $hash->{sort_order};
708 }
709 my ($decoded, $response) = $self->use_url('put', $url, {});
710 return 1;
711 }
712  
713  
714 sub is_valid { eval { $_[0]->get_shop; }; return undef if ($@); return 1; }
715 sub handleize {
716 my ($self, $handle) = @_;
717 $handle = $self if !ref($self);
718 $handle = lc($handle);
719 $handle =~ s/^\s+//;
720 $handle =~ s/\s+$//;
721 $handle =~ s/\s/-/g;
722 $handle =~ s/[^a-z0-9\-]//g;
723 $handle =~ s/\-+/-/g;
724 return $handle;
725 }
726  
727  
728 =head2 create_private_app()
729  
730 Automates a form submission to generate a private app. Returns a WWW::Shopify::Private with the appropriate credentials. Must be logged in.
731  
732 =cut
733  
734 use WWW::Shopify::Private;
735 use List::Util qw(first);
736 sub create_private_app {
737 my ($self) = @_;
738 my $app = $self->create(new WWW::Shopify::Model::APIClient({}));
739 my @permissions = $self->get_all("APIPermission");
740 my $permission = first { $_->api_client->api_key eq $app->api_key } @permissions;
741 return new WWW::Shopify::Private($self->shop_url, $app->api_key, $permission->access_token);
742 }
743  
744  
745 =head2 delete_private_app($private_api)
746  
747 Removes a private app. Must be logged in.
748  
749 =cut
750  
751 sub delete_private_app {
752 my ($self, $api) = @_;
753 my @apps = $self->get_all("APIPermission");
754 my $app = first { $_->api_client && $_->api_client->api_key eq $api->api_key } @apps;
755 die new WWW::Shopify::Exception("Can't find app with api key " . $api->api_key) unless $app;
756 return $self->delete(new WWW::Shopify::Model::APIClient({ id => $app->api_client->id }));
757 }
758  
759  
760 # Internal methods.
761 sub validate_item {
762 eval { die unless $_[1]; $_[1]->is_item; };
763 die new WWW::Shopify::Exception($_[1] . " is not an item.") if ($@);
764 die new WWW::Shopify::Exception($_[1] . " requires you to login with an admin account.") if ($_[1]->needs_login && !$_[1]->needs_plus) && !$_[0]->logged_in_admin;
765 }
766  
767  
768 =cut
769  
770 =head1 EXPORTED FUNCTIONS
771  
772 The functions below are exported as part of the package.
773  
774 =cut
775  
776 =head2 calc_webhook_signature($shared_secret, $request_body)
777  
778 Calculates the webhook_signature based off the shared secret and request body passed in.
779  
780 =cut
781  
782 =head2 verify_webhook($shared_secret, $request_body)
783  
784 Shopify webhook authentication. ALMOST the same as login authentication, but, of course, because this is shopify they've got a different system. 'Cause you know, one's not good enough.
785  
786 Follows this: http://wiki.shopify.com/Verifying_Webhooks.
787  
788 =cut
789  
790 use Exporter 'import';
791 our @EXPORT_OK = qw(verify_webhook verify_login verify_proxy calc_webhook_signature calc_login_signature calc_hmac_login_signature calc_proxy_signature handleize calc_jwt_signature);
792 use Digest::MD5 'md5_hex';
793 use Digest::SHA qw(hmac_sha256_hex hmac_sha256_base64 hmac_sha256);
794 use MIME::Base64 qw(encode_base64url);
795  
796 sub calc_webhook_signature {
797 my ($shared_secret, $request_body) = @_;
798 die new WWW::Shopify::Exception("Requires a shared secret.") unless $shared_secret;
799 my $calc_signature = hmac_sha256_base64((defined $request_body) ? $request_body : "", $shared_secret);
800 while (length($calc_signature) % 4) { $calc_signature .= '='; }
801 return $calc_signature;
802 }
803  
804  
805 sub verify_webhook {
806 my ($x_shopify_hmac_sha256, $request_body, $shared_secret) = @_;
807 return undef unless $x_shopify_hmac_sha256;
808 return $x_shopify_hmac_sha256 eq calc_webhook_signature($shared_secret, $request_body);
809 }
810  
811 sub calc_jwt_signature {
812 my ($shared_secret, $header_and_body) = @_;
813 return encode_base64url(hmac_sha256($header_and_body, $shared_secret));
814 }
815  
816 =head2 calc_login_signature($shared_secret, $%params)
817  
818 Calculates the MD5 login signature based on the shared secret and parmaeter hash passed in. This is deprecated.
819  
820 =cut
821  
822 =head2 calc_hmac_login_signature($shared_secret, $%params)
823  
824 Calculates the SHA256 login signature based on the shared secret and parmaeter hash passed in.
825  
826 =cut
827  
828 =head2 verify_login($shared_secret, $%params)
829  
830 Shopify app dashboard verification (when someone clicks Login on the app dashboard).
831  
832 This one was kinda random, 'cause they say it's like a webhook, but it's actually like legacy auth.
833  
834 Also, they don't have a code parameter. For whatever reason.
835  
836 =cut
837  
838 sub calc_login_signature {
839 my ($shared_secret, $params) = @_;
840 return md5_hex($shared_secret . join("", map { "$_=" . $params->{$_} } (sort(grep { $_ ne "signature" } keys(%$params)))));
841 }
842  
843 sub calc_hmac_login_signature {
844 my ($shared_secret, $params) = @_;
845 return hmac_sha256_hex(join("&", map {
846 my $key = $_ =~ s/\[\]//r;
847 (ref($params->{$_}) eq 'ARRAY' ? ($_ !~ m/\[\]$/ ? "$key=" . join(", ", @{$params->{$_}}) : "$key=[" . join(", ", map { "\"$_\"" } @{$params->{$_}}) . "]") : ("$_=" . $params->{$_}))
848 } (sort(grep { $_ ne "hmac" && $_ ne "signature" } keys(%$params)))), $shared_secret);
849 }
850  
851 sub verify_login {
852 my ($shared_secret, $params) = @_;
853 return undef unless $params->{hmac};
854 my $hmac = ref($params->{hmac}) eq 'ARRAY' ? $params->{hmac}->[0] : $params->{hmac};
855 return calc_hmac_login_signature($shared_secret, $params) eq $hmac;
856 }
857  
858 =head2 calc_proxy_signature($shared_secret, $%params)
859  
860 Based on shared secret/hash of parameters passed in, calculates the proxy signature.
861  
862 =cut
863  
864 =head2 verify_proxy($shared_secret, %$params)
865  
866 This is SLIGHTLY different from the above two. For, as far as I can tell, no reason.
867  
868 =cut
869  
870 sub calc_proxy_signature {
871 my ($shared_secret, $params) = @_;
872 return hmac_sha256_hex(join("", sort(map {
873 my $p = $params->{$_};
874 "$_=" . (ref($p) eq "ARRAY" ? join(",", @$p) : $p);
875 } (grep { $_ ne "signature" } keys(%$params)))), $shared_secret);
876 }
877  
878 sub verify_proxy {
879 my ($shared_secret, $params) = @_;
880 return undef unless $params->{signature};
881 my $signature = ref($params->{signature}) eq 'ARRAY' ? $params->{signature}->[0] : $params->{signature};
882 return calc_proxy_signature($shared_secret, $params) eq $signature;
883 }
884  
885 =head2 all_items($self)
886  
887 Returns a list of all publically available items on the store.
888  
889 =cut
890  
891 sub all_items {
892 my ($package) = @_;
893 return grep { $_ ne 'WWW::Shopify::Model::NestedItem' && $_ ne 'WWW::Shopify::Model::Item' && !$_->needs_login && (!$_->is_nested || !$_->included_in_parent) } findsubmod WWW::Shopify::Model;
894 }
895  
896 =head1 SEE ALSO
897  
898 L<WWW::Shopify::Public>, L<WWW::Shopify::Private>, L<WWW::Shopify::Test>, L<WWW::Shopify::Item>, L<WWW::Shopify::Common::DBIx>
899  
900 =head1 AUTHOR
901  
902 Adam Harrison (adamdharrison@gmail.com)
903  
904 =head1 LICENSE
905  
906 Copyright (C) 2020 Adam Harrison
907  
908 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
909  
910 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
911  
912 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
913  
914 =cut
915  
916 1;
« Shopify/Public.pm ↑ Summary