Integration
Payments in iOS, Android, and React Native apps
PaymentHooks does not publish native mobile SDKs. Mobile apps open hosted checkout in the system browser, and your server confirms the payment. The reference code below shows the pattern on each platform.
How mobile checkout works
- Your backend creates a checkout session with
POST https://paymenthooks.com/api/v1/checkout-sessionsusing your secret key, and returns the sessionidandurlto the app. - The app opens
urlin the system browser (SFSafariViewController, ASWebAuthenticationSession or a Chrome Custom Tab). The customer pays on PaymentHooks. - PaymentHooks redirects to your
successUrlwithsession_idandpayment_idquery parameters. Register that URL as a Universal Link / App Link to return to the app. - The app asks your backend whether the session is
complete; your backend reads it withGET /api/v1/checkout-sessions/:idor relies on a verified webhook.
React Native
/**
* Hosted checkout from React Native (reference implementation).
*
* npm install react-native-inappbrowser-reborn
*
* Flow:
* 1. Your backend creates a checkout session with your secret key and returns
* { sessionId, url }. Set successUrl / cancelUrl to https URLs on your
* domain that are registered as iOS Universal Links / Android App Links.
* 2. The app opens session.url in the system browser (SFSafariViewController /
* Chrome Custom Tabs), where the customer pays on PaymentHooks.
* 3. After payment PaymentHooks redirects to successUrl with
* ?session_id=...&payment_id=... and the OS hands that link to your app.
* 4. The app asks YOUR backend for the session status. Never treat the
* redirect alone as proof of payment.
*/
import { Linking } from 'react-native';
import InAppBrowser from 'react-native-inappbrowser-reborn';
const YOUR_BACKEND = 'https://yourapp.example.com';
const PAYMENTHOOKS_CHECKOUT_BASE = 'https://paymenthooks.com';
// Your backend calls POST https://paymenthooks.com/api/v1/checkout-sessions
// (Authorization: Bearer phk_live_...) and returns { sessionId, url }.
async function createSession(cartId) {
const res = await fetch(`${YOUR_BACKEND}/checkout-sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cartId }),
});
if (!res.ok) throw new Error(`Could not create checkout session (${res.status})`);
return res.json();
}
// Your backend calls GET https://paymenthooks.com/api/v1/checkout-sessions/:id
// with your secret key and returns the session status ("complete" when paid).
async function fetchSessionStatus(sessionId) {
const res = await fetch(`${YOUR_BACKEND}/checkout-sessions/${encodeURIComponent(sessionId)}`);
if (!res.ok) throw new Error(`Could not load checkout session (${res.status})`);
return res.json();
}
export async function payWithHostedCheckout(cartId) {
const { sessionId, url } = await createSession(cartId);
const checkoutUrl = url ?? `${PAYMENTHOOKS_CHECKOUT_BASE}/checkout/${sessionId}`;
if (await InAppBrowser.isAvailable()) {
// Resolves when the customer closes the browser or your return link opens the app.
await InAppBrowser.open(checkoutUrl, { dismissButtonStyle: 'close' });
} else {
await Linking.openURL(checkoutUrl);
}
const session = await fetchSessionStatus(sessionId);
return session.status === 'complete'
? { status: 'paid', sessionId, paymentId: session.paymentId }
: { status: 'not_paid', sessionId };
}
iOS setup
Requires iOS 15+. To return to the app automatically after payment, host an apple-app-site-association file on your domain, add the Associated Domains capability (applinks:yourapp.example.com), and use a path on that domain as the session's successUrl.
iOS (Swift)
//
// HostedCheckout.swift — reference implementation, iOS 15+.
//
// 1. Your backend creates a checkout session with your secret key and returns
// { sessionId, url }. Set successUrl to an https URL on your domain.
// 2. The app opens session.url in ASWebAuthenticationSession; the customer pays
// on PaymentHooks.
// 3. Confirm the outcome with YOUR backend (GET /api/v1/checkout-sessions/:id
// with your secret key). The redirect alone is not proof of payment.
//
import AuthenticationServices
import UIKit
struct CheckoutSessionInfo: Decodable {
let sessionId: String
let url: String?
}
struct CheckoutStatus: Decodable {
let status: String // "complete" once paid
let paymentId: String?
}
final class HostedCheckout: NSObject, ASWebAuthenticationPresentationContextProviding {
private let backend = URL(string: "https://yourapp.example.com")!
private let checkoutBase = "https://paymenthooks.com"
private var authSession: ASWebAuthenticationSession?
/// Your backend calls POST https://paymenthooks.com/api/v1/checkout-sessions.
func createSession(cartId: String) async throws -> CheckoutSessionInfo {
var request = URLRequest(url: backend.appendingPathComponent("checkout-sessions"))
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(["cartId": cartId])
let (data, _) = try await URLSession.shared.data(for: request)
return try JSONDecoder().decode(CheckoutSessionInfo.self, from: data)
}
/// Your backend calls GET https://paymenthooks.com/api/v1/checkout-sessions/:id.
func fetchStatus(sessionId: String) async throws -> CheckoutStatus {
let url = backend.appendingPathComponent("checkout-sessions").appendingPathComponent(sessionId)
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(CheckoutStatus.self, from: data)
}
/// Presents hosted checkout and returns the confirmed status from your backend.
@MainActor
func pay(cartId: String) async throws -> CheckoutStatus {
let info = try await createSession(cartId: cartId)
let checkoutURL = URL(string: info.url ?? "\(checkoutBase)/checkout/\(info.sessionId)")!
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// The completion fires when the customer closes the sheet or a
// redirect to the callback scheme occurs; either way we re-check status.
let session = ASWebAuthenticationSession(url: checkoutURL, callbackURLScheme: nil) { _, _ in
continuation.resume()
}
session.presentationContextProvider = self
session.prefersEphemeralWebBrowserSession = false
authSession = session
session.start()
}
return try await fetchStatus(sessionId: info.sessionId)
}
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
UIApplication.shared.connectedScenes
.compactMap { ($0 as? UIWindowScene)?.keyWindow }
.first ?? ASPresentationAnchor()
}
}
Android setup
Add androidx.browser:browser for Custom Tabs, and declare your successUrl as a verified App Link (publish /.well-known/assetlinks.json on your domain).
<activity android:name=".CheckoutReturnActivity" android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https"
android:host="yourapp.example.com"
android:pathPrefix="/checkout/return" />
</intent-filter>
</activity>Android (Kotlin)
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
// 1. Ask YOUR backend to create a checkout session (it uses your phk_live_ secret key)
// and return { sessionId, url }.
// 2. Open hosted checkout in a Custom Tab.
fun openHostedCheckout(activity: Activity, checkoutUrl: String) {
CustomTabsIntent.Builder()
.setShowTitle(true)
.build()
.launchUrl(activity, Uri.parse(checkoutUrl))
}
// 3. Declare your successUrl as an Android App Link so the redirect
// https://yourapp.example.com/checkout/return?session_id=...&payment_id=...
// returns to your app, then confirm the session status with YOUR backend
// before showing a success screen.Apple Pay and Google Pay
Wallet buttons appear on hosted checkout when the session's payment is routed through a Stripe gateway connection and the customer's browser supports the wallet. There is no separate native wallet API for apps: the hosted page handles Apple Pay and Google Pay inside the system browser.
Confirming payments
Your server is the source of truth, not the app. Either read the checkout session from your backend after the customer returns, or handle webhooks. Events for registered endpoints (for example payment.succeeded) are signed with that endpoint's signing secret; if you set a per-session webhookUrl, it receives checkout.session.completed and checkout.session.payment_failed signed with your session webhook secret. Verification is the same in both cases:
import crypto from 'node:crypto';
import express from 'express';
const app = express();
const SECRET = process.env.PAYMENTHOOKS_WEBHOOK_SECRET; // whsec_...
const TOLERANCE_SECONDS = 300;
function verify(rawBody, header, secret) {
if (!header) return false;
const parts = { v1: [] };
for (const item of header.split(',')) {
const i = item.indexOf('=');
if (i <= 0) continue;
const key = item.slice(0, i).trim();
const value = item.slice(i + 1).trim();
if (key === 't') parts.t = value;
if (key === 'v1' || key === 'v1_previous') parts.v1.push(value);
}
const t = Number(parts.t);
if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;
const expected = crypto.createHmac('sha256', secret)
.update(t + '.')
.update(rawBody) // Buffer of the exact bytes received
.digest();
return parts.v1.some((sig) => {
const given = Buffer.from(sig, 'hex');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}
// express.raw keeps the body as a Buffer — do NOT use express.json() on this route.
app.post('/webhooks/paymenthooks', express.raw({ type: 'application/json' }), (req, res) => {
if (!verify(req.body, req.get('X-PaymentHooks-Signature'), SECRET)) {
return res.status(400).send('Invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
// Delivery is at-least-once: de-duplicate on event.id
res.sendStatus(200);
});Accept v1 or v1_previous (sent during the 24-hour secret rotation window), reject timestamps more than 300 seconds old, and hash the raw request body before any JSON parsing. In serverless functions, read the body as raw bytes so the signature matches byte-for-byte.