You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Cordova的iOS应用内购买:自定义数量对应IAP档位问题

How to Map User-Requested Credits to Your IAP Tiers with Cordova Purchase Plugin

Hey there! Let's walk through how to connect the number of credits a user wants to buy to your iTunes Connect IAPs using the cc.fovea.cordova.purchase plugin. I'll break this down into actionable steps that fit your tiered pricing model.

First, let's assume you've got three consumable IAPs set up in iTunes Connect with clear product IDs (make sure these match exactly in your code later):

  • 1-25 credits: com.yourapp.credits.tier1 ($10)
  • 26-50 credits: com.yourapp.credits.tier2 ($8)
  • 50+ credits: com.yourapp.credits.tier3 ($6)

1. Define Your Tier Rules & IAP Mapping

Start by turning your pricing tiers into a reusable object in your code. This makes it easy to check which tier a user's request falls into:

const creditTiers = [
  { min: 1, max: 25, productId: 'com.yourapp.credits.tier1', price: 10 },
  { min: 26, max: 50, productId: 'com.yourapp.credits.tier2', price: 8 },
  { min: 51, max: Infinity, productId: 'com.yourapp.credits.tier3', price: 6 }
];

2. Write a Function to Match User Input to the Right IAP

Next, create a helper function that takes the user's desired credit count and returns the corresponding IAP details. I'll cover two common scenarios here depending on how you set up your IAPs:

Scenario A: IAPs are for individual credits

If each IAP represents a single credit at the tiered price (e.g., tier1 is $10 for 1 credit), use this:

function getMatchingIAP(desiredCredits) {
  // Validate input first
  if (typeof desiredCredits !== 'number' || desiredCredits < 1) {
    throw new Error('Please enter a valid number of credits (at least 1)');
  }

  // Find the tier that matches the desired count
  const matchedTier = creditTiers.find(tier => 
    desiredCredits >= tier.min && desiredCredits <= tier.max
  );

  if (!matchedTier) {
    throw new Error('No valid purchase option available for this amount');
  }

  // Return the IAP ID and exact quantity the user wants
  return { 
    productId: matchedTier.productId, 
    quantity: desiredCredits,
    totalCost: desiredCredits * matchedTier.price
  };
}

Scenario B: IAPs are bulk credit packs

If each IAP is a bulk pack (e.g., tier1 is $10 for 25 credits), calculate how many packs the user needs to cover their requested amount:

function getMatchingIAP(desiredCredits) {
  // Validate input first
  if (typeof desiredCredits !== 'number' || desiredCredits < 1) {
    throw new Error('Please enter a valid number of credits (at least 1)');
  }

  // Find the tier that matches the desired count
  const matchedTier = creditTiers.find(tier => 
    desiredCredits >= tier.min && desiredCredits <= tier.max
  );

  if (!matchedTier) {
    throw new Error('No valid purchase option available for this amount');
  }

  // Calculate how many bulk packs are needed (round up to cover the full request)
  const creditsPerPack = 25; // Adjust this to match your pack size
  const quantity = Math.ceil(desiredCredits / creditsPerPack);

  return { 
    productId: matchedTier.productId, 
    quantity: quantity,
    totalCost: quantity * matchedTier.price,
    totalCredits: quantity * creditsPerPack
  };
}

3. Integrate with the Cordova Purchase Plugin

Once you have the matching IAP details, use the plugin to handle the purchase flow. First, make sure you've initialized the plugin and loaded your products (do this on app startup ideally):

// Initialize the plugin
store.initialize();

// Load your IAP products from Apple's servers
store.load([
  'com.yourapp.credits.tier1',
  'com.yourapp.credits.tier2',
  'com.yourapp.credits.tier3'
]);

Then, create a function to handle the user's purchase request:

async function processCreditPurchase(desiredCredits) {
  try {
    // Get the matching IAP details
    const { productId, quantity } = getMatchingIAP(desiredCredits);

    // Check if the product is available for purchase
    const product = store.get(productId);
    if (!product || product.state !== 'approved') {
      throw new Error('This credit option is currently unavailable');
    }

    // Initiate the purchase
    const order = await store.order(productId, { quantity: quantity });

    // Handle successful purchase
    order.on('approved', (order) => {
      // Important: Verify this order with Apple's server before updating user credits!
      // Once verified, add the credits to the user's account
      // For Scenario A: add desiredCredits; for Scenario B: add quantity * creditsPerPack
      addCreditsToUserAccount(desiredCredits); // Adjust this to your logic

      // Mark the order as finished (required by the plugin)
      order.finish();
    });

    // Handle purchase errors
    order.on('error', (error) => {
      console.error('Purchase failed:', error.message);
      alert(`Oops, purchase failed: ${error.message}`);
    });

  } catch (error) {
    console.error('Error preparing purchase:', error.message);
    alert(error.message);
  }
}

4. Critical Things to Remember

  • Product ID Consistency: Double-check that the product IDs in your code match exactly what's in iTunes Connect (case-sensitive!).
  • Server-Side Verification: Never trust the frontend alone. Always validate the purchase receipt with Apple's server to prevent fraud.
  • Input Validation: Add checks on both the frontend and backend to ensure users can't request invalid credit amounts (like negative numbers).
  • User Feedback: Show the total cost to the user before they confirm the purchase—use the totalCost value returned from getMatchingIAP for this!

内容的提问来源于stack exchange,提问作者Souvik Saha Choudhury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:49:54