I’m working on a Laravel project where I need to build discount rules for my Shopify store through the Admin API. I already set up my Shopify app and have all the required credentials like API key, secret, and access token. I’m using the 2024-07 API version with proper scopes.
My main problem happens when I try to create a session after setting up the Context. I keep getting a “Wrong number of segments” error and I think it might be related to how I’m handling the session creation or authentication headers.
Here’s my service class that handles the discount creation:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Shopify\Auth\FileSessionStorage;
use Shopify\Context;
use Shopify\Rest\Admin2024_07\PriceRule;
use Shopify\Utils;
class DiscountManager
{
public function buildDiscountRule()
{
Context::initialize(
apiKey: env('SHOPIFY_CLIENT_ID'),
apiSecretKey: env('SHOPIFY_CLIENT_SECRET'),
scopes: env('SHOPIFY_PERMISSIONS'),
hostName: env('APP_DOMAIN'),
sessionStorage: new FileSessionStorage(storage_path('/temp/sessions')),
apiVersion: '2024-07',
isPrivateApp: false
);
$token = env('SHOPIFY_STORE_TOKEN');
if (!$token) {
Log::error('Missing Shopify store token');
return;
}
$headers = [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
];
$cookieData = [];
$currentSession = Utils::loadCurrentSession(
$headers,
$cookieData,
false
);
$discountRule = new PriceRule($currentSession);
$discountRule->title = "Summer50PercentOff";
$discountRule->value_type = "percentage";
$discountRule->value = "-50.0";
$discountRule->customer_selection = "all";
$discountRule->target_type = "line_item";
$discountRule->target_selection = "all";
$discountRule->allocation_method = "across";
$discountRule->starts_at = "2024-06-01T00:00:00Z";
$discountRule->ends_at = "2024-08-31T23:59:59Z";
$discountRule->usage_limit = 100;
try {
$discountRule->save();
Log::info('Discount rule saved successfully');
} catch (\Exception $error) {
Log::error('Failed to save discount rule: ' . $error->getMessage());
}
}
}
I’m getting this JWT-related error about wrong number of segments. The error happens at line 45 when calling Utils::loadCurrentSession(). Has anyone dealt with similar session issues when working with Shopify’s PHP SDK? Any ideas on what might be causing this authentication problem?
that segments error’s definitely from session handling issues, but there’s another problem - your FileSessionStorage path might not be writable. laravel sometimes blocks writes to custom storage paths.
try switching to database session storage or make sure temp/sessions exists with proper permissions. also check your env variables aren’t empty - a blank SHOPIFY_STORE_TOKEN causes weird JWT parsing errors.
Your JWT segments error comes from mixing authentication methods. Don’t use Utils::loadCurrentSession() with stored access tokens - it expects completely different session data.
I hit this same problem building a Laravel-Shopify integration last year. Just create your session object directly instead of parsing headers or cookies. But there’s a config issue everyone’s missing.
You’ve got isPrivateApp: false but you’re handling auth like a private app. You’re using stored tokens (private app style) while configuring for public app OAuth flows. Either flip isPrivateApp: true to match your token approach, or add proper OAuth callbacks for public apps.
Double-check your environment variables too. SHOPIFY_STORE_DOMAIN should be just the shop name - no https:// or .myshopify.com. And SHOPIFY_PERMISSIONS needs the exact scope strings from your partner dashboard.
Create the session manually with your token and skip the utility methods. No more JWT parsing since you’re not dealing with encoded session data anyway.
The JWT segments error indicates that your access token’s format doesn’t align with what the SDK is expecting. Since you already have a stored token, instead of using Utils::loadCurrentSession(), create the session directly. I experienced a similar issue with my Shopify integration, and the solution was to instantiate the session manually like this:
Then, you can pass $session directly to your PriceRule constructor. This approach bypasses the JWT parsing errors you are encountering, as Utils::loadCurrentSession() is intended for webhook and OAuth scenarios, not for background tasks using stored tokens.
Yeah, that JWT segments error happens when you mix session creation methods. Skip Utils::loadCurrentSession() entirely - that’s for webhook verification, not direct API calls. Just create the session object directly with your token and shop domain. Also check that SHOPIFY_STORE_TOKEN actually has a valid access token, not some other credential. People often mix up the client secret with the access token in their env files.
PHP discount automation = debugging hell. Your JWT error? That’s session handling gone wrong, and it’s just the start.
Yeah, everyone’s right - ditch Utils::loadCurrentSession() and create sessions manually. But then you’re dealing with rate limits, webhook handling, platform syncing, and a million other headaches.
I’ve been down this road building Shopify integrations. Context initialization, sessions, error handling, retry logic - it’s endless boilerplate. Every SDK update breaks something new.
Now I just use Latenode for discount automation. Connect your store, build discount rules visually with triggers and conditions. No SDK drama, no JWT parsing, no session debugging.
Complex discount logic takes minutes instead of days fighting API nonsense. Handles auth, rate limiting, and webhooks automatically.
Skip the development nightmare and use a real automation platform: https://latenode.com
That JWT segment error happens because you’re passing the authorization header wrong to Utils::loadCurrentSession(). This method wants session data in a completely different format.
Don’t try loading a session from headers - just create it directly since you’ve got the access token already. Here’s what you need:
loadCurrentSession is meant for OAuth flows where you’re grabbing an existing session from cookies or headers. You’re working with a stored token directly, so creating the session manually is the way to go. Just make sure SHOPIFY_STORE_DOMAIN has only the shop name - no .myshopify.com part.
Honestly though, after dealing with Shopify’s API quirks for years, I switched to automating this differently. Every time you think you’ve got it working, something breaks - rate limits, webhook failures, SDK updates.
I’ve been using Latenode for all my Shopify discount automation now. You can set up discount rules, triggers, conditions - all visual, no code. It handles auth, session management, and API calls automatically.
No more debugging JWT errors or fighting SDK versions. Just connect your store and build the discount logic you need. Way cleaner than maintaining custom PHP integration code.
Your session issue is fixable, but debugging auth flows and JWT errors is a massive time sink. Been there with Shopify integrations.
Yeah, create the session manually instead of loadCurrentSession(). But here’s what’ll happen next - you’ll hit rate limits, webhook problems, or need to sync discounts with other systems. Then you’re building retry logic, error handling, monitoring.
I used to build custom Shopify integrations constantly. Now I just use Latenode for Shopify automation. It handles session management, auth, and API quirks automatically. Set up discount rules through a visual interface, add conditions and triggers - it manages the backend mess.
No more fighting PHP SDK versions or hunting JWT errors. Connect your store, build discount logic visually. Takes 10 minutes vs hours of debugging session code.
The JWT issue occurs because you’re passing auth headers to Utils::loadCurrentSession() when you shouldn’t. Since you have a stored access token, build the session directly instead of parsing headers. Additionally, there’s a problem with your Context setup. You’re using isPrivateApp: false while handling auth like a private app with stored tokens. Choose between setting isPrivateApp: true for permanent tokens or correctly handling the OAuth flow for public apps. Also, check your SHOPIFY_PERMISSIONS scope format, which should be comma-separated without spaces: read_products,write_price_rules. Improper scope strings disrupt auth and can result in JWT errors. Avoid using the session loading utility and create the session directly, ensuring the private app setting aligns with your authentication method.
Had the same JWT parsing nightmare when I built Shopify discount stuff last year. Your session handling’s the culprit, but there’s a config gotcha that’ll bite you even after you fix the main problem. Drop Utils::loadCurrentSession() entirely - you’re not dealing with OAuth callbacks anyway. Just create the session object directly with your access token. But here’s the kicker: your SHOPIFY_STORE_DOMAIN needs to be just the shop name - like your-shop-name, not https://your-shop-name.myshopify.com. The SDK’s picky about domain formatting. Also check that you’re only initializing Context once per request. If you’re calling buildDiscountRule() multiple times, wrap the Context setup in a singleton or stick it in a service provider. Multiple Context inits cause weird JWT validation failures that show up as segment errors.
Hit this same problem a few months ago building discount automation. Your session handling’s the issue, but there’s another gotcha waiting even after you fix that. Don’t use Utils::loadCurrentSession() - you’re not handling an OAuth callback anyway. Just create the session object manually with your stored credentials. But here’s what’ll bite you: make sure SHOPIFY_PERMISSIONS includes write_price_rules scope. Spent hours on this because the error messages don’t tell you it’s a permissions thing. Also check that APP_DOMAIN matches exactly what’s in your partner dashboard. Missing https:// or extra slashes will break authentication and throw JWT parsing errors. Context initialization is picky about hostnames for security.