Skip to content

Commit

Permalink
Update Giving sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Kwok-he-Chu committed Sep 28, 2023
1 parent c7547c6 commit 6cbaf0c
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 57 deletions.
2 changes: 2 additions & 0 deletions giving-example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ First make a test payment using one of our test card numbers, so you can see the

![Giving demo](src/main/resources/static/images/donations.gif)

> **Note**: You need to have donations [enabled in your Customer Area](https://docs.adyen.com/online-payments/donations/testing/#step-1-enable-the-donation-token-in-your-api-response) in order to receive the `DonationToken`.
## Supported Integrations

The amount of payment methods supported for donations is limited. In this demo, you will find a use case centered around the use of cards.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OnlinePaymentsApplication {
private static final Logger log = LoggerFactory.getLogger(OnlinePaymentsApplication.class);
public class GivingApplication {
private static final Logger log = LoggerFactory.getLogger(GivingApplication.class);

@Autowired
private ApplicationProperty applicationProperty;

public static void main(String[] args) {
SpringApplication.run(OnlinePaymentsApplication.class, args);
SpringApplication.run(GivingApplication.class, args);
}

@PostConstruct
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.adyen.service.checkout.PaymentsApi;
import com.adyen.service.exception.ApiException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
Expand All @@ -32,6 +33,10 @@ public class CheckoutResource {

private final PaymentsApi paymentsApi;

private final String donationToken = "DonationToken";

private final String paymentOriginalPspReference = "PaymentOriginalPspReference";

public CheckoutResource(ApplicationProperty applicationProperty) {

this.applicationProperty = applicationProperty;
Expand All @@ -54,15 +59,26 @@ public CheckoutResource(ApplicationProperty applicationProperty) {
* @throws ApiException from Adyen API.
*/
@PostMapping("/donations")
public ResponseEntity<DonationPaymentResponse> donations(@RequestParam String donationToken, @RequestParam String pspReference, @RequestBody Amount body, @RequestHeader String host, HttpServletRequest request) throws IOException, ApiException {
var decodedDonationToken = URLDecoder.decode(donationToken.replace("+", "%2B"), StandardCharsets.UTF_8).replace("%2B", "+");

public ResponseEntity<DonationPaymentResponse> donations(@RequestBody Amount body, @RequestHeader String host, HttpServletRequest request) throws IOException, ApiException {
DonationPaymentRequest donationRequest = new DonationPaymentRequest();
HttpSession session = request.getSession();
String pspReference = session.getAttribute(paymentOriginalPspReference).toString();
String token = session.getAttribute(donationToken).toString();

if (pspReference == null) {
log.info("Could not find the PspReference in the stored session.");
return ResponseEntity.badRequest().build();
}

if (token == null) {
log.info("Could not find the DonationToken in the stored session.");
return ResponseEntity.badRequest().build();
}

donationRequest.amount(body);
donationRequest.reference(UUID.randomUUID().toString());
donationRequest.setPaymentMethod(new CheckoutPaymentMethod(new CardDetails()));
donationRequest.setDonationToken(decodedDonationToken);
donationRequest.setDonationToken(token);
donationRequest.donationOriginalPspReference(pspReference);
donationRequest.setDonationAccount(this.applicationProperty.getDonationMerchantAccount());
donationRequest.returnUrl(request.getScheme() + "://" + host);
Expand Down Expand Up @@ -133,6 +149,16 @@ public ResponseEntity<PaymentResponse> payments(@RequestHeader String host, @Req

log.info("REST request to make Adyen payment {}", paymentRequest);
var response = paymentsApi.payments(paymentRequest);

var session = request.getSession();
session.setAttribute(paymentOriginalPspReference, response.getPspReference());

if (response.getDonationToken() == null) {
log.error("The payments endpoint did not return a donationToken, please enable this in your Customer Area. See README.");
}
else {
session.setAttribute(donationToken, response.getDonationToken());
}
return ResponseEntity.ok()
.body(response);
}
Expand Down
40 changes: 16 additions & 24 deletions giving-example/src/main/resources/static/adyenGiving.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ async function callServer(url, data) {
return await res.json();
}

async function handleDonation(donationToken, pspReference, amount) {
async function handleDonation(amount) {
try {
const res = await callServer(`/api/donations?donationToken=${encodeURIComponent(donationToken)}&pspReference=${pspReference}`, amount);
console.log(amount);
const res = await callServer(`/api/donations`, amount);

switch (res.status) {
case "completed":
Expand All @@ -28,18 +29,13 @@ async function handleDonation(donationToken, pspReference, amount) {
console.error(error);
alert("Error occurred. Look at console for details");
}


}

async function startGiving() {

const checkout= await AdyenCheckout(
{
clientKey,
environment: "test",
}
);
const checkout= await AdyenCheckout({
clientKey,
environment: "test",
});

const donationConfig = {
amounts: {
Expand All @@ -60,25 +56,21 @@ async function startGiving() {
onDonate: (state, component) => {
if(state.isValid) {
console.log("Initiating donation");
let donationToken = sessionStorage.getItem("donationToken");
let pspReference = sessionStorage.getItem("pspReference");

if(!donationToken || !pspReference) {
console.log("No token or pspReference found, can't donate");
}
else{
handleDonation(donationToken, pspReference, state.data.amount);
}
handleDonation(state.data.amount);
}

},
onCancel: (result, component) => {
console.log("Donation cancelled");
document.getElementById( 'donation-container' ).style.display = 'none';
console.log(result);
document.getElementById('donation-container').style.display = 'none';
}
};

checkout.create('donation', donationConfig).mount('#donation-container');
try {
checkout.create('donation', donationConfig).mount('#donation-container');
} catch (ex) {
console.warn(ex);
}
}

startGiving();
startGiving();
19 changes: 1 addition & 18 deletions giving-example/src/main/resources/static/adyenImplementation.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,6 @@ async function initCheckout() {
value: 10000,
currency: "EUR",
},
},
paypal: {
amount: {
value: 10000,
currency: "USD",
},
environment: "test", // Change this to "live" when you're ready to accept live PayPal payments
countryCode: "US", // Only needed for test. This will be automatically retrieved when you are in production.
onCancel: (data, component) => {
component.setStatus('ready');
},
}
},
onSubmit: (state, component) => {
Expand All @@ -58,12 +47,6 @@ async function initCheckout() {
async function handleSubmission(state, component, url) {
try {
const res = await callServer(url, state.data);
if(res.donationToken){
// Depending on how you are handling the donation, you may want to store the token and pspReference, reuse the checkout instance, or store the data in the backend session.
console.log("Caching donationToken and pspReference");
sessionStorage.setItem("donationToken", res.donationToken);
sessionStorage.setItem("pspReference", res.pspReference);
}
handleServerResponse(res, component);
} catch (error) {
console.error(error);
Expand Down Expand Up @@ -107,4 +90,4 @@ function handleServerResponse(res, component) {
}
}

initCheckout();
initCheckout();
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ body {
a,
u {
text-decoration: none;
color: #0abf53
}

a:hover {
Expand Down
7 changes: 0 additions & 7 deletions giving-example/src/main/resources/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,6 @@ <h1>Adyen Giving - Donations demo</h1>
</div>
</a>
</li>
<!-- <li class="integration-list-item">-->
<!-- <a href="/preview?type=ideal" class="integration-list-item-link">-->
<!-- <div class="title-container">-->
<!-- <p class="integration-list-item-title">iDEAL</p>-->
<!-- </div>-->
<!-- </a>-->
<!-- </li>-->
</ul>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion giving-example/src/main/resources/templates/preview.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ <h2>Cart</h2>
</ul>
</div>
<div class="cart-footer"><span class="cart-footer-label">Total:</span><span
class="cart-footer-amount">10.00</span>
class="cart-footer-amount">100.00</span>
<a th:href="@{/checkout(type=${type})}">
<p class="button">Continue to checkout</p>
</a>
Expand Down

0 comments on commit 6cbaf0c

Please sign in to comment.