Skip to content

Commit

Permalink
Add callback functions backend processing for Google Pay
Browse files Browse the repository at this point in the history
Error hanling to be added next

ISSUE: AD4CR22I-14
  • Loading branch information
filipkojic committed Dec 29, 2024
1 parent a6571ec commit 739c875
Show file tree
Hide file tree
Showing 7 changed files with 397 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,43 @@ public function getExpressCheckoutConfig(
): JsonResponse {
$productId = $request->request->get('productId');
$quantity = (int)$request->request->get('quantity');
$newAddress = $request->request->get('newAddress');
$newShipping = $request->request->get('newShippingMethod');

if ($newAddress === null) {
$newAddress = [];
}

if ($newShipping === null) {
$newShipping = [];
}

return new JsonResponse($this->expressCheckoutService->getExpressCheckoutConfigOnProductPage(
$productId,
$quantity,
$salesChannelContext
$salesChannelContext,
$newAddress,
$newShipping
));
}
}

/**
* Creates a cart with the provided product and calculates it with the resolved shipping location and method.
*
* @param string $productId The ID of the product.
* @param int $quantity The quantity of the product.
* @param SalesChannelContext $salesChannelContext The current sales channel context.
* @param array $newAddress Optional new address details.
* @param array $newShipping Optional new shipping method details.
* @return array The cart, shipping methods, selected shipping method, and payment methods.
*/
public function createCart(
string $productId,
int $quantity,
SalesChannelContext $salesChannelContext,
array $newAddress = [],
array $newShipping = []
): array {
return $this->expressCheckoutService->createCart($productId, $quantity, $salesChannelContext, $newAddress, $newShipping);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,43 +27,149 @@ export default class ExpressCheckoutPlugin extends Plugin {
init() {
this._client = new HttpClient();
this.paymentMethodInstance = null;
const userLoggedIn = adyenExpressCheckoutOptions.userLoggedIn === "1";

const userLoggedIn = adyenExpressCheckoutOptions.userLoggedIn === "true";

let onPaymentDataChanged = (intermediatePaymentData) => {
console.log("onPaymentDataChanged triggered", intermediatePaymentData);
return new Promise(async resolve => {
const { callbackTrigger, shippingAddress, shippingOptionData } = intermediatePaymentData;
const paymentDataRequestUpdate = {};

if (callbackTrigger === 'INITIALIZE' || callbackTrigger === 'SHIPPING_ADDRESS') {
console.log("ADDRESS trigger");

const extraData = {};

if (shippingAddress) {
extraData.newAddress = shippingAddress;
}

const response = await this.fetchExpressCheckoutConfig(adyenExpressCheckoutOptions.expressCheckoutConfigUrl, extraData);

let shippingMethodsArray = response.shippingMethodsResponse;

paymentDataRequestUpdate.newShippingOptionParameters = {
defaultSelectedOptionId: shippingMethodsArray[0].id,
shippingOptions: shippingMethodsArray
};

paymentDataRequestUpdate.newTransactionInfo = {
currencyCode: response.currency,
totalPriceStatus: "FINAL",
totalPrice: (parseInt(response.amount) / 100).toString(),
totalPriceLabel: "Total",
countryCode: response.countryCode,
};
}

if (callbackTrigger === 'SHIPPING_OPTION') {
console.log("SHIPPING trigger")

const extraData = {};

if (shippingAddress) {
extraData.newAddress = shippingAddress;
}

if (shippingOptionData) {
extraData.newShippingMethod = shippingOptionData;
}

const response = await this.fetchExpressCheckoutConfig(adyenExpressCheckoutOptions.expressCheckoutConfigUrl, extraData);

paymentDataRequestUpdate.newTransactionInfo = {
currencyCode: response.currency,
totalPriceStatus: "FINAL",
totalPrice: (parseInt(response.amount) / 100).toString(),
totalPriceLabel: "Total",
countryCode: response.countryCode,
};
}

resolve(paymentDataRequestUpdate);
});
};

let onPaymentAuthorized = (intermediatePaymentData) => {
console.log("onPaymentAuthorized triggered", intermediatePaymentData);
return new Promise(resolve => {
resolve({transactionState: "SUCCESS",});
});
};

this.paymentMethodSpecificConfig = {
"paywithgoogle": {
onClick: (resolve, reject) => {
console.log("Google Pay button clicked!");
console.log(userLoggedIn)
resolve();
},
isExpress: true,
callBackIntents: adyenExpressCheckoutOptions.userLoggedIn === "" ? ['SHIPPING_ADDRESS', 'PAYMENT_AUTHORIZATION'] : [],
shippingAddressRequired: adyenExpressCheckoutOptions.userLoggedIn === "",
emailRequired: adyenExpressCheckoutOptions.userLoggedIn === "",
callbackIntents: !userLoggedIn ? ['SHIPPING_ADDRESS', 'PAYMENT_AUTHORIZATION', 'SHIPPING_OPTION'] : [],
shippingAddressRequired: !userLoggedIn ,
emailRequired: !userLoggedIn ,
shippingAddressParameters: {
allowedCountryCodes: [],
phoneNumberRequired: true
},
shippingOptionRequired: false,
shippingOptionRequired: !userLoggedIn,
buttonSizeMode: "fill",
onAuthorized: paymentData => {
console.log('Shopper details', paymentData);
},
buttonColor : "white"
buttonColor : "white",
paymentDataCallbacks: !userLoggedIn ?
{
onPaymentDataChanged: onPaymentDataChanged,
onPaymentAuthorized: onPaymentAuthorized
} :
{}
},
"googlepay": {},
"paypal": {},
"applepay": {}
};
this.quantityInput = document.querySelector('.product-detail-quantity-input');
//this.quantityInput = document.querySelector('.product-detail-quantity-input'); - shopware 6.5
this.quantityInput = document.querySelector('.product-detail-quantity-select');
this.listenOnQuantityChange();

this.mountExpressCheckoutComponents({
countryCode: adyenExpressCheckoutOptions.countryCode,
amount: adyenExpressCheckoutOptions.amount,
currency: adyenExpressCheckoutOptions.currency,
paymentMethodsResponse: JSON.parse(adyenExpressCheckoutOptions.paymentMethodsResponse),
// shippingMethodsResponse: adyenExpressCheckoutOptions.paymentMethodsResponse,
});

}

async fetchExpressCheckoutConfig(url, extraData = {}) {
const productMeta = document.querySelector('meta[itemprop="productID"]');
const productId = productMeta ? productMeta.content : '-1';

return new Promise((resolve, reject) => {
this._client.post(
url,
JSON.stringify({
quantity: this.quantityInput ? this.quantityInput.value : -1,
productId: productId,
...extraData
}),
(response) => {
try {
const parsedResponse = JSON.parse(response);
console.log("Controller Response:", parsedResponse);
resolve(parsedResponse);
} catch (error) {
console.error("Failed to parse response:", error);
reject(error);
}
}
);
});
}

mountExpressCheckoutComponents(data) {
if (!document.getElementById('adyen-express-checkout')) {
return;
Expand Down Expand Up @@ -112,13 +218,17 @@ export default class ExpressCheckoutPlugin extends Plugin {
},
paymentMethodsResponse: data.paymentMethodsResponse,
onAdditionalDetails: this.handleOnAdditionalDetails.bind(this),
onSubmit: function (state, component) {
console.log("on submit funkcija")
}
};

return Promise.resolve(await AdyenCheckout(ADYEN_EXPRESS_CHECKOUT_CONFIG));
}


handleOnAdditionalDetails(state) {
console.log("aasdasdasdad")
this._client.post(
`${adyenExpressCheckoutOptions.paymentDetailsUrl}`,
JSON.stringify({orderId: this.orderId, stateData: JSON.stringify(state.data)}),
Expand Down Expand Up @@ -150,20 +260,6 @@ export default class ExpressCheckoutPlugin extends Plugin {
);
});
}
// this.quantityInput?.addEventListener('change', (event) => {
// const newQuantity = event.target.value;
// const productMeta = document.querySelector('meta[itemprop="productID"]');
// const productId = productMeta ? productMeta.content : '-1';
// this._client.post(
// adyenExpressCheckoutOptions.expressCheckoutConfigUrl,
// JSON.stringify({
// quantity: newQuantity,
// productId: productId
// }),
// this.afterQuantityUpdated.bind(this)
// );
//
// });
}

afterQuantityUpdated(response){
Expand All @@ -179,4 +275,4 @@ export default class ExpressCheckoutPlugin extends Plugin {
window.location.reload();
}
}
}
}
3 changes: 2 additions & 1 deletion src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
<service id="Adyen\Shopware\Service\ExpressCheckoutService" autowire="true">
<argument type="service" id="Shopware\Core\Checkout\Cart\SalesChannel\CartService"/>
<argument type="service" id="country.repository"/>
<argument type="service" id="shipping_method.repository"/>
<argument type="service" id="Adyen\Shopware\Service\PaymentMethodsService"/>
<argument type="service" id="Adyen\Shopware\Util\Currency"/>
</service>
Expand Down Expand Up @@ -115,4 +116,4 @@
id="Adyen\Shopware\Framework\Cookie\AdyenCookieProvider.inner"/>
</service>
</services>
</container>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
data-currency="{{ adyenFrontendData.currency }}"
data-payment-methods-response="{{ adyenFrontendData.paymentMethodsResponse }}",
data-user-logged-in="{{ adyenFrontendData.userLoggedIn }}"
data-shipping-methods-response="{{ adyenFrontendData.shippingMethodsResponse }}"
></div>
{% set adyenExpressCheckoutPaymentTypes = ['applepay', 'paywithgoogle', 'paypal'] %}
{% for adyenPaymentMethodType in adyenExpressCheckoutPaymentTypes %}
Expand Down
Loading

0 comments on commit 739c875

Please sign in to comment.