Пример #1
0
            public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
            {
                Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
                Debug.Log("Receipt: " + e.purchasedProduct.receipt);

                m_LastTransationID = e.purchasedProduct.transactionID;
                m_LastReceipt      = e.purchasedProduct.receipt;

                                #if RECEIPT_VALIDATION
                // Local validation is available for GooglePlay and Apple stores
                if (m_IsGooglePlayStoreSelected ||
                    Application.platform == RuntimePlatform.IPhonePlayer ||
                    Application.platform == RuntimePlatform.OSXPlayer ||
                    Application.platform == RuntimePlatform.tvOS)
                {
                    try {
                        var result = validator.Validate(e.purchasedProduct.receipt);
                        Debug.Log("Receipt is valid. Contents:");
                        foreach (IPurchaseReceipt productReceipt in result)
                        {
                            Debug.Log(productReceipt.productID);
                            Debug.Log(productReceipt.purchaseDate);
                            Debug.Log(productReceipt.transactionID);

                            GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                            if (null != google)
                            {
                                Debug.Log(google.purchaseState);
                                Debug.Log(google.purchaseToken);
                            }

                            AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                            if (null != apple)
                            {
                                Debug.Log(apple.originalTransactionIdentifier);
                                Debug.Log(apple.subscriptionExpirationDate);
                                Debug.Log(apple.cancellationDate);
                                Debug.Log(apple.quantity);
                            }
                        }
                    } catch (IAPSecurityException) {
                        Debug.Log("Invalid receipt, not unlocking content");
                        return(PurchaseProcessingResult.Complete);
                    }
                }
                                #endif

                foreach (var button in activeButtons)
                {
                    if (button.productId == e.purchasedProduct.definition.id)
                    {
                        return(button.ProcessPurchase(e));
                    }
                }

                return(PurchaseProcessingResult.Complete);                // TODO: Maybe this shouldn't return complete
            }
 SubscriptionInfo CreateSubscription(AppleInAppPurchaseReceipt purchase)
 {
     return(new SubscriptionInfo
     {
         UserId = null,
         TransactionId = purchase.OriginalTransactionId,
         SubscriptionDate = purchase.PurchaseDateDt,
         ExpirationDate = purchase.ExpirationDateDt,
         CancellationDate = purchase.CancellationDateDt,
         AutoRenews = purchase.SubscriptionAutoRenewStatus == AppleSubscriptionAutoRenewStatus.Active
     });
 }
Пример #3
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        m_PurchaseInProgress = false;

        // Now that my purchase history has changed, update its UI
        UpdateHistoryUI();

                #if RECEIPT_VALIDATION
        if (Application.platform == RuntimePlatform.Android ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }
                }
            } catch (IAPSecurityException) {
                Debug.Log("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Complete);
            }
        }
                #endif

        // You should unlock the content here.

        // Indicate we have handled this purchase, we will not be informed of it again.x
        return(PurchaseProcessingResult.Complete);
    }
Пример #4
0
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            var iapProduct = IAPController.Instance.GetProduct(e.purchasedProduct.definition.id);

            if (iapProduct != null)
            {
                var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
                var valid     = false;
                try
                {
                    var result = validator.Validate(e.purchasedProduct.receipt);
                    foreach (IPurchaseReceipt receipt in result)
                    {
#if UNITY_ANDROID || UNITY_STANDALONE
                        var google = receipt as GooglePlayReceipt;
                        if (null != google)
                        {
                            Debug.Log(google.transactionID);
                            Debug.Log(google.purchaseState);
                            Debug.Log(google.purchaseToken);
                        }
#elif UNITY_IOS
                        AppleInAppPurchaseReceipt apple = receipt as AppleInAppPurchaseReceipt;
                        if (null != apple)
                        {
                            Debug.Log(apple.originalTransactionIdentifier);
                            Debug.Log(apple.subscriptionExpirationDate);
                            Debug.Log(apple.cancellationDate);
                            Debug.Log(apple.quantity);
                        }
#endif
                    }
                    valid = true;
                }
                catch (IAPSecurityException secureException)
                {
                    Debug.Log(secureException.ToString());
                    valid = false;
                }

                if (valid)
                {
                    IAPController.Instance.OnPurchaseAuthorized(iapProduct);
                }
                else
                {
                    IAPController.Instance.OnPurchaseError(iapProduct);
                }
            }

            return(PurchaseProcessingResult.Complete);
        }
Пример #5
0
    private bool ValidateReceipt(Product product)
    {
        bool validReceipt = true;

#if UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE_OSX
        var validator = new CrossPlatformValidator(AppleTangle.Data(), GooglePlayTangle.Data(), Application.identifier);

        try
        {
            var result = validator.Validate(product.receipt);
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.LogFormat("{0}, {1}, {2}", productReceipt.productID,
                                productReceipt.purchaseDate,
                                productReceipt.transactionID);

                AppleInAppPurchaseReceipt aReceipt = productReceipt as AppleInAppPurchaseReceipt;
                if (aReceipt != null)
                {
                    Debug.LogFormat("{0}, {1}, {2}, {3}", aReceipt.originalTransactionIdentifier,
                                    aReceipt.subscriptionExpirationDate,
                                    aReceipt.cancellationDate,
                                    aReceipt.quantity);
                }

                GooglePlayReceipt gReceipt = productReceipt as GooglePlayReceipt;
                if (gReceipt != null)
                {
                    Debug.LogFormat("{0}, {1}, {2}", gReceipt.transactionID,
                                    gReceipt.purchaseState,
                                    gReceipt.purchaseToken);
                }
            }
        }
        catch (MissingStoreSecretException)
        {
            Debug.Log("You haven't supplied a secret key for this platform...");
            validReceipt = false;
        }
        catch (IAPSecurityException)
        {
            Debug.LogFormat("Invalid receipt {0}", product.receipt);
            validReceipt = false;
        }
#endif

        return(validReceipt);
    }
Пример #6
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        try {
            var result = validator.Validate(e.purchasedProduct.receipt);
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);

                AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                if (null != apple)
                {
                    Debug.Log(apple.originalTransactionIdentifier);
                    Debug.Log(apple.subscriptionExpirationDate);
                    Debug.Log(apple.cancellationDate);
                    Debug.Log(apple.quantity);


                    //如果有服务器,服务器用这个receipt去苹果验证。
                    //	var receiptJson = JSONObject.Parse(e.purchasedProduct.receipt);
                    //	var receipt = receiptJson.GetString("Payload");
                }
                GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                if (null != google)
                {
                    Debug.Log(google.purchaseState);
                    Debug.Log(google.purchaseToken);
                }
                PlatFormController.GetInstance().buyCommand(productReceipt.productID, productReceipt.transactionID, e.purchasedProduct.receipt);
            }
            return(PurchaseProcessingResult.Complete);
        } catch (Exception) {
            Debug.Log("Invalid receipt, not unlocking content");
            return(PurchaseProcessingResult.Complete);
        }
    }
Пример #7
0
    public void SendReqPurchase(Action <string, string> response, Action <string> timeout, string productUrl,
                                GooglePlayReceipt google, AppleInAppPurchaseReceipt apple)
    {
        if (CONFIG.IsRunningAndroid())
        {
            PK.Purchase.SendDataAndroid data = new PK.Purchase.SendDataAndroid();
            data.status        = "completed";
            data.currency      = "USD";
            data.quantity      = "1";
            data.amount        = 1.0;
            data.purchase_type = "coin";
            data.product_url   = productUrl;
            data.packageName   = google.packageName;
            data.productId     = google.productID;
            data.transactionID = google.transactionID;
            data.purchaseTime  = (double)google.purchaseDate.Ticks;
            data.purchaseState = (int)google.purchaseState;
            data.purchaseToken = google.purchaseToken;

            PK.Purchase.SENDAndroid command = new PK.Purchase.SENDAndroid(PKID.PurchaseAndroid, data);
            _NetSocket.SendData(xLitJson.JsonMapper.ToJson(command), PKID.PurchaseAndroid, response, timeout);
        }
        else if (CONFIG.IsRunningiOS())
        {
            PK.Purchase.SendDataIOS data = new PK.Purchase.SendDataIOS();
            data.status        = "completed";
            data.currency      = "USD";
            data.quantity      = "1";
            data.product_url   = productUrl;
            data.purchase_type = "coin";
            data.amount        = 1.0;
            data.purchaseToken = apple.originalTransactionIdentifier;

            PK.Purchase.SENDIOS command = new PK.Purchase.SENDIOS(PKID.PurchaseIOS, data);
            _NetSocket.SendData(xLitJson.JsonMapper.ToJson(command), PKID.PurchaseIOS, response, timeout);
        }
    }
        public AppleAppReceipt GetAppleReceiptFromNode(Asn1Node tNode, AppleAppReceipt?receipt = null)
        {
            receipt ??= new AppleAppReceipt();

            var processedNode = false;

            if ((tNode.Tag & Asn1Type.Date) == Asn1Type.Sequence && tNode.ChildNodeCount == 3)
            {
                var node1 = tNode.GetChildNode(0);
                var node2 = tNode.GetChildNode(1);
                var node3 = tNode.GetChildNode(2);

                if ((node1.Tag & Asn1Type.Date) == Asn1Type.Integer &&
                    (node2.Tag & Asn1Type.Date) == Asn1Type.Integer &&
                    (node3.Tag & Asn1Type.Date) == Asn1Type.OctetString)
                {
                    processedNode = true;
                    var asnType = (ReceiptAsnType)_utilities.BytesToLong(node1.Data);
                    switch (asnType)
                    {
                    case ReceiptAsnType.ReceiptType:
                        receipt.ReceiptType = _nodesParser.GetStringFromNode(node3);
                        break;

                    case ReceiptAsnType.BundleIdentifier:
                        receipt.BundleId = _nodesParser.GetStringFromNode(node3);
                        break;

                    case ReceiptAsnType.AppVersion:
                        receipt.ApplicationVersion = _nodesParser.GetStringFromNode(node3);
                        break;

                    case ReceiptAsnType.OpaqueValue:
                        break;

                    case ReceiptAsnType.Hash:
                        break;

                    case ReceiptAsnType.OriginalAppVersion:
                        receipt.OriginalApplicationVersion = _nodesParser.GetStringFromNode(node3);
                        break;

                    case ReceiptAsnType.ReceiptExpirationDate:
                        break;

                    case ReceiptAsnType.ReceiptCreationDate:
                        receipt.ReceiptCreationDateMs = _nodesParser.GetDateTimeMsFromNode(node3);
                        break;

                    case ReceiptAsnType.OriginalPurchaseDate:
                        receipt.OriginalPurchaseDateMs = _nodesParser.GetDateTimeMsFromNode(node3);
                        break;

                    case ReceiptAsnType.InAppPurchaseReceipt:
                    {
                        if (node3.ChildNodeCount > 0)
                        {
                            var node31 = node3.GetChildNode(0);

                            if ((node31.Tag & Asn1Type.Date) == Asn1Type.Set && node31.ChildNodeCount > 0)
                            {
                                var purchaseReceipt = new AppleInAppPurchaseReceipt();

                                for (var i = 0; i < node31.ChildNodeCount; i++)
                                {
                                    var node311 = node31.GetChildNode(i);
                                    if ((node311.Tag & Asn1Type.Date) == Asn1Type.Sequence &&
                                        node311.ChildNodeCount == 3)
                                    {
                                        var node3111 = node311.GetChildNode(0);
                                        var node3112 = node311.GetChildNode(1);
                                        var node3113 = node311.GetChildNode(2);

                                        if ((node3111.Tag & Asn1Type.Date) == Asn1Type.Integer &&
                                            (node3112.Tag & Asn1Type.Date) == Asn1Type.Integer &&
                                            (node3113.Tag & Asn1Type.Date) == Asn1Type.OctetString)
                                        {
                                            var childAsnType = (InAppPurchaseAsnType)_utilities.BytesToLong(node3111.Data);
                                            switch (childAsnType)
                                            {
                                            case InAppPurchaseAsnType.Quantity:
                                                purchaseReceipt.Quantity = _nodesParser.GetIntegerFromNode(node3113).ToString();
                                                break;

                                            case InAppPurchaseAsnType.ProductIdentifier:
                                                purchaseReceipt.ProductId = _nodesParser.GetStringFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.TransactionIdentifier:
                                                purchaseReceipt.TransactionId = _nodesParser.GetStringFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.PurchaseDate:
                                                purchaseReceipt.PurchaseDateMs = _nodesParser.GetDateTimeMsFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.OriginalTransactionIdentifier:
                                                purchaseReceipt.OriginalTransactionId = _nodesParser.GetStringFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.OriginalPurchaseDate:
                                                purchaseReceipt.OriginalPurchaseDateMs = _nodesParser.GetDateTimeMsFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.SubscriptionExpirationDate:
                                                purchaseReceipt.ExpirationDateMs = _nodesParser.GetDateTimeMsFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.WebOrderLineItemId:
                                                purchaseReceipt.WebOrderLineItemId = _nodesParser.GetStringFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.CancellationDate:
                                                purchaseReceipt.CancellationDateMs = _nodesParser.GetDateTimeMsFromNode(node3113);
                                                break;

                                            case InAppPurchaseAsnType.SubscriptionIntroductoryPricePeriod:
                                                purchaseReceipt.IsInIntroOfferPeriod = _nodesParser.GetBoolFromNode(node3113);
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (!string.IsNullOrEmpty(purchaseReceipt.ProductId))
                                {
                                    receipt.PurchaseReceipts.Add(purchaseReceipt);
                                }
                            }
                        }
                    }
                    break;

                    default:
                        processedNode = false;
                        break;
                    }
                }
            }

            if (!processedNode)
            {
                for (var i = 0; i < tNode.ChildNodeCount; i++)
                {
                    var chld = tNode.GetChildNode(i);
                    if (chld != null)
                    {
                        var subReceipt = GetAppleReceiptFromNode(chld, receipt);
                        if (subReceipt.PurchaseReceipts != null)
                        {
                            foreach (var sr in subReceipt.PurchaseReceipts)
                            {
                                if (receipt.PurchaseReceipts.All(purchaseReceipt =>
                                                                 purchaseReceipt.ProductId != sr.ProductId))
                                {
                                    receipt.PurchaseReceipts.Add(sr);
                                }
                            }
                        }
                    }
                }
            }

            return(receipt);
        }
    private void parseNodeRecursive(Asn1Node tNode)
    {
        bool processed_node = false;

        if ((tNode.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.SEQUENCE && tNode.ChildNodeCount == 3)
        {
            Asn1Node node1 = tNode.GetChildNode(0);
            Asn1Node node2 = tNode.GetChildNode(1);
            Asn1Node node3 = tNode.GetChildNode(2);
            if ((node1.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER && (node2.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER &&
                (node3.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING)
            {
                processed_node = true;
                int type = (int)Asn1Util.BytesToLong(node1.Data);
                switch (type)
                {
                case AppReceiptASN1TypeBundleIdentifier:
                    BundleIdentifier = getStringFromSubNode(node3);
                    break;

                case AppReceiptASN1TypeAppVersion:
                    AppVersion = getStringFromSubNode(node3);
                    break;

                case AppReceiptASN1TypeOpaqueValue:
                    break;

                case AppReceiptASN1TypeHash:
                    break;

                case AppReceiptASN1TypeOriginalAppVersion:
                    OriginalAppVersion = getStringFromSubNode(node3);
                    break;

                case AppReceiptASN1TypeReceiptExpirationDate:
                    break;

                case AppReceiptASN1TypeReceiptCreationDate:
                    ReceiptCreationDate = getDateTimeFromSubNode(node3);
                    break;

                case AppReceiptASN1TypeInAppPurchaseReceipt:
                {
                    if (node3.ChildNodeCount > 0)
                    {
                        Asn1Node node31 = node3.GetChildNode(0);
                        if ((node31.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.SET && node31.ChildNodeCount > 0)
                        {
                            AppleInAppPurchaseReceipt receipt = new AppleInAppPurchaseReceipt();
                            for (int i = 0; i < node31.ChildNodeCount; i++)
                            {
                                Asn1Node node311 = node31.GetChildNode(i);
                                if ((node311.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.SEQUENCE && node311.ChildNodeCount == 3)
                                {
                                    Asn1Node node3111 = node311.GetChildNode(0);
                                    Asn1Node node3112 = node311.GetChildNode(1);
                                    Asn1Node node3113 = node311.GetChildNode(2);
                                    if ((node3111.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER && (node3112.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.INTEGER &&
                                        (node3113.Tag & Asn1Tag.TAG_MASK) == Asn1Tag.OCTET_STRING)
                                    {
                                        int type1 = (int)Asn1Util.BytesToLong(node3111.Data);
                                        switch (type1)
                                        {
                                        case AppReceiptASN1TypeQuantity:
                                            receipt.Quantity = getIntegerFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeProductIdentifier:
                                            receipt.ProductIdentifier = getStringFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeTransactionIdentifier:
                                            receipt.TransactionIdentifier = getStringFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypePurchaseDate:
                                            receipt.PurchaseDate = getDateTimeFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeOriginalTransactionIdentifier:
                                            receipt.OriginalTransactionIdentifier = getStringFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeOriginalPurchaseDate:
                                            receipt.OriginalPurchaseDate = getDateTimeFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeSubscriptionExpirationDate:
                                            receipt.SubscriptionExpirationDate = getDateTimeFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeWebOrderLineItemID:
                                            receipt.WebOrderLineItemID = getIntegerFromSubNode(node3113);
                                            break;

                                        case AppReceiptASN1TypeCancellationDate:
                                            receipt.CancellationDate = getDateTimeFromSubNode(node3113);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(receipt.ProductIdentifier))
                            {
                                PurchaseReceipts.Add(receipt.ProductIdentifier, receipt);
                            }
                        }
                    }
                }
                break;

                default:
                    processed_node = false;
                    break;
                }
            }
        }
        if (!processed_node)
        {
            for (int i = 0; i < tNode.ChildNodeCount; i++)
            {
                Asn1Node chld = tNode.GetChildNode(i);
                if (chld != null)
                {
                    parseNodeRecursive(chld);
                }
            }
        }
    }
Пример #10
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        m_LastTransationID   = e.purchasedProduct.transactionID;
        m_LastReceipt        = e.purchasedProduct.receipt;
        m_PurchaseInProgress = false;

        // Now that my purchase history has changed, update its UI
        UpdateHistoryUI();

                #if RECEIPT_VALIDATION
        // Local validation is available for GooglePlay and Apple stores
        if (m_IsGooglePlayStoreSelected ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer ||
            Application.platform == RuntimePlatform.tvOS)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }
                }
            } catch (IAPSecurityException) {
                Debug.Log("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Complete);
            }
        }
                #endif

        // CloudMoolah purchase completion / finishing currently requires using the API
        // extension IMoolahExtension.RequestPayout to finish a transaction.
        if (m_IsCloudMoolahStoreSelected)
        {
            // Finish transaction with CloudMoolah server
            m_MoolahExtensions.RequestPayOut(e.purchasedProduct.transactionID,
                                             (string transactionID, RequestPayOutState state, string message) => {
                if (state == RequestPayOutState.RequestPayOutSucceed)
                {
                    // Finally, finish transaction with Unity IAP's local
                    // transaction log, recording the transaction id there
                    m_Controller.ConfirmPendingPurchase(e.purchasedProduct);

                    // Unlock content here.
                }
                else
                {
                    Debug.Log("RequestPayOut: failed. transactionID: " + transactionID +
                              ", state: " + state + ", message: " + message);
                    // Finishing failed. Retry later.
                }
            });
        }

        // You should unlock the content here.

        // Indicate if we have handled this purchase.
        //   PurchaseProcessingResult.Complete: ProcessPurchase will not be called
        //     with this product again, until next purchase.
        //   PurchaseProcessingResult.Pending: ProcessPurchase will be called
        //     again with this product at next app launch. Later, call
        //     m_Controller.ConfirmPendingPurchase(Product) to complete handling
        //     this purchase. Use to transactionally save purchases to a cloud
        //     game service.
        return(PurchaseProcessingResult.Complete);
    }
Пример #11
0
    //购买不同商品结束后的处理方法 对应定义的商品
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {//https://docs.unity3d.com/Manual/UnityIAPValidatingReceipts.html
        Debug.Log("e.purchasedProduct.availableToPurchase:" + e.purchasedProduct.availableToPurchase);
        Debug.Log("e.purchasedProduct.definition:" + e.purchasedProduct.definition);
        Debug.Log("e.purchasedProduct.hasReceipt:" + e.purchasedProduct.hasReceipt);
        Debug.Log("e.purchasedProduct.metadata:" + e.purchasedProduct.metadata);

        Debug.Log("e.purchasedProduct.receipt:" + e.purchasedProduct.receipt);
        Debug.Log("e.purchasedProduct.transactionID:" + e.purchasedProduct.transactionID);

        Debug.Log("enabled:" + e.purchasedProduct.definition.enabled);
        Debug.Log("id:" + e.purchasedProduct.definition.id);
        Debug.Log("storeSpecificId:" + e.purchasedProduct.definition.storeSpecificId);
        Debug.Log("type:" + e.purchasedProduct.definition.type);

        Debug.Log("isoCurrencyCode:" + e.purchasedProduct.metadata.isoCurrencyCode);
        Debug.Log("localizedDescription:" + e.purchasedProduct.metadata.localizedDescription);
        Debug.Log("localizedPrice:" + e.purchasedProduct.metadata.localizedPrice);
        Debug.Log("localizedPriceString:" + e.purchasedProduct.metadata.localizedPriceString);
        Debug.Log("localizedTitle:" + e.purchasedProduct.metadata.localizedTitle);

        bool validPurchase = true; // Presume valid for platforms with no R.V.

        // Unity IAP's validation logic is only included on these platforms.
        #if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.identifier);

        string googleToken = null;
        bool   isGoogle    = false;

        try
        {
            // On Google Play, result has a single product ID.
            // On Apple stores, receipts contain multiple products.
            var result = validator.Validate(e.purchasedProduct.receipt);
            // For informational purposes, we list the receipt(s)
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);

                GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                if (null != google)
                {
                    // This is Google's Order ID.
                    // Note that it is null when testing in the sandbox
                    // because Google's sandbox does not provide Order IDs.
                    Debug.Log(google.transactionID);
                    Debug.Log(google.purchaseState);
                    Debug.Log(google.purchaseToken);
                    isGoogle    = true;
                    googleToken = google.purchaseToken;
                }

                AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                if (null != apple)
                {
                    Debug.Log(apple.originalTransactionIdentifier);
                    Debug.Log(apple.subscriptionExpirationDate);
                    Debug.Log(apple.cancellationDate);
                    Debug.Log(apple.quantity);
                }
            }
        }
        catch (IAPSecurityException)
        {
            Debug.Log("Invalid receipt, not unlocking content");
            validPurchase = false;
        }
        #endif

        if (validPurchase && isGoogle)
        {
            buyCallBack.Invoke(e.purchasedProduct.definition.id, true, googleToken);
        }
        else
        {
            buyCallBack.Invoke(e.purchasedProduct.definition.id, false, null);
        }

        //if (Application.platform == RuntimePlatform.Android){
        //    try {
        //        var result = validator.Validate (e.purchasedProduct.receipt);
        //        Debug.Log ("Receipt is valid. Contents:");
        //        foreach (IPurchaseReceipt productReceipt in result) {
        //            Debug.Log(productReceipt.productID);
        //            Debug.Log(productReceipt.purchaseDate);
        //            Debug.Log(productReceipt.transactionID);

        //            AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
        //            if (null != apple) {
        //                Debug.Log(apple.originalTransactionIdentifier);
        //                Debug.Log(apple.subscriptionExpirationDate);
        //                Debug.Log(apple.cancellationDate);
        //                Debug.Log(apple.quantity);


        //                //如果有服务器,服务器用这个receipt去苹果验证。
        //                //var receiptJson = JSONObject.Parse(e.purchasedProduct.receipt);
        //                //var receipt = receiptJson.GetString("Payload");
        //            }

        //            GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
        //            if (null != google) {
        //                Debug.Log(google.purchaseState);
        //                Debug.Log(google.purchaseToken);
        //            }
        //        }
        //        return PurchaseProcessingResult.Complete;
        //    } catch (IAPSecurityException) {
        //        Debug.Log("Invalid receipt, not unlocking content");
        //        return PurchaseProcessingResult.Complete;
        //    }
        //}

        //if (Application.platform == RuntimePlatform.IPhonePlayer)
        //{

        //}


        //WarnDialog.showWarnDialog(e.purchasedProduct.definition.id+","+e.purchasedProduct.receipt+","+e.purchasedProduct.metadata.localizedPrice);

        //try {
        //    var result = validator.Validate (e.purchasedProduct.receipt);
        //    Debug.Log ("Receipt is valid. Contents:");
        //    foreach (IPurchaseReceipt productReceipt in result) {
        //        Debug.Log(productReceipt.productID);
        //        Debug.Log(productReceipt.purchaseDate);
        //        Debug.Log(productReceipt.transactionID);

        //        AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
        //        if (null != apple) {
        //            Debug.Log(apple.originalTransactionIdentifier);
        //            Debug.Log(apple.subscriptionExpirationDate);
        //            Debug.Log(apple.cancellationDate);
        //            Debug.Log(apple.quantity);


        //            //如果有服务器,服务器用这个receipt去苹果验证。
        //            //var receiptJson = JSONObject.Parse(e.purchasedProduct.receipt);
        //            //var receipt = receiptJson.GetString("Payload");
        //        }

        //        GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
        //        if (null != google) {
        //            Debug.Log(google.purchaseState);
        //            Debug.Log(google.purchaseToken);
        //        }
        //    }
        //    return PurchaseProcessingResult.Complete;
        //} catch (IAPSecurityException) {
        //    Debug.Log("Invalid receipt, not unlocking content");
        //    return PurchaseProcessingResult.Complete;
        //}
        //return PurchaseProcessingResult.Complete;



        //// A consumable product has been purchased by this user.
        //if (String.Equals(args.purchasedProduct.definition.id, product_1, StringComparison.Ordinal))
        //{
        //    //商品1购买成功逻辑
        //    Debug.Log(args.purchasedProduct.definition.id+","+product_1);
        //}
        //else if (String.Equals(args.purchasedProduct.definition.id, product_2, StringComparison.Ordinal))
        //{

        //    //商品2购买成功逻辑
        //    Debug.Log(args.purchasedProduct.definition.id + "," + product_2);
        //}
        //else if (String.Equals(args.purchasedProduct.definition.id, product_3, StringComparison.Ordinal))
        //{
        //    //商品3购买成功逻辑
        //    Debug.Log(args.purchasedProduct.definition.id + "," + product_3);
        //}
        //else
        //{
        //    Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
        //}

        //// Return a flag indicating whether this product has completely been received, or if the application needs
        //// to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
        //// saving purchased products to the cloud, and when that save is delayed.
        return(PurchaseProcessingResult.Complete);
    }
Пример #12
0
    /// <summary> 구매에 대한 처리 부분 </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        Debug.Log(args.purchasedProduct.receipt);
        string signedData = "";
        string signature  = "";
        Dictionary <string, object> jsonReceiptDic = (Dictionary <string, object>)MiniJson.JsonDecode(args.purchasedProduct.receipt);
        var payload = jsonReceiptDic["Payload"];
        Dictionary <string, object> jsonDic = (Dictionary <string, object>)MiniJson.JsonDecode(payload.ToString());


        foreach (KeyValuePair <string, object> pair in jsonDic)
        {
            if (pair.Key == "json")
            {
                signedData = pair.Value.ToString();
                Debug.Log(pair.Value);
            }
            else if (pair.Key == "signature")
            {
                signature = pair.Value.ToString();
                Debug.Log(pair.Value);
            }
        }
        bool validPurchase = true;

        string purchaseToken = "";
        string purchaseDate  = "";

        transactionID = null;

        //#if RECEIPT_VALIDATION
        if (isGooglePlayStoreSelected || isAppStoreSelected)
        {
            validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
            try
            {
                var result = validator.Validate(args.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");

                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        //Debug.Log(google.transactionID);
                        //Debug.Log(google.purchaseState);
                        //Debug.Log(google.purchaseToken);
                        Debug.Log(args.purchasedProduct.definition.id);
                        Debug.Log(productReceipt.productID);
                        if (args.purchasedProduct.transactionID != productReceipt.transactionID)
                        {
                            throw new IAPSecurityException("not matched transactionID");
                        }

                        if (args.purchasedProduct.definition.id != productReceipt.productID)
                        {
                            throw new IAPSecurityException("not matched productID");
                        }



                        transactionID = google.transactionID;
                        purchaseToken = google.purchaseToken;
                        purchaseDate  = google.purchaseDate.ToString();
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }

                    // For improved security, consider comparing the signed
                    // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
                    // embedded in the signed receipt objects to the data which the game is using
                    // to make this purchase.
                }
            }
            catch (IAPSecurityException ex)
            {
                isFailed = true;
                Debug.Log("Invalid receipt, not unlocking content. " + ex);
                validPurchase = false;
            }
        }
        //#endif


        if (validPurchase)
        {
#if UNITY_EDITOR
            isSuccess = true;
            if (AdController.Instance != null)
            {
                AdController.Instance.DeleteBanner();
            }
#endif
#if !UNITY_EDITOR
            if (isGooglePlayStoreSelected)
            {
                //StartCoroutine(PurchaseGoogleReceiptSave(args.purchasedProduct.definition.id, args.purchasedProduct.receipt, transactionID, purchaseToken, purchaseDate, signedData, signature));
                //
                StartVerifyGoogleReceipt(args.purchasedProduct.definition.id, args.purchasedProduct.receipt, transactionID, purchaseToken, purchaseDate, signedData, signature);
            }
            else if (isAppStoreSelected)
            {
                //애플 검증
            }
#endif
        }
        return(PurchaseProcessingResult.Complete);
    }
Пример #13
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        purchaseInProgress = false;

                #if RECEIPT_VALIDATION
        if (Application.platform == RuntimePlatform.Android ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }
                }
            } catch (IAPSecurityException) {
                Debug.Log("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Complete);
            }
        }
                #endif


        // アイテムデータの取得
                #if UNITY_ANDROID
        PurchaseItemData[] items = androidItems;
                #elif UNITY_IOS
        PurchaseItemData[] items = iosItems;
                #endif

        Debug.Log(string.Join(" - ",
                              new[]
        {
            e.purchasedProduct.definition.id,
            e.purchasedProduct.definition.storeSpecificId,
            e.purchasedProduct.metadata.localizedTitle,
            e.purchasedProduct.metadata.localizedDescription,
            e.purchasedProduct.metadata.isoCurrencyCode,
            e.purchasedProduct.metadata.localizedPrice.ToString(),
            e.purchasedProduct.metadata.localizedPriceString
        }));

        // プロダクトIDの検索
        foreach (PurchaseItemData item in items)
        {
            // 同じプロダクトIDであれば
            if (item.productId == e.purchasedProduct.definition.storeSpecificId)
            {
                // 購入完了通知
                if (OnPurchaseCompletedEvent != null)
                {
                    OnPurchaseCompletedEvent(item);
                }
            }
        }

        // You should unlock the content here.

        // Indicate we have handled this purchase, we will not be informed of it again.x
        return(PurchaseProcessingResult.Complete);
    }
Пример #14
0
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        MyLog.D("Purchase OK: " + e.purchasedProduct.definition.id);
        MyLog.D("Receipt: " + e.purchasedProduct.receipt);

        m_PurchaseInProgress = false;

                #if RECEIPT_VALIDATION
        if (Application.platform == RuntimePlatform.Android ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                MyLog.D("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    MyLog.D(productReceipt.productID);
                    MyLog.D(productReceipt.purchaseDate);
                    MyLog.D(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        MyLog.D(google.purchaseState);
                        MyLog.D(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        MyLog.D(apple.originalTransactionIdentifier);
                        MyLog.D(apple.subscriptionExpirationDate);
                        MyLog.D(apple.cancellationDate);
                        MyLog.D(apple.quantity);
                    }
                }
            } catch (IAPSecurityException) {
                MyLog.D("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Pending);
            }
        }
                #endif

        /// Unity: Receipt:
        /// {"Store":"GooglePlay",
        ///  "TransactionID":"jajodepcioojoaihijpmknfo.AO-J1OwyGtSin48PuN7edkU971ENoMJqLptLkptMNMi0
        ///   eTPXs-cLbDVNMJYvfMNcYPtt0PcpvQQ_zzJ96DfDImgMVnl-Pc1lDghKxPQI2MS9mrOBAPUH1Zd_3TvYRf3Bm
        ///   j3lnaPiTS09",
        ///   "Payload":"{\"json\":\"{\\\"packageName\\\":\\\"com.tatuaki.unity\\\",\\\"productId\\\":\\\"com.tatuaki.unity.04\\\",
        ///  \\\"purchaseTime\\\":1477152805761,\\\"purchaseState\\\":0,\\\"purchaseToken\\\":
        ///  \\\"jajodepcioojoaihijpmknfo.AO-J1OwyGtSin48PuN7edkU971ENoMJqLptLkptMNMi0eTPXs-cL
        ///  // bDVNMJYvfMNcYPtt0PcpvQQ_zzJ96DfDImgMVnl-Pc1lDghKxPQI2MS9mrOBAPUH1Zd_3TvYRf3Bmj3lnaPiTS09\\\"}\",
        ///  \"signature\":\"UBvK6MVoYWznB8oADRU4ligkTX7MdQCI7EuyBuSD8HvB\\/cCTF3mJirbzQi9gU0MijkHG1gFVg396kSGa5e
        ///  eXA5AHrz+eVkYO9sqgMwdJA71S\\/UNW9YAIirVqSEgNGWLz3uEv\\/tPgcmM7ypJvjdepGbm1FD\\/TQcp6oTHhR1aBBuwxxkRJ
        ///  rD7S0ScZJjIv8vQZxWY49rmKHGN4BGxJls5h+RnxKoz3arXzMPf4Z0UN5x1PYv9Q3JUxk7Fhy15CaI39ikjt1CiRAr9293jOLV7fI
        ///  EX5JbIavbosAZsCtFTlToJtiawYbj3OcOzpCPt3QXeKrmgE5fwfmyd3Sex7FyNrCQ==\"}"}


        // TODO 価格取得
        finishPurchaseEvent = TopViewController.FinishPurchaseEvent;
        finishPurchaseEvent(e.purchasedProduct.definition.id, null);

        return(PurchaseProcessingResult.Pending);
    }
Пример #15
0
    /// <summary>
    /// 구매성공 Processes the purchase.
    /// </summary>
    /// <param name="args">The <see cref="PurchaseEventArgs"/> instance containing the event data.</param>
    /// <returns></returns>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        bool validPurchase = true; // Presume valid for platforms with no R.V.

        // Unity IAP's validation logic is only included on these platforms.
#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
        // Prepare the validator with the secrets we prepared in the Editor
        // obfuscation window.
        var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),
                                                   AppleTangle.Data(), Application.bundleIdentifier);

        try
        {
            // On Google Play, result has a single product ID.
            // On Apple stores, receipts contain multiple products.
            var result = validator.Validate(args.purchasedProduct.receipt);
            // For informational purposes, we list the receipt(s)
            Debug.Log("Receipt is valid. Contents:");
            foreach (IPurchaseReceipt productReceipt in result)
            {
                Debug.Log(productReceipt.productID);
                Debug.Log(productReceipt.purchaseDate);
                Debug.Log(productReceipt.transactionID);

                GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                if (null != google)
                {
                    // This is Google's Order ID.
                    // Note that it is null when testing in the sandbox
                    // because Google's sandbox does not provide Order IDs.
                    Debug.Log(google.transactionID);
                    Debug.Log(google.purchaseState);
                    Debug.Log(google.purchaseToken);
                }

                AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                if (null != apple)
                {
                    Debug.Log(apple.originalTransactionIdentifier);
                    Debug.Log(apple.subscriptionExpirationDate);
                    Debug.Log(apple.cancellationDate);
                    Debug.Log(apple.quantity);
                }

                if (_onComplete != null)
                {
                    _onComplete("ok", google, apple);
                }
            }
        }
        catch (IAPSecurityException)
        {
            Debug.Log("Invalid receipt, not unlocking content");
            validPurchase = false;
        }
#endif

        if (validPurchase)
        {
            if (_onComplete != null)
            {
                _onComplete("failed", null, null);
            }
            // Unlock the appropriate content here.
        }

        /*
         * // A consumable product has been purchased by this user.
         * UnityEngine.Debug.Log("## ProcessPurchase >> receipt = " + args.purchasedProduct.receipt);
         *
         * if (String.Equals(args.purchasedProduct.definition.id, strProductId, StringComparison.Ordinal))
         * {
         *  UnityEngine.Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
         *  if (_onComplete != null) _onComplete(args.purchasedProduct.definition.id, args.purchasedProduct.receipt);
         * }
         * else if (_onComplete != null)
         * {
         *  _onComplete("failed", "Not Equals ProductId : " + strProductId);
         * }
         * // Return a flag indicating wither this product has completely been received, or if the application needs to be reminded of this purchase at next app launch. Is useful when saving purchased products to the cloud, and when that save is delayed.
         */
        return(PurchaseProcessingResult.Complete);
    }
Пример #16
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id + " ! " + M.COINS);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        if (e.purchasedProduct.definition.id.Contains(mIDs[0]) ||
            e.purchasedProduct.definition.id.Contains(mIDs[0]))
        {
            M.COINS += 100000;
            transform.Find("IAP/Massge/Panel/Text").GetComponent <Text> ().text = "<color=#feda49>Congratulation</color>\n\n You get 100000 coins.";
        }
        if (e.purchasedProduct.definition.id.Contains(mIDs[1]) ||
            e.purchasedProduct.definition.id.Contains(mIDs[1]))
        {
            M.isAds = false;
            transform.Find("IAP/Massge/Panel/Text").GetComponent <Text> ().text = "<color=#feda49>Congratulation</color>\n\n Now game is ads free";
            transform.Find("IAP/ADSFREE").gameObject.SetActive(M.isAds);
        }
        transform.Find("IAP/Coin/Text").GetComponent <Text> ().text = M.COINS + "";
        transform.Find("IAP/Massge").GetComponent <Animator> ().SetBool("isOpen", true);
        M.Save();
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id + " ~update~ " + M.COINS);

        m_LastTransationID   = e.purchasedProduct.transactionID;
        m_LastReceipt        = e.purchasedProduct.receipt;
        m_PurchaseInProgress = false;

                #if RECEIPT_VALIDATION
        // Local validation is available for GooglePlay and Apple stores
        if (m_IsGooglePlayStoreSelected ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer ||
            Application.platform == RuntimePlatform.tvOS)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }
                }
            } catch (IAPSecurityException) {
                Debug.Log("Invalid receipt, not unlocking content");
                return(PurchaseProcessingResult.Complete);
            }
        }
                #endif


                #if DELAY_CONFIRMATION
        StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct));
        return(PurchaseProcessingResult.Pending);
                #else
//		UpdateHistoryUI();
        return(PurchaseProcessingResult.Complete);
                #endif
    }
Пример #17
0
    void ApplyIAPPackage(string _productId, IPurchaseReceipt _productReceipt = null)
    {
        Debug.Log(">>> ApplyIAPPackage " + _productId);
        if (_productReceipt == null)
        {
            Debug.LogError(">>> _productReceipt is null");
            return;
        }
        string            _tokenPurchase = string.Empty;
        GooglePlayReceipt _google        = _productReceipt as GooglePlayReceipt;

        if (_google != null)
        {
            _tokenPurchase = _google.purchaseToken;
            // Debug.Log(google.purchaseState);
            // Debug.Log(google.purchaseToken);
        }
        AppleInAppPurchaseReceipt _apple = _productReceipt as AppleInAppPurchaseReceipt;

        if (_apple != null)
        {
            // Debug.Log(_apple.originalTransactionIdentifier);
            // Debug.Log(_apple.subscriptionExpirationDate);
            // Debug.Log(_apple.cancellationDate);
            // Debug.Log(_apple.quantity);
            _tokenPurchase = _google.purchaseToken;
        }

        if (!string.IsNullOrEmpty(_tokenPurchase))
        {
            byte _screenPurchase = (byte)IMySceneManager.Type.Home;
            if (CoreGameManager.instance.currentSceneManager != null)
            {
                _screenPurchase = (byte)CoreGameManager.instance.currentSceneManager.mySceneType;
            }

            PurchaseReceiptDetail _purchaseReceiptDetail = new PurchaseReceiptDetail(_screenPurchase, _productReceipt.transactionID, _productId, _tokenPurchase, _productReceipt.purchaseDate);
            DataManager.instance.purchaseReceiptData.AddNewPurchaseReceiptDetail(_purchaseReceiptDetail);

            SubServerDetail _serverDetail = GetGoldScreenController.instance.GetServerDetail();
            LoadingCanvasController.instance.Show(-1f, true);
            _purchaseReceiptDetail.SendMessageToServer(_serverDetail,
                                                       (_listRewarDetails) => {
                PopupManager.Instance.CreatePopupReward(_listRewarDetails);
                GetGoldScreenController.instance.RefreshMyGoldInfo(false);
                // StartCoroutine(CreatePopUpRewards(_listRewarDetails, null));
                if (GetGoldScreenController.instance.currentState == UIHomeScreenController.State.Show &&
                    GetGoldScreenController.instance.currentTab == GetGoldScreenController.Tab.BuyGold)
                {
                    ((GetGoldScreen_PanelBuyGold_Controller)GetGoldScreenController.instance.currentPanel).SetActiveIconWarningHasNewPurchase(true);
                }

                if (HomeManager.instance != null && HomeManager.instance.myCallbackManager != null &&
                    HomeManager.instance.myCallbackManager.onLoadDataGoldGemFinished != null)
                {
                    HomeManager.instance.myCallbackManager.onLoadDataGoldGemFinished();
                }
            },
                                                       () => {
                LoadingCanvasController.instance.Hide();
            });
        }
        else
        {
            Debug.LogError(">>> _tokenPurchase is null");
        }
    }
Пример #18
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        m_LastTransationID   = e.purchasedProduct.transactionID;
        m_LastReceipt        = e.purchasedProduct.receipt;
        m_PurchaseInProgress = false;

        // Decode the UnityChannelPurchaseReceipt, extracting the gameOrderId
        if (m_IsUnityChannelSelected)
        {
            var unifiedReceipt = JsonUtility.FromJson <UnifiedReceipt>(e.purchasedProduct.receipt);
            if (unifiedReceipt != null && !string.IsNullOrEmpty(unifiedReceipt.Payload))
            {
                var purchaseReceipt = JsonUtility.FromJson <UnityChannelPurchaseReceipt>(unifiedReceipt.Payload);
                Debug.LogFormat("UnityChannel receipt: storeSpecificId = {0}, transactionId = {1}, orderQueryToken = {2}",
                                purchaseReceipt.storeSpecificId, purchaseReceipt.transactionId, purchaseReceipt.orderQueryToken);
            }
        }

        #if RECEIPT_VALIDATION
        // Local validation is available for GooglePlay, Apple, and UnityChannel stores
        if (m_IsGooglePlayStoreSelected ||
            (m_IsUnityChannelSelected && m_FetchReceiptPayloadOnPurchase) ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer ||
            Application.platform == RuntimePlatform.tvOS)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    UnityChannelReceipt unityChannel = productReceipt as UnityChannelReceipt;
                    if (null != unityChannel)
                    {
                        Debug.Log(unityChannel.productID);
                        Debug.Log(unityChannel.purchaseDate);
                        Debug.Log(unityChannel.transactionID);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }

                    // For improved security, consider comparing the signed
                    // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
                    // embedded in the signed receipt objects to the data which the game is using
                    // to make this purchase.
                }
            } catch (IAPSecurityException ex) {
                Debug.Log("Invalid receipt, not unlocking content. " + ex);
                return(PurchaseProcessingResult.Complete);
            }
        }
        #endif

        // Verify remotely
        // If this game has a Game Server and is capable of Server-to-Server communication, consider
        // server-based verification, instead of client-based verification, to avoid "man in the middle"
        // security attacks.
        bool needRemoteValidation = m_IsCloudMoolahStoreSelected;

        if (needRemoteValidation)
        {
            // CloudMoolah purchase completion / finishing currently requires using the API
            // extension IMoolahExtension.RequestPayout to finish a transaction.
            if (m_IsCloudMoolahStoreSelected)
            {
                // Finish transaction with CloudMoolah server
                m_MoolahExtensions.RequestPayOut(e.purchasedProduct.transactionID,
                                                 (string transactionID, RequestPayOutState state, string message) => {
                    if (state == RequestPayOutState.RequestPayOutSucceed)
                    {
                        // Finally, finish transaction with Unity IAP's local
                        // transaction log, recording the transaction id there
                        m_Controller.ConfirmPendingPurchase(e.purchasedProduct);

                        // Unlock content here from purchases when using CloudMoolah.
                    }
                    else
                    {
                        Debug.Log("RequestPayOut: failed. transactionID: " + transactionID +
                                  ", state: " + state + ", message: " + message);
                        // Finishing failed. Retry later.
                    }
                });
            }

            return(PurchaseProcessingResult.Pending);
        }

        // Unlock content from purchases here.
#if USE_PAYOUTS
        if (e.purchasedProduct.definition.payouts != null)
        {
            Debug.Log("Purchase complete, paying out based on defined payouts");
            foreach (var payout in e.purchasedProduct.definition.payouts)
            {
                Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data));
            }
        }
#endif
        // Indicate if we have handled this purchase.
        //   PurchaseProcessingResult.Complete: ProcessPurchase will not be called
        //     with this product again, until next purchase.
        //   PurchaseProcessingResult.Pending: ProcessPurchase will be called
        //     again with this product at next app launch. Later, call
        //     m_Controller.ConfirmPendingPurchase(Product) to complete handling
        //     this purchase. Use to transactionally save purchases to a cloud
        //     game service.
#if DELAY_CONFIRMATION
        StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct));
        return(PurchaseProcessingResult.Pending);
#else
        UpdateHistoryUI();
        return(PurchaseProcessingResult.Complete);
#endif
    }
Пример #19
0
        public void ViewReceipt()
        {
            if (selectedProduct == null)
            {
                NativeUI.Alert("Alert", "Please select a product.");
                return;
            }

            #if EM_UIAP
            if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                AppleInAppPurchaseReceipt receipt = InAppPurchasing.GetAppleIAPReceipt(selectedProduct.Name);

                if (receipt != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("- Product ID: " + receipt.productID);
                    sb.Append("\n- Original Purchase Date: " + receipt.originalPurchaseDate.ToShortDateString());
                    sb.Append("\n- Original Transaction ID: " + receipt.originalTransactionIdentifier);
                    sb.Append("\n- Purchase Date: " + receipt.purchaseDate.ToShortDateString());
                    sb.Append("\n- Transaction ID: " + receipt.transactionID);
                    sb.Append("\n- Quantity: " + receipt.quantity);
                    sb.Append("\n- Cancellation Date: " + receipt.cancellationDate.ToShortDateString());
                    sb.Append("\n- Subscription Expiration Date: " + receipt.subscriptionExpirationDate.ToShortDateString());

                    ShowReceiptViewer(sb.ToString());
                }
                else
                {
                    NativeUI.Alert("Alert", "The receipt of this product could not be retrieved. Make sure the product is owned and receipt validation is enabled.");
                }
            }
            else if (Application.platform == RuntimePlatform.Android)
            {
                GooglePlayReceipt receipt = InAppPurchasing.GetGooglePlayReceipt(selectedProduct.Name);

                if (receipt != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("- Package Name: " + receipt.packageName);
                    sb.Append("\n- Product ID: " + receipt.productID);
                    sb.Append("\n- Purchase Date: " + receipt.purchaseDate.ToShortDateString());
                    sb.Append("\n- Purchase State: " + receipt.purchaseState.ToString());
                    sb.Append("\n- Transaction ID: " + receipt.transactionID);
                    sb.Append("\n- Purchase Token: " + receipt.purchaseToken);

                    ShowReceiptViewer(sb.ToString());
                }
                else
                {
                    NativeUI.Alert("Alert", "The receipt of this product could not be retrieved. Make sure the product is owned and receipt validation is enabled.");
                }
            }
            else
            {
                Debug.Log("Please test on an iOS or Android device.");
            }
            #else
            NativeUI.Alert("Alert", "Please enable Unity IAP service.");
            #endif
        }
Пример #20
0
        public SubscriptionInfo(AppleInAppPurchaseReceipt r, string intro_json)
        {
            var productType = (AppleStoreProductType)Enum.Parse(typeof(AppleStoreProductType), r.productType.ToString());

            if (productType == AppleStoreProductType.Consumable || productType == AppleStoreProductType.NonConsumable)
            {
                throw new InvalidProductTypeException();
            }

            if (!string.IsNullOrEmpty(intro_json))
            {
                var intro_wrapper = (Dictionary <string, object>)MiniJson.JsonDecode(intro_json);
                var nunit         = -1;
                var unit          = SubscriptionPeriodUnit.NotAvailable;
                this.introductory_price = intro_wrapper.TryGetString("introductoryPrice") + intro_wrapper.TryGetString("introductoryPriceLocale");
                if (string.IsNullOrEmpty(this.introductory_price))
                {
                    this.introductory_price = "not available";
                }
                else
                {
                    try {
                        this.introductory_price_cycles = Convert.ToInt64(intro_wrapper.TryGetString("introductoryPriceNumberOfPeriods"));
                        nunit = Convert.ToInt32(intro_wrapper.TryGetString("numberOfUnits"));
                        unit  = (SubscriptionPeriodUnit)Convert.ToInt32(intro_wrapper.TryGetString("unit"));
                    } catch (Exception e) {
                        Debug.unityLogger.Log("Unable to parse introductory period cycles and duration, this product does not have configuration of introductory price period", e);
                        unit = SubscriptionPeriodUnit.NotAvailable;
                    }
                }
                DateTime now = DateTime.Now;
                switch (unit)
                {
                case SubscriptionPeriodUnit.Day:
                    this.introductory_price_period = TimeSpan.FromTicks(TimeSpan.FromDays(1).Ticks *nunit);
                    break;

                case SubscriptionPeriodUnit.Month:
                    TimeSpan month_span = now.AddMonths(1) - now;
                    this.introductory_price_period = TimeSpan.FromTicks(month_span.Ticks * nunit);
                    break;

                case SubscriptionPeriodUnit.Week:
                    this.introductory_price_period = TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks *nunit);
                    break;

                case SubscriptionPeriodUnit.Year:
                    TimeSpan year_span = now.AddYears(1) - now;
                    this.introductory_price_period = TimeSpan.FromTicks(year_span.Ticks * nunit);
                    break;

                case SubscriptionPeriodUnit.NotAvailable:
                    this.introductory_price_period = TimeSpan.Zero;
                    this.introductory_price_cycles = 0;
                    break;
                }
            }
            else
            {
                this.introductory_price        = "not available";
                this.introductory_price_period = TimeSpan.Zero;
                this.introductory_price_cycles = 0;
            }

            DateTime current_date = DateTime.UtcNow;

            this.purchaseDate = r.purchaseDate;
            this.productId    = r.productID;

            this.subscriptionExpireDate = r.subscriptionExpirationDate;
            this.subscriptionCancelDate = r.cancellationDate;

            // if the product is non-renewing subscription, apple store will not return expiration date for this product
            if (productType == AppleStoreProductType.NonRenewingSubscription)
            {
                this.is_subscribed                = Result.Unsupported;
                this.is_expired                   = Result.Unsupported;
                this.is_cancelled                 = Result.Unsupported;
                this.is_free_trial                = Result.Unsupported;
                this.is_auto_renewing             = Result.Unsupported;
                this.is_introductory_price_period = Result.Unsupported;
            }
            else
            {
                this.is_cancelled     = (r.cancellationDate.Ticks > 0) && (r.cancellationDate.Ticks < current_date.Ticks) ? Result.True : Result.False;
                this.is_subscribed    = r.subscriptionExpirationDate.Ticks >= current_date.Ticks ? Result.True : Result.False;
                this.is_expired       = (r.subscriptionExpirationDate.Ticks > 0 && r.subscriptionExpirationDate.Ticks < current_date.Ticks) ? Result.True : Result.False;
                this.is_free_trial    = (r.isFreeTrial == 1) ? Result.True : Result.False;
                this.is_auto_renewing = ((productType == AppleStoreProductType.AutoRenewingSubscription) && this.is_cancelled == Result.False &&
                                         this.is_expired == Result.False) ? Result.True : Result.False;
                this.is_introductory_price_period = r.isIntroductoryPricePeriod == 1 ? Result.True : Result.False;
            }

            if (this.is_subscribed == Result.True)
            {
                this.remainedTime = r.subscriptionExpirationDate.Subtract(current_date);
            }
            else
            {
                this.remainedTime = TimeSpan.Zero;
            }
        }
Пример #21
0
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
        {
            Debug.Log("ProcessPurchase");
            bool   validPurchase = true; // Presume valid for platforms with no R.V.
            string transactionId = "";

            // Unity IAP's validation logic is only included on these platforms.
            //#if UNITY_ANDROID || UNITY_STANDALONE_OSX

#if UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE_OSX
            // Prepare the validator with the secrets we prepared in the Editor
            // obfuscation window.

            var validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);

            try
            {
                Debug.Log(args.purchasedProduct.metadata.isoCurrencyCode);
                Debug.Log(args.purchasedProduct.metadata.localizedPrice);
                Debug.Log(args.purchasedProduct.metadata.localizedPriceString);

                var result = validator.Validate(args.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);
                    transactionId = productReceipt.transactionID;
                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        // This is Google's Order ID.
                        // Note that it is null when testing in the sandbox
                        // because Google's sandbox does not provide Order IDs.
                        Debug.Log(google.transactionID);
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                        if (transactionId == "" || transactionId == null)
                        {
                            transactionId = google.transactionID;
                        }
                        if (transactionId == "" || transactionId == null)
                        {
                            transactionId = google.purchaseToken;
                        }
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                        transactionId = apple.originalTransactionIdentifier;
                    }
                    marketClass.instance.setRewardForPurchase(productReceipt.productID, transactionId, args.purchasedProduct.metadata.isoCurrencyCode, args.purchasedProduct.metadata.localizedPrice);
                }
            }
            catch (IAPSecurityException)
            {
                Debug.Log("Invalid receipt, not unlocking content");
                validPurchase = false;
                //for test on desktop
                //point
                //marketClass.instance.setRewardForPurchase(args.purchasedProduct.definition.id, transactionId, args.purchasedProduct.metadata.isoCurrencyCode, args.purchasedProduct.metadata.localizedPrice);
            }
#endif

            if (validPurchase)
            {
                // Unlock the appropriate content here.
            }



            // A consumable product has been purchased by this user.

            /*
             * if (String.Equals(args.purchasedProduct.definition.id, kProductIDConsumable, StringComparison.Ordinal))
             * {
             *  Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
             *  // The consumable item has been successfully purchased, add 100 coins to the player's in-game score.
             *  //ScoreManager.score += 100;
             * }
             * // Or ... a non-consumable product has been purchased by this user.
             * else if (String.Equals(args.purchasedProduct.definition.id, kProductIDNonConsumable, StringComparison.Ordinal))
             * {
             *  Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
             *  // TODO: The non-consumable item has been successfully purchased, grant this item to the player.
             * }
             * // Or ... a subscription product has been purchased by this user.
             * else if (String.Equals(args.purchasedProduct.definition.id, kProductIDSubscription, StringComparison.Ordinal))
             * {
             *  Debug.Log(string.Format("ProcessPurchase: PASS. Product: '{0}'", args.purchasedProduct.definition.id));
             *  // TODO: The subscription item has been successfully purchased, grant this to the player.
             * }
             * // Or ... an unknown product has been purchased by this user. Fill in additional products here....
             * else
             * {
             *
             *  Debug.Log(string.Format("ProcessPurchase: FAIL. Unrecognized product: '{0}'", args.purchasedProduct.definition.id));
             * }
             */
            // Return a flag indicating whether this product has completely been received, or if the application needs
            // to be reminded of this purchase at next app launch. Use PurchaseProcessingResult.Pending when still
            // saving purchased products to the cloud, and when that save is delayed.
            return(PurchaseProcessingResult.Complete);
        }
Пример #22
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// 这将在购买完成时调用。
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        m_LastTransactionID  = e.purchasedProduct.transactionID;
        m_PurchaseInProgress = false;

        // Decode the UnityChannelPurchaseReceipt, extracting the gameOrderId
        // 解码UnityChannelPurchaseReceipt,提取gameOrderId
        if (m_IsUnityChannelSelected)
        {
            var unifiedReceipt = JsonUtility.FromJson <UnifiedReceipt>(e.purchasedProduct.receipt);
            if (unifiedReceipt != null && !string.IsNullOrEmpty(unifiedReceipt.Payload))
            {
                var purchaseReceipt = JsonUtility.FromJson <UnityChannelPurchaseReceipt>(unifiedReceipt.Payload);
                Debug.LogFormat(
                    "UnityChannel receipt: storeSpecificId = {0}, transactionId = {1}, orderQueryToken = {2}",
                    purchaseReceipt.storeSpecificId, purchaseReceipt.transactionId, purchaseReceipt.orderQueryToken);
            }
        }

#if RECEIPT_VALIDATION // Local validation is available for GooglePlay, Apple, and UnityChannel stores
                       //本地验证可用于GooglePlay、Apple和UnityChannel商店。
        if (m_IsGooglePlayStoreSelected ||
            (m_IsUnityChannelSelected && m_FetchReceiptPayloadOnPurchase) ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer ||
            Application.platform == RuntimePlatform.tvOS)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    UnityChannelReceipt unityChannel = productReceipt as UnityChannelReceipt;
                    if (null != unityChannel)
                    {
                        Debug.Log(unityChannel.productID);
                        Debug.Log(unityChannel.purchaseDate);
                        Debug.Log(unityChannel.transactionID);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }

                    // For improved security, consider comparing the signed
                    // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
                    // embedded in the signed receipt objects to the data which the game is using
                    // to make this purchase.
                    //为了改进安全性,请考虑比较签名
                    //IPurchaseReceipt。productId IPurchaseReceipt。transactionID和其他数据
                    //嵌入到游戏正在使用的数据的已签名接收对象中
                    //做这笔交易。
                }
            } catch (IAPSecurityException ex) {
                Debug.Log("Invalid receipt, not unlocking content. " + ex);
                return(PurchaseProcessingResult.Complete);
            }
        }
#endif

        //从这里购买的内容解锁。
        // Unlock content from purchases here.
#if USE_PAYOUTS
        if (e.purchasedProduct.definition.payouts != null)
        {
            Debug.Log("Purchase complete, paying out based on defined payouts");
            foreach (var payout in e.purchasedProduct.definition.payouts)
            {
                Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data));
            }
        }
#endif
        // Indicate if we have handled this purchase.
        //   PurchaseProcessingResult.Complete: ProcessPurchase will not be called
        //     with this product again, until next purchase.
        //   PurchaseProcessingResult.Pending: ProcessPurchase will be called
        //     again with this product at next app launch. Later, call
        //     m_Controller.ConfirmPendingPurchase(Product) to complete handling
        //     this purchase. Use to transactionally save purchases to a cloud
        //     game service.
        //        //表明我们是否处理了这笔交易。
        // PurchaseProcessingResult。完成: ProcessPurchase不会被调用
        // 再用这个产品,直到下次购买。
        // PurchaseProcessingResult。待定: ProcessPurchase将被调用
        //再次使用该产品在下次应用发布会上。后来,电话
        //m_Controller.ConfirmPendingPurchase(产品)来完成处理
        //  购买。用于将购买转移到云上
        //游戏服务。
#if DELAY_CONFIRMATION
        StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct));
        return(PurchaseProcessingResult.Pending);
#else
        UpdateProductUI(e.purchasedProduct);
        return(PurchaseProcessingResult.Complete);
#endif
    }
Пример #23
0
    /// <summary>
    /// This will be called when a purchase completes.
    /// </summary>
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
    {
        Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
        Debug.Log("Receipt: " + e.purchasedProduct.receipt);

        m_PurchaseInProgress = false;

#if RECEIPT_VALIDATION // Local validation is available for GooglePlay, and Apple stores
        if (m_IsGooglePlayStoreSelected ||
            Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer ||
            Application.platform == RuntimePlatform.tvOS)
        {
            try {
                var result = validator.Validate(e.purchasedProduct.receipt);
                Debug.Log("Receipt is valid. Contents:");
                foreach (IPurchaseReceipt productReceipt in result)
                {
                    Debug.Log(productReceipt.productID);
                    Debug.Log(productReceipt.purchaseDate);
                    Debug.Log(productReceipt.transactionID);

                    GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                    if (null != google)
                    {
                        Debug.Log(google.purchaseState);
                        Debug.Log(google.purchaseToken);
                    }

                    AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                    if (null != apple)
                    {
                        Debug.Log(apple.originalTransactionIdentifier);
                        Debug.Log(apple.subscriptionExpirationDate);
                        Debug.Log(apple.cancellationDate);
                        Debug.Log(apple.quantity);
                    }

                    // For improved security, consider comparing the signed
                    // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
                    // embedded in the signed receipt objects to the data which the game is using
                    // to make this purchase.
                }
            } catch (IAPSecurityException ex) {
                Debug.Log("Invalid receipt, not unlocking content. " + ex);
                return(PurchaseProcessingResult.Complete);
            }
        }
#endif

        // Unlock content from purchases here.
#if USE_PAYOUTS
        if (e.purchasedProduct.definition.payouts != null)
        {
            Debug.Log("Purchase complete, paying out based on defined payouts");
            foreach (var payout in e.purchasedProduct.definition.payouts)
            {
                Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data));
            }
        }
#endif
        // Indicate if we have handled this purchase.
        //   PurchaseProcessingResult.Complete: ProcessPurchase will not be called
        //     with this product again, until next purchase.
        //   PurchaseProcessingResult.Pending: ProcessPurchase will be called
        //     again with this product at next app launch. Later, call
        //     m_Controller.ConfirmPendingPurchase(Product) to complete handling
        //     this purchase. Use to transactionally save purchases to a cloud
        //     game service.
#if DELAY_CONFIRMATION
        StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct));
        return(PurchaseProcessingResult.Pending);
#else
        UpdateProductUI(e.purchasedProduct);
        return(PurchaseProcessingResult.Complete);
#endif
    }
Пример #24
0
        // 支付成功处理函数;
        public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
        {
            Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);

#if RECEIPT_VALIDATION // Local validation is available for GooglePlay, Apple, and UnityChannel stores
            if (m_IsGooglePlayStoreSelected ||
                //(m_IsUnityChannelSelected && m_FetchReceiptPayloadOnPurchase) ||
                Application.platform == RuntimePlatform.IPhonePlayer ||
                Application.platform == RuntimePlatform.OSXPlayer ||
                Application.platform == RuntimePlatform.tvOS)
            {
                try
                {
                    var result = validator.Validate(e.purchasedProduct.receipt);
                    Debug.Log("Receipt is valid. Contents:");
                    foreach (IPurchaseReceipt productReceipt in result)
                    {
                        Debug.Log("UNITY IAP productID : " + productReceipt.productID);
                        Debug.Log("UNITY IAP purchaseDate : " + productReceipt.purchaseDate);
                        Debug.Log("UNITY IAP transactionID : " + productReceipt.transactionID);

                        GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
                        if (null != google)
                        {
                            Debug.Log(google.purchaseState);
                            Debug.Log(google.purchaseToken);
                        }

                        UnityChannelReceipt unityChannel = productReceipt as UnityChannelReceipt;
                        if (null != unityChannel)
                        {
                            Debug.Log(unityChannel.productID);
                            Debug.Log(unityChannel.purchaseDate);
                            Debug.Log(unityChannel.transactionID);
                        }

                        AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
                        if (null != apple)
                        {
                            Debug.Log("UNITY IAP originalTransactionIdentifier : " + apple.originalTransactionIdentifier);
                            Debug.Log("UNITY IAP subscriptionExpirationDate : " + apple.subscriptionExpirationDate);
                            Debug.Log("UNITY IAP cancellationDate : " + apple.cancellationDate);
                            Debug.Log("UNITY IAP quantity : " + apple.quantity);
                        }

                        // For improved security, consider comparing the signed
                        // IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
                        // embedded in the signed receipt objects to the data which the game is using
                        // to make this purchase.
                    }
                }
                catch (IAPSecurityException ex)
                {
                    Debug.Log("Invalid receipt, not unlocking content. " + ex);
                    return(PurchaseProcessingResult.Complete);
                }
            }
#endif

            if (null != m_Usr_ReqVerifyTransaction)
            {
                m_Usr_ReqVerifyTransaction.SafeInvoke(e.purchasedProduct.definition.id, e.purchasedProduct.receipt);
            }
            else
            {
                return(PurchaseProcessingResult.Complete);
            }

            // 我们自己后台完毕的话,通过代码设置成功(如果是不需要后台设置直接设置完毕,不要设置Pending);
            return(PurchaseProcessingResult.Pending);
        }