getAppSecret example

/** @var AppEntity|null $app */
        $app = $this->appRepository->search($criteria$context)->first();
        if ($app === null) {
            throw new AppByNameNotFoundException($appName);
        }

        $shopUrl = EnvironmentHelper::getVariable('APP_URL');
        if (!\is_string($shopUrl)) {
            throw new MissingShopUrlException();
        }

        $appSecret = $app->getAppSecret();
        if ($appSecret === null) {
            throw new MissingAppSecretException();
        }

        $targetUrl = $requestDataBag->get('url');
        $targetHost = \parse_url((string) $targetUrl, \PHP_URL_HOST);
        $allowedHosts = $app->getAllowedHosts() ?? [];
        if (!$targetHost || !\in_array($targetHost$allowedHosts, true)) {
            throw new UnallowedHostException($targetUrl$allowedHosts$app->getName());
        }

        
/** * @return array{source: string}|null */
    private function formatMainModule(AppEntity $app, Context $context): ?array
    {
        if ($app->getMainModule() === null) {
            return null;
        }

        $source = $app->getMainModule()['source'] ?? '';
        $secret = $app->getAppSecret() ?? '';

        return [
            'source' => $this->sign($source$secret$context),
        ];
    }

    /** * @return array<string, string|null> */
    private function mapTranslatedLabels(AppEntity $app): array
    {
        
$encoded = $this->helper->encode($payload);
        $jsonPayload = json_encode($encoded, \JSON_THROW_ON_ERROR);

        if (!$jsonPayload) {
            if ($payload instanceof PaymentPayloadInterface) {
                throw PaymentException::asyncProcessInterrupted($payload->getOrderTransaction()->getId(), \sprintf('Empty payload, got: %s', var_export($jsonPayload, true)));
            }

            throw PaymentException::validatePreparedPaymentInterrupted(\sprintf('Empty payload, got: %s', var_export($jsonPayload, true)));
        }

        $secret = $app->getAppSecret();
        if ($secret === null) {
            throw AppException::registrationFailed($app->getName(), 'App secret is missing');
        }

        return [
            AuthMiddleware::APP_REQUEST_CONTEXT => $context,
            AuthMiddleware::APP_REQUEST_TYPE => [
                AuthMiddleware::APP_SECRET => $secret,
                AuthMiddleware::VALIDATED_RESPONSE => true,
            ],
            'headers' => [
                
static::assertNotEmpty($registrationRequest->getHeaderLine('sw-version'));
        static::assertNotEmpty($registrationRequest->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertNotEmpty($registrationRequest->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));

        $secret = $setup->getSecret();
        static::assertNotNull($secret);

        $this->assertRequestIsSigned($registrationRequest$secret);

        $app = $this->fetchApp($id);

        static::assertEquals(TestAppServer::APP_SECRET, $app->getAppSecret());

        static::assertEquals(2, $this->getRequestCount());

        $confirmationReq = $this->getPastRequest(1);
        static::assertEquals('POST', $confirmationReq->getMethod());

        $postBody = \json_decode($confirmationReq->getBody()->getContents(), true, 512, \JSON_THROW_ON_ERROR);
        static::assertEquals($secretAccessKey$postBody['secretKey']);

        $integration = $app->getIntegration();
        static::assertNotNull($integration);
        
$response = (new AsyncFinalizeResponse())->assign([
            'status' => StateMachineTransitionActions::ACTION_AUTHORIZE,
        ]);
        $this->appendNewResponse($this->signResponse($response->jsonSerialize()));

        $this->paymentService->finalizeTransaction($data['token']new \Symfony\Component\HttpFoundation\Request()$this->getSalesChannelContext($data['paymentMethodId']));

        /** @var Request $request */
        $request = $this->getLastRequest();
        $body = $request->getBody()->getContents();

        $appSecret = $this->app->getAppSecret();
        static::assertNotNull($appSecret);

        static::assertTrue($request->hasHeader('shopware-shop-signature'));
        static::assertSame(\hash_hmac('sha256', $body$appSecret)$request->getHeaderLine('shopware-shop-signature'));
        static::assertNotEmpty($request->getHeaderLine('sw-version'));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertSame('POST', $request->getMethod());
        static::assertJson($body);
        $content = json_decode($body, true, 512, \JSON_THROW_ON_ERROR);
        static::assertIsArray($content);
        
if ($event instanceof AppFlowActionEvent) {
                $headers = array_merge($headers$event->getWebhookHeaders());
            }

            $request = new Request(
                'POST',
                $webhook->getUrl(),
                $headers,
                $jsonPayload
            );

            if ($webhook->getApp() !== null && $webhook->getApp()->getAppSecret() !== null) {
                $request = $request->withHeader(
                    RequestSigner::SHOPWARE_SHOP_SIGNATURE,
                    (new RequestSigner())->signPayload($jsonPayload$webhook->getApp()->getAppSecret())
                );
            }

            $requests[] = $request;
        }

        if (\count($requests) > 0) {
            $pool = new Pool($this->guzzle, $requests);
            
$this->updateMetadata($metadata$context);

        $app = $this->loadApp($id$context);

        $this->updateCustomEntities($app->getId()$app->getPath()$manifest);

        $this->permissionPersister->updatePrivileges($manifest->getPermissions()$roleId);

        // If the app has no secret yet, but now specifies setup data we do a registration to get an app secret         // this mostly happens during install, but may happen in the update case if the app previously worked without an external server         if (!$app->getAppSecret() && $manifest->getSetup()) {
            try {
                $this->registrationService->registerApp($manifest$id$secretAccessKey$context);
            } catch (AppRegistrationException $e) {
                $this->removeAppAndRole($app$context);

                throw $e;
            }
        }

        // Refetch app to get secret after registration         $app = $this->loadApp($id$context);

        
'status' => 'complete',
        ]);

        $this->appendNewResponse($this->signResponse($response->jsonSerialize()));

        $this->paymentRefundProcessor->processRefund($refundId$salesChannelContext->getContext());

        /** @var Request $request */
        $request = $this->getLastRequest();
        $body = $request->getBody()->getContents();

        $appSecret = $this->app->getAppSecret();
        static::assertNotNull($appSecret);

        static::assertTrue($request->hasHeader('shopware-shop-signature'));
        static::assertSame(hash_hmac('sha256', $body$appSecret)$request->getHeaderLine('shopware-shop-signature'));
        static::assertNotEmpty($request->getHeaderLine('sw-version'));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));
        static::assertSame('POST', $request->getMethod());
        static::assertJson($body);
        $content = json_decode($body, true, 512, \JSON_THROW_ON_ERROR);
        static::assertArrayHasKey('source', $content);
        
$response = ValidateResponse::create(null, ['preOrderPayment' => ['test' => 'response']]);
        $this->appendNewResponse($this->signResponse($response->jsonSerialize()));

        $returnValue = $this->preparedPaymentService->handlePreOrderPayment($cartnew RequestDataBag()$salesChannelContext);
        static::assertInstanceOf(ArrayStruct::class$returnValue);
        static::assertSame(['test' => 'response']$returnValue->all());

        /** @var Request $request */
        $request = $this->getLastRequest();
        $body = $request->getBody()->getContents();

        $appSecret = $this->app->getAppSecret();
        static::assertNotNull($appSecret);

        static::assertTrue($request->hasHeader('shopware-shop-signature'));
        static::assertSame(hash_hmac('sha256', $body$appSecret)$request->getHeaderLine('shopware-shop-signature'));
        static::assertNotEmpty($request->getHeaderLine('sw-version'));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));
        static::assertSame('POST', $request->getMethod());
        static::assertJson($body);
        $content = json_decode($body, true, 512, \JSON_THROW_ON_ERROR);
        static::assertIsArray($content);
        
static::assertEquals('POST', $request->getMethod());
        $body = $request->getBody()->getContents();
        static::assertJson($body);

        $result = $this->validateRequestSchema($body);

        $message = $this->parseSchemaErrors($result);

        static::assertTrue($result->isValid()$message);

        $appSecret = $action->getAppSecret();
        static::assertNotNull($appSecret);

        static::assertEquals(
            hash_hmac('sha256', $body$appSecret),
            $request->getHeaderLine('shopware-shop-signature')
        );

        static::assertNotEmpty($request->getHeaderLine('sw-version'));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));
    }

    
if ($actionButton === null) {
            throw new ActionNotFoundException();
        }

        try {
            $shopId = $this->shopIdProvider->getShopId();
        } catch (AppUrlChangeDetectedException) {
            throw new ActionNotFoundException();
        }

        /** @var string $secret */
        $secret = $actionButton->getApp()->getAppSecret();

        return new AppAction(
            $actionButton->getUrl(),
            $this->url,
            $actionButton->getApp()->getVersion(),
            $actionButton->getEntity(),
            $actionButton->getAction(),
            $ids,
            $secret,
            $shopId,
            $actionId
        );
'foo' => 'bar',
            'source' => [
                'url' => 'https://example.com',
                'appVersion' => $webhookEntity->getApp()?->getVersion(),
                'shopId' => 'foobar',
                'action' => $event->getName(),
            ],
        ]$payload);

        static::assertEquals($message->getLanguageId(), Defaults::LANGUAGE_SYSTEM);
        static::assertEquals($message->getAppId()$webhookEntity->getApp()?->getId());
        static::assertEquals($message->getSecret()$webhookEntity->getApp()?->getAppSecret());
        static::assertEquals($message->getShopwareVersion(), '0.0.0');
        static::assertEquals($message->getUrl(), 'https://foo.bar');
        static::assertEquals($message->getWebhookId()$webhookEntity->getId());
    }

    private function getWebhookDispatcher(bool $isAdminWorkerEnabled): WebhookDispatcher
    {
        return new WebhookDispatcher(
            $this->dispatcher,
            $this->connection,
            $this->client,
            
$encoded = $this->encode($payload);
        $jsonPayload = json_encode($encoded, \JSON_THROW_ON_ERROR);

        if (!$jsonPayload) {
            if ($payload instanceof PaymentPayloadInterface) {
                throw PaymentException::asyncProcessInterrupted($payload->getOrderTransaction()->getId(), \sprintf('Empty payload, got: %s', var_export($jsonPayload, true)));
            }

            throw PaymentException::validatePreparedPaymentInterrupted(\sprintf('Empty payload, got: %s', var_export($jsonPayload, true)));
        }

        $secret = $app->getAppSecret();
        if ($secret === null) {
            throw AppException::registrationFailed($app->getName(), 'App secret is missing');
        }

        return [
            AuthMiddleware::APP_REQUEST_CONTEXT => $context,
            AuthMiddleware::APP_REQUEST_TYPE => [
                AuthMiddleware::APP_SECRET => $secret,
                AuthMiddleware::VALIDATED_RESPONSE => true,
            ],
            'headers' => [
                
 catch (AppUrlChangeDetectedException $e) {
            throw AppException::actionButtonProcessException($action->getActionId()$e->getMessage()$e);
        }

        $payload = $action->asPayload();
        $payload['meta'] = [
            'timestamp' => (new \DateTime())->getTimestamp(),
            'reference' => Uuid::randomHex(),
            'language' => $context->getLanguageId(),
        ];

        $appSecret = $action->getAppSecret();

        if (!$appSecret || str_starts_with($action->getTargetUrl(), '/')) {
            $content = $this->executeSubRequest($action);
        } else {
            $content = $this->executeHttpRequest($action$context$payload$appSecret);
        }

        if (empty($content)) {
            return new JsonResponse();
        }

        

    }

    /** * @param array<int|string, mixed> $content */
    protected function signResponse(array $content): ResponseInterface
    {
        $json = \json_encode($content, \JSON_THROW_ON_ERROR);
        static::assertNotFalse($json);

        $secret = $this->app->getAppSecret();
        static::assertNotNull($secret);

        $hmac = \hash_hmac('sha256', $json$secret);

        return new Response(
            200,
            [
                'shopware-app-signature' => $hmac,
            ],
            $json
        );
    }
Home | Imprint | This part of the site doesn't use cookies.