Unity 学习分享游戏极客社区

Unity 接 iOS 内购(Unity内置IAP)

2021-03-24  本文已影响0人  游戏创作者

Author :JerryYang
Create by 2021.03.24

环境:
Unity:2020.3.0f1c1


一、后台商品配置

  1. 进入苹果开发者后台,填写税务信息,银行信息(不填会出现购买失败);
  2. 选择你要添加内购的应用,找到 In-App Purchases 选项,点击 Manage
    选择你要添加内购的应用
  3. 点击添加商品,然后完善商品信息;

注意:这里要填写所以信息,包括截图,直到状态为 Ready to Submit 为止,不然也会出现购买失败

添加商品

二、unity API接入

  1. 点击 manage service 打开services面板;


    Services
  2. 选择一个组织,没有的话创建一个;
  3. 根据提示打开Purchasing,导入包,如果需要更新,请点击update;


    导入
  4. 购买功能可以通过unity提供的组件实现,也可以用代码实现,我们选择用代码实现。


    Unity IAP

三、代码部分

using UnityEngine;
using UnityEngine.Purchasing;
using System;

public class PurchasingManager : IStoreListener
{
    public static readonly PurchasingManager Instance = new PurchasingManager();
    private IStoreController storeController;
    private static IExtensionProvider extensionProvider;
    private static IAppleExtensions appleExtension;
    //private static IGooglePlayStoreExtensions googleExtension;

    private Action<string> failedCallback;
    private Action<Product> successedCallback;

    PurchasingManager()
    {
        
    }

    /// <summary>
    /// 初始化商品
    /// 建议在游戏初始化完成的时候就去初始化商品
    /// </summary>
    public void InitProduct()
    {
        if (IsInitialized()) return;
        var module = StandardPurchasingModule.Instance();
        ConfigurationBuilder builder = ConfigurationBuilder.Instance(module);
        builder.AddProduct("goods_coins100", ProductType.Consumable);
        builder.AddProduct("goods_vip7days", ProductType.NonConsumable);
        UnityPurchasing.Initialize(this, builder);
    }

    /// <summary>
    /// 发起内购
    /// </summary>
    /// <param name="_productId">要购买的商品ID</param>
    /// <param name="_successedCallback">购买成功回调</param>
    /// <param name="_failedCallback">购买失败回调</param>
    public void Purchase(string _productId, Action<Product> _successedCallback, Action<string> _failedCallback)
    {
        failedCallback = _failedCallback;
        successedCallback = _successedCallback;

        if (!IsInitialized())
        {
            OnFailedCallback("Not initialized.");
            return;
        }

        var product = storeController.products.WithID(_productId);
        if (product == null || !product.availableToPurchase)
        {
            OnFailedCallback("Either is not found or is not available for purchase");
            return;
        }

        Debug.Log($"Inicializando compra del producto {product.metadata.localizedTitle} en la tienda.");
        storeController.InitiatePurchase(product);
    }

    /// <summary>
    /// IOS恢复内购
    /// Google会在删除应用后,第一次安装是自动恢复
    /// </summary>
    /// <param name="restoreCallback">恢复回调</param>
    public void IosRestore(Action<bool> restoreCallback)
    {
        if (appleExtension != null)
        {
            appleExtension.RestoreTransactions(restoreCallback);
        }
        else
        {
            Debug.LogWarning("IAppleExtensions is null");
            restoreCallback(false);
        }
    }

    //======================================分割线=========================================


    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        storeController = controller;
        extensionProvider = extensions;
        appleExtension = extensions.GetExtension<IAppleExtensions>();
        //googleExtension = extensions.GetExtension<IGooglePlayStoreExtensions>();
    }

    public void OnInitializeFailed(InitializationFailureReason error)
    {
        Debug.LogWarning("OnInitializeFailed Reason:" + error);
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        Debug.LogWarning("OnPurchaseFailedproduct:"+ product.transactionID + "  failureReason:"+ failureReason);
    }

    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
    {
        if (successedCallback != null)
        {
            successedCallback(purchaseEvent.purchasedProduct);
        }
        return PurchaseProcessingResult.Complete;
    }

    private bool IsInitialized()
    {
        return storeController != null && extensionProvider != null;
    }

    private void OnFailedCallback(string _reason)
    {
        if (failedCallback != null)
        {
            failedCallback(_reason);
        }
    }
}

四、打包测试

  1. 包名一定和你后台的包名对应;

  2. 商品ID和类型也要和后台对应;

  3. 在苹果开发者后台的用户和访问菜单中找到沙盒,添加沙盒测试人员;


    添加测试员
  4. 在App Store登陆该测试账号;

  5. 点击要购买的商品,输入密码,弹出以下弹窗的时候说明购买成功了


    购买成功

走到这里说明你接成功了,恭喜你。


暂时写这么多,有不懂的或者需要补充的请私信我。

上一篇下一篇

猜你喜欢

热点阅读