Skip to content

Instantly share code, notes, and snippets.

@wehub
Last active April 16, 2018 16:43
Show Gist options
  • Save wehub/24857daa502fa51b854b5681591f01fe to your computer and use it in GitHub Desktop.
Save wehub/24857daa502fa51b854b5681591f01fe to your computer and use it in GitHub Desktop.
Sample code for Apple Pay
$(function() {
// Point WePay to stage
WePay.set_endpoint("stage");
// Use your WePay client and account IDs here.
var clientId = 12345;
var accountId = 123456789;
// This is your Apple-registered merchant identifier
var merchantId = "example.com.wepay";
// The canonical name for your store. This may be displayed to the user.
// 128-character or less UTF-8 string. Do not localize the name.
var displayName = "WePay Example";
// Check that Apple Pay is available on this device/OS. This call is synchronous.
if (WePay.wallet.canMakeApplePayPayments()) {
// Show Apple Pay button
}
// Alternatively, check that Apple Pay is available and the user has saved a card.
// This performs an async server call to Apple.
WePay.wallet.canMakeApplePayPaymentsWithActiveCard(applePayMerchantId, function(response) {
if (response.canMakePayments) {
// Default to Apple Pay or show Apple Pay button
}
if (response.error) {
// Handle error if needed.
}
});
// If you ship products, you might want to have a variety of shipping method
// options depending on the shipping contact location.
var localShippingMethods = [
{label: 'Standard',
detail: 'Standard shipping via USPS.',
amount: '1.00',
identifier: 'usps_l'},
{label: 'Expedited',
detail: 'Expedited shipping via UPS.',
amount: '1.50',
identifier: 'ups_expedited_l'},
{label: 'Overnight',
detail: 'Overnight shipping via UPS.',
amount: '4.65',
identifier: 'ups_overnight_l'}
];
var nationalShippingMethods = [
{label: 'Standard',
detail: 'Standard shipping via USPS.',
amount: '3.15',
identifier: 'usps_n'},
{label: 'Expedited',
detail: 'Expedited shipping via UPS.',
amount: '5.25',
identifier: 'ups_expedited_n'},
{label: 'Overnight',
detail: 'Overnight shipping via UPS.',
amount: '14.60',
identifier: 'ups_overnight_n'}
];
var internationalShippingMethods = [
{label: 'International',
detail: 'International shipping via USPS.',
amount: '12.35',
identifier: 'international'}
];
// Create the payment request object to use with the payment sheet. Make
// changes to this payment request object as needed in response to changes
// on the payment sheet.
var paymentRequest = {
countryCode: 'US',
currencyCode: 'USD',
displayName: displayName,
lineItems: [
{label: 'Subtotal', amount: '10.00'},
{label: 'Shipping', amount: '1.00'}
{label: 'Tax', amount: '1.80'},
],
// Any combination of the following is allowed:
requiredBillingContactFields: ['name', 'postalAddress'],
// Any combination of the following is allowed:
requiredShippingContactFields: ['name', 'phone', 'postalAddress', 'email'],
shippingContact: {
emailAddress: '[email protected]'
},
shippingMethods: localShippingMethods,
// shippingType can be one or more of the following: shipping, delivery,
// storePickup, or servicePickup
shippingType: ['shipping'],
// This amount must always be the combined total of all line items (if lineItems are specified)
total: {label: 'Total', amount: '12.80'}
};
// Helper function to calculate a total from provided line items.
// This returns a string that is currency formatted.
function calculateTotalFromLineItems(lineItems) {
var total, x, item;
// Initialize the new total as a float.
total = 0.0;
for (x in lineItems) {
item = lineItems[x];
total += parseFloat(item.amount); // Amounts are strings so we must convert to a float first.
}
return "" + total.toFixed(2); // Returns the total as a string with two decimal places.
}
var onPaymentMethodSelected = function(paymentMethod) {
// The user changed their selected payment method. This can
// be used to update the line items and total if (for example)
// you wish to charge more for a certain payment method. We
// aren’t making any changes here, so just pass in the original data
var result = WePay.wallet.updateAfterPaymentMethodSelected(paymentRequest.total,
paymentRequest.lineItems);
if (result.error) {
// Handle error if needed.
WePay.wallet.abort();
}
};
var onShippingMethodSelected = function(shippingMethod) {
// The user changed their selected shipping method. This is where
// we update the shipping line item and new total.
// Make the changes directly to your paymentRequest object from earlier.
var x, item;
for (x in paymentRequest.lineItems) {
item = paymentRequest.lineItems[x];
if (item.label == 'Shipping') {
item.amount = shippingMethod.amount;
}
}
paymentRequest.total.amount = calculateTotalFromLineItems(paymentRequest.lineItems);
// This method takes a status param, which means that you can choose
// to inform the user that what they selected is invalid.
var result = WePay.wallet.updateAfterShippingMethodSelected(WePay.wallet.STATUS_SUCCESS,
paymentRequest.total,
paymentRequest.lineItems);
if (result.error) {
// Handle error if needed.
WePay.wallet.abort();
}
};
var onShippingContactSelected = function(shippingContact) {
// The user changed their selected shipping contact. This is where
// we update the the available shipping methods based
// on the user’s location.
var newShippingMethods, shippingAmount, x, item, result;
if (shippingContact.countryCode !== ‘us’) {
// Charge extra for international shipping
newShippingMethods = internationalShippingMethods;
}
else if (shippingContact.administrativeArea !== 'CA') {
// Charge a little extra for other states.
newShippingMethods = nationalShippingMethods;
}
else {
// Charge the local shipping rates
newShippingMethods = localShippingMethods;
}
// Update the line item for shipping to the default shipping method (index 0)
shippingAmount = newShippingMethods[0].amount;
for (x in paymentRequest.lineItems) {
item = paymentRequest.lineItems[x];
if (item.label == 'Shipping') {
item.amount = shippingAmount;
}
}
// Apply the shipping methods and update the total
paymentRequest.shippingMethods = newShippingMethods;
paymentRequest.total.amount = calculateTotalFromLineItems(paymentRequest.lineItems);
// This method takes a status param, which means that you
// can choose to inform the user that what they selected is invalid.
result = WePay.wallet.updateAfterShippingContactSelected(WePay.wallet.STATUS_SUCCESS,
paymentRequest.shippingMethods,
paymentRequest.total,
paymentRequest.lineItems);
if (result.error) {
// Handle error if needed.
WePay.wallet.abort();
}
};
var callback = function(response) {
// {string} credit_card_id, {object} paymentMethod, and an {object} error (if an error occurred).
if (response.error) {
// An error occurred during the Apple Pay tokenization process. Handle the error.
WePay.wallet.abort();
return;
}
var cardId = response.creditCardId;
var paymentMethod = response.paymentMethod;
// Make the call to your server with the card ID to complete the checkout process.
$.ajax({
url: "/processPayment",
data: {
credit_card_id: cardId
},
dataType: 'json',
type: 'POST',
success: function(result, status, xhr) {
// Dismiss the payment sheet with a successful status
WePay.wallet.completePayment(WePay.wallet.STATUS_SUCCESS);
},
error: function(xhr, status, error) {
// Determine what went wrong and dismiss the payment sheet with the error
WePay.wallet.completePayment(Wepay.wallet.STATUS_FAILURE);
}
});
};
// Respond to the Apple Pay button press
$("#applepay-button").click(function(e) {
// Begin tokenization with the previously defined parameters
var result = WePay.wallet.beginTokenization(clientId,
accountId,
merchantId,
paymentRequest,
callback,
onShippingContactSelected,
onShippingMethodSelected,
onPaymentMethodSelected);
if (result.error) {
// Handle error if needed.
}
});
});
@santiago-delpuerto-cko
Copy link

Hi,

What is the best way to stop someone from editing the page source and changing the amount that is then sent in the paymentRequest?

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment