I am trying utilize recurring payments through Apple Pay. It appears that the payment session is setup correctly. The correct popup appears, indicating a immediate charge and a recurring payment, the the payment is successfully submitted to NMI and the response is sent back to the client.
Frontend Code:
function subscribe() {
var request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Budmember', amount: packages?.Package_Amount__c.toFixed(2).toString()},
recurringPaymentRequest: {
managementURL:"https://7d50e9ae5e20.ngrok.io/billing",
tokenNotificationURL:"https://webhook.site/8bb38a60-be08-47f5-82ba-2bdccc7ec4cf/",
paymentDescription: "VIP Membership",
regularBilling: {
label: {amount: packages?.Package_Amount__c.toFixed(2).toString(), type: "final"},
amount: packages?.Package_Amount__c.toFixed(2).toString(),
paymentTiming: "recurring",
recurringPaymentIntervalUnit: "month",
recurringPaymentStartDate: moment().format("YYYY-MM-DD"),
}},
}
//start apple Pay session
var session = new window.ApplePaySession(3, request);
session.begin()
session.onvalidatemerchant = async (event) => {
const res = await applePaySessionRequest(event.validationURL)
console.log(res.data)
session.completeMerchantValidation(res.data)
}
//submit payment to backend
session.onpaymentauthorized = async (event) => {
const dataPackage= {
onboardingStep: '7',
salesForceId: cognitoUser.salesForceId,
packageId: packages?.Id,
billingPackage: {
first_name: currentUser.firstName,
last_name: currentUser.lastName,
company: "",
address1: "",
address2: "",
city: "",
state: "",
zip: "",
country:"USA",
phone: "",
fax: "",
email: currentUser.email,
}
}
const res = await applePayInitialSub(event.payment, dataPackage )
if (res?.data?.success) {
//update token for new field in the token
setOnboardingStep("7");
localStorage.setItem("token", res.data.token || localStorage.getItem("token"));
notification("Membership Payment Received","success","Payment Success");
handleBillingAddress()
} else {
notification(res.data.msg || "Card Declined" , "danger" , "Error");
setLoading(false)
}
session.completePayment({status: res.data.applePayMsg})
}
}
Backend Code (Apple Pay Session):
async function applePaySession(req, res, next) {
const sessionURL = req.body.sessionURL
let response = {};
try {
function promisifyRequest(options) {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (body) {
return resolve(res.send(body));
}
if (error) {
return reject(error);
}
});
});
}
const options = {
url: sessionURL,
agentOptions: {
pfx: fs.readFileSync("./merchant_id.p12"),
passphrase: "SECRET",
},
method: 'post',
body: {
merchantIdentifier: "merchant.com.some.app",
displayName: "NAME",
initiative: "web",
initiativeContext: "some.url" // Frontend url as registered
},
json: true,
};
response = await promisifyRequest(options);
console.log(response)
} catch (error) {
console.log(error)
}
return response;
}
Backend Code (Payment and Subscribe):
async function appleSubProcessor(req, res, next) {
try {
const conn = sfConn();
const { cognitoUserId, accessToken, email } = req.user.data
const {billingPackage} = req.body
const {onboardingStep, salesForceId, packageId} = billingPackage
const member = await conn.sobject("Contact").find({"Email": email})
const response = await NMI.getSubscriptionById(member[0].Subscription_ID__c)
// PROCESSING CODE!!!!!
//encodes data object to buffer
const data = req.body.paymentObject.token.paymentData
var buf = Buffer.from(JSON.stringify(data))
//encodes buffer to hex string
const hexCode = buf.toString("hex")
//if subscription is present on NMI only charge
if(response?.nm_response?.subscription?.subscription_id) {
await applePaymentOnly(member, hexCode, billingPackage, email, res)
} else {
await applePayInitialSub(req, member, hexCode, res, cognitoUserId, accessToken, email, billingPackage)
}
} catch(err) {
console.log(err)
}
}
async function applePayInitialSub(req, member, paymentToken, res, cognitoUserId, accessToken, email, billingPackage) {
try {
const conn = sfConn()
// const { cognitoUserId, accessToken, email } = req.user.data
// const {billingPackage} = req.body
const {onboardingStep, salesForceId, packageId} = billingPackage
const subsc_data = await conn.sobject("Packages__c").find({"Id": packageId})
const dueNow = subsc_data[0].Package_Amount__c.toFixed(2).toString()
//Error handling - no package available
if(!subsc_data || !subsc_data.length){
console.log("Error")
Sentry.withScope((scope) => {
scope.setLevel("fatal");
Sentry.captureException("Internal Error, Unable to get subscription data");
})
return res.json({
success: false,
message:"Internal Error. Unable to get subscription data"
})
}
//sends request
const response = await NMI.applePayInitialSubscription(billingPackage.billingPackage, paymentToken, dueNow, email, billingPackage.billingPackage.email)
console.log(response)
onboarding logic ...
}
What I have tried so far:
Recharge the initial token. NMI returned "DO NOT HONOR". This indicated that Apple Pay was blocking the transaction. The card didn't have any fraud alert and I was able to charge it with a new token.
Set the subscription interval with Apple Pay to "minute" and attempted to re-charge the token after 60 seconds. Again, "DO NOT HONOR".
I set the tokenNotificationURL to an endpoint on my server. I tunneled to my localhost via NGROK for https. I was able to call the endpoint via postman. I followed the Apple Developer Docs. But didn't receive any hook calls from Apple.
I did step 3 with my webhook.site pro subscription. Postman call succeeded, no calls from Apple.
I searched StackOverflow for answers and found this post for Stripe. Here it is described that (with Stripe SDK) the paymentRequest comes with a "paymentmethod" listener which should return paymentMethod.id. I attempted to utilize AppleJS's onpaymentmethodselected to get access to the id but I only got paymentMethod: {type: "Credit"} as a response:
session.onpaymentmethodselected = async (event) => { session.completePaymentMethodSelection({newTotal: { amount:"49.00", label:'VIP Membership'}}) }
I decrypted the payment token on the backend. I followed this guide to create the certificate and key (.pem) files. His package uses an outdated dependency that doesn't work on newer versions of Node. I used this package to decrypt the token. However, I was not able to charge the applicationPrimaryAccountNumber. AVS seems to be not allowed so providing the zip code doesn't yield a successful transaction either. Below is the decrypted token as well as the NMI response:
I searched on SO and in the Apple Developer forums but wasn't able to get anywhere with this. I have been working on this issue for the past 3 days. Any help is greatly appreciated!