ホームページ  >  記事  >  ウェブフロントエンド  >  詳細: PayPal 統合パート 2: PayPal REST API

詳細: PayPal 統合パート 2: PayPal REST API

WBOY
WBOYオリジナル
2023-08-29 12:45:01822ブラウズ

深入解析:PayPal整合第二部分:PayPal REST API

このチュートリアルでは、PayPal REST API と C# を使用して支払いを行う方法を説明します。 Ruby、Node.js、Python、PHP などのさまざまな言語用に提供されるライブラリはすべて非常に似ているため、ここで説明するすべての概念はすべてのライブラリに適用できます。

プロジェクト設定

まず、Visual Studio 2015 で MVC プロジェクトを作成しました: [ファイル] > [新規] > [プロジェクト] を選択し、ASP.NET アプリケーション を選択しました。

深入解析:PayPal整合第二部分:PayPal REST API

新しい MVC 6 を使用する ASP.NET 5 Web アプリケーション テンプレートを選択します。 MVC 5 に慣れている場合は、MVC 5 に似ています。

深入解析:PayPal整合第二部分:PayPal REST API

下の写真からわかるように、ソリューションにいくつかのファイルとフォルダーを追加しました。注意すべき主な点は次の 2 つです:

  1. 参照では、ターゲットの DNX Core 5.0 を削除しました。これにより、このプロジェクトを Mac OS X または Linux で実行できるようになりますが、必要な PayPal ライブラリはまだ更新されていません。
  2. コントローラーをクリーンかつシンプルに保つために、PayPal 呼び出しのロジックをカプセル化する「Services」フォルダーを追加しました。

深入解析:PayPal整合第二部分:PayPal REST API

NuGet を使用して PayPal SDK をインストールします。 ソリューション名を右クリックし、NuGetパッケージの管理を選択し、「PayPal」を検索してインストールします。

深入解析:PayPal整合第二部分:PayPal REST API

PayPal アプリの作成

アプリケーションを PayPal と統合するには、PayPal Developers に移動し、

REST API アプリケーションCreate Application をクリックする必要があります。

深入解析:PayPal整合第二部分:PayPal REST API

アプリに名前を付け、アプリに関連付けるサンドボックス開発者アカウントを選択します。テストの目的で、http://sandbox.paypal.com に移動し、サンドボックスのログイン詳細を使用してログインし、テスト用の PayPal アカウントとトランザクションを表示できます。

深入解析:PayPal整合第二部分:PayPal REST API

[アプリケーションの作成] をクリックすると、クライアント ID とシークレット トークンを含む確認画面が表示されます。

深入解析:PayPal整合第二部分:PayPal REST API以下のスクリーンショットに示すように、clientId トークンと clientSecret トークンを

appsettings.json

にコピーします。

テスト支払い深入解析:PayPal整合第二部分:PayPal REST API

PayPal はテスト用のサンドボックス環境を提供します。そこから、テストの購入者アカウントと販売者アカウントを作成できます。サインアップすると、開発者アカウントに関連付けられたサンドボックス内のエンタープライズ アカウントが作成されます。

新しいテスト アカウントを作成するには、開発者 Web サイトにログインし、

コントロール パネル

タブをクリックして、

サンドボックス > アカウントに移動します。 ここでテスト アカウントのリスト (利用可能な場合) を確認できます:

テスト アカウントをまだ作成していない場合は、[深入解析:PayPal整合第二部分:PayPal REST APIアカウントの作成] をクリックしてください。

右上隅で、少なくとも 1 つのテスト用個人アカウントと 1 つのテスト用個人アカウントを作成します。ビジネスアカウントのテスト。

テスト アカウントを作成した後、前のフォームで各アカウントに割り当てたテスト電子メール アドレスとパスワードを使用して、www.sandbox.paypal.com からログインできます。これは、個人テスト アカウントを使用して購入するときに、資金がテスト ビジネス アカウントに転送されるかどうかをテストするのに役立ちます。これで、PayPal との統合を開始し、あるアカウントから別のアカウントに資金が転送されるかどうかをテストする準備が整いました。 深入解析:PayPal整合第二部分:PayPal REST API

単一PayPal支払い

PayPal はさまざまな支払い方法を提供しています。直接クレジット カード支払いを使用できます。つまり、顧客は PayPal のログイン ページや概要を見ることができません。すべてが Web サイト上で行われます。これを行うには、PCI に準拠する必要があります。JavaScript ライブラリを使用する SSL のみが必要なため、Stripe を使用することをお勧めします。一方、PayPal 経由で支払うには、次の 3 つの手順があります:

  1. 支払い情報を指定して 支払いを作成します。
  2. 支払い承認の取得 取引を承認するために顧客を PayPal にリダイレクトします。
  3. PayPal が顧客を Web サイトにリダイレクトした後、支払いを実行して資金を受け取ります。

MVC プロジェクトの Services フォルダーで、PayPalPaymentService クラスを作成し、そこに次のメソッドを追加しました。 リーリー

この呼び出しではいくつかのパラメータが渡されます:

Intent
    : 3 つの可能な値: 即時支払いの場合は「sales」、後で支払いを取得する権限の場合は「authorization」、または注文を作成する場合は「order」。後で支払いを請求することが
  • 承認 されている場合、3 日間の保証がありますが、最大 29 日後までは支払いの回収を試みることができます。 Payer
  • : この支払いの資金源、使用された支払い方法 - PayPal ウォレット支払い、銀行口座引き落とし、または直接クレジット カード。
  • Transaction:
  • は、支払い金額を指定し、オプションで支払うアイテムを指定するために使用されます。必要に応じて、小計、配送料、税金を指定することもできます。
  • リダイレクト URL
  • : データベースを更新して確認メッセージを表示できるように、取引後に PayPal が顧客をリダイレクトする URL を指定します。
  • 以前の機能は、次のようにコントローラーから使用できます。
  • リーリー
ご覧のとおり、3 つのアクションを作成しました:

CreatePayment
    : これは支払いをトリガーするアクションです。 PayPal を呼び出して支払いを作成し、ユーザーを PayPal にリダイレクトしてトランザクションを承認します。
  • 支払い成功
  • : これは、支払いが成功した後に PayPal が顧客をリダイレクトするために行うことです。この時点で、支払いを実行し、資金を販売者アカウントに送金できます。
  • PaymentCancelled
  • : ユーザーが承認プロセスをキャンセルした場合、ユーザーを PayPal からこのアクションにリダイレクトします。この時点で、顧客にもう一度試すか連絡するかの選択肢を与えるとよいでしょう。
  • 支払いを承認して後で受け取ることを許可します

このシナリオは前のケースと非常によく似ています。まだ入手できない製品を予約注文しようとしている場合は、この方法を使用するとよいでしょう。この支払いを受け取る手順は次のとおりです:

支払いの承認:
    この呼び出しの「intent」パラメータは「authorize」である必要があります。
  1. 支払いの受け取り:
  2. 承認は最大 3 日間保証されていますが、最大 29 日間支払いを受け取ることができることに注意してください。
  3. このタイプの支払いを実装するために、PayPalPaymentService クラスに支払いをキャプチャする新しいメソッドを追加しました。
  4. リーリー
次に、このタイプの支払いを表示するために HomeController に 2 つの新しいアクションを追加しました。 リーリー

AuthorizePayment

は、支払いをトリガーするアクションです。これは前の「CreatePayment」関数とよく似ていますが、この場合は「authorize」をインテントパラメータとして渡します。
  • AuthorizeSuccessful は、PayPal 支払いが正常に承認された後に顧客をリダイレクトするアクションです。この時点では支払いをキャプチャしていますが、paymentId をデータベースに保存し、必要に応じて支払いをキャプチャすることもできます。
  • これらのコード例では、わかりやすくするために支払い変数の値をハードコーディングしています。実際のアプリケーションでは、これらすべての値を変数として受け取るメソッドでラップして、すべてを動的に設定して再利用できるようにするでしょう。 ###サブスクリプション###
  • これは PayPal では「請求プラン」と呼ばれます。請求契約を作成することで、定期的な支払いプランを作成し、顧客を請求プランに加入させることができます。 PayPal REST API を使用すると、請求プランを作成、更新、または削除できます。これは、ビジネス用にこれらを管理する管理パネルを構築したい場合に使用できます。

顧客への定期的な請求を作成する手順は次のとおりです:

料金プランを作成

し、

アクティブ化します

。料金プランを作成すると、ステータスが「作成済み」になります。 PATCH リクエストを発行してアクティブ化する必要があります。
  1. 和解契約の作成および実行: 「和解契約の作成」呼び出しに対する応答には、approval_urlおよびexecute_urlへのリンクが含まれています。請求契約の承認を得てから、請求契約を実行する必要があります。
  2. 料金プラン 料金プランの作成
  3. 請求サイクルを定義する請求プランを作成します。これは、プランの作成時に渡す必要があるパラメーターの概要です。
  • 名称:计费计划的名称。
  • 说明:计费计划的说明。
  • 类型:对于固定次数的定期付款,允许的值为“FIXED”;对于手动取消之前重复的计划,允许的值为“INFINITE”。
  • 商户首选项:这是一个指定首选项的对象,例如设置费用、付款的最大失败尝试次数、返回 URL、取消 URL、通知 URL,PayPal 在付款后将在其中重定向用户。李>
  • 付款定义:此计划的付款定义数组。通常,该数组将具有一两个付款定义。如果我们想提供免费试用或折扣价格试用,那么我们会设置两种付款定义。第一个定义是试用期,第二个定义是定期付款。付款定义的属性包括名称类型(试用或常规)、频率(日、周、月、年)、 >频率间隔(如果我们将频率设置为“周”并将频率间隔设置为“1”,则我们定义每周付款)、向客户收费的金额,以及cycles 是总付款次数。 收费模式用于指定计划金额之外的运费和税费。

这是一个代码片段,展示了如何创建计费计划:

// Define the plan and attach the payment definitions and merchant preferences.
// More Information: https://developer.paypal.com/webapps/developer/docs/api/#create-a-plan
var billingPlan = new Plan
{
    name = "Tuts+ Plus",
    description = "Monthly plan for courses.",
    type = "fixed",
    // Define the merchant preferences.
    // More Information: https://developer.paypal.com/webapps/developer/docs/api/#merchantpreferences-object
    merchant_preferences = new MerchantPreferences()
    {
        setup_fee = GetCurrency("0"), // $0
        return_url = "returnURL", // Retrieve from config
        cancel_url = "cancelURL", // Retrieve from config
        auto_bill_amount = "YES",
        initial_fail_amount_action = "CONTINUE",
        max_fail_attempts = "0"
    },
    payment_definitions = new List<PaymentDefinition>
    {
        // Define a trial plan that will only charge $9.99 for the first
        // month. After that, the standard plan will take over for the
        // remaining 11 months of the year.
        new PaymentDefinition()
        {
            name = "Trial Plan",
            type = "TRIAL",
            frequency = "MONTH",
            frequency_interval = "1",
            amount = GetCurrency("0"), // Free for the 1st month
            cycles = "1",
            charge_models = new List<ChargeModel>
            {
                new ChargeModel()
                {
                    type = "TAX",
                    amount = GetCurrency("1.65") // If we need to charge Tax
                },
                new ChargeModel()
                {
                    type = "SHIPPING",
                    amount = GetCurrency("9.99") // If we need to charge for Shipping
                }
            }
        },
        // Define the standard payment plan. It will represent a monthly
        // plan for $19.99 USD that charges once month for 11 months.
        new PaymentDefinition
        {
            name = "Standard Plan",
            type = "REGULAR",
            frequency = "MONTH",
            frequency_interval = "1",
            amount = GetCurrency("15.00"),
            // > NOTE: For `IFNINITE` type plans, `cycles` should be 0 for a `REGULAR` `PaymentDefinition` object.
            cycles = "11",
            charge_models = new List<ChargeModel>
            {
                new ChargeModel
                {
                    type = "TAX",
                    amount = GetCurrency("2.47")
                },
                new ChargeModel()
                {
                    type = "SHIPPING",
                    amount = GetCurrency("9.99")
                }
            }
        }
    }
};

// Get PayPal Config
var apiContext = PayPalConfiguration.GetAPIContext();

// Create Plan
plan.Create(apiContext);

新创建的结算计划处于 CREATED 状态。将其激活为“活动”状态,以便您的客户可以订阅该计划。要激活该计划,我们需要发出 PATCH 请求:

// Activate the plan
var patchRequest = new PatchRequest()
{
    new Patch()
    {
        op = "replace",
        path = "/",
        value = new Plan() { state = "ACTIVE" }
    }
};
plan.Update(apiContext, patchRequest);

如您所见,PayPal 库是其 REST API 的直接包装器,这很好,但与 Stripe 等其他 API 相比,该 API 也非常复杂。因此,将所有 PayPal 通信包装在对象中,为我们的应用程序提供更清晰、更简单的 API,这确实是一个不错的选择。在这里您可以看到封装在多个带有参数的函数中的代码的样子:

public static Plan CreatePlanObject(string planName, string planDescription, string returnUrl, string cancelUrl,
    string frequency, int frequencyInterval, decimal planPrice,
    decimal shippingAmount = 0, decimal taxPercentage = 0, bool trial = false, int trialLength = 0, decimal trialPrice = 0)
{
    // Define the plan and attach the payment definitions and merchant preferences.
    // More Information: https://developer.paypal.com/docs/rest/api/payments.billing-plans/
    return new Plan
    {
        name = planName,
        description = planDescription,
        type = PlanType.Fixed,

        // Define the merchant preferences.
        // More Information: https://developer.paypal.com/webapps/developer/docs/api/#merchantpreferences-object
        merchant_preferences = new MerchantPreferences()
        {
            setup_fee = GetCurrency("1"),
            return_url = returnUrl,
            cancel_url = cancelUrl,
            auto_bill_amount = "YES",
            initial_fail_amount_action = "CONTINUE",
            max_fail_attempts = "0"
        },
        payment_definitions = GetPaymentDefinitions(trial, trialLength, trialPrice, frequency, frequencyInterval, planPrice, shippingAmount, taxPercentage)
    };
}

private static List<PaymentDefinition> GetPaymentDefinitions(bool trial, int trialLength, decimal trialPrice,
    string frequency, int frequencyInterval, decimal planPrice, decimal shippingAmount, decimal taxPercentage)
{
    var paymentDefinitions = new List<PaymentDefinition>();

    if (trial)
    {
        // Define a trial plan that will charge 'trialPrice' for 'trialLength'
        // After that, the standard plan will take over.
        paymentDefinitions.Add(
            new PaymentDefinition()
            {
                name = "Trial",
                type = "TRIAL",
                frequency = frequency,
                frequency_interval = frequencyInterval.ToString(),
                amount = GetCurrency(trialPrice.ToString()),
                cycles = trialLength.ToString(),
                charge_models = GetChargeModels(trialPrice, shippingAmount, taxPercentage)
            });
    }

    // Define the standard payment plan. It will represent a 'frequency' (monthly, etc)
    // plan for 'planPrice' that charges 'planPrice' (once a month) for #cycles.
    var regularPayment = new PaymentDefinition
    {
        name = "Standard Plan",
        type = "REGULAR",
        frequency = frequency,
        frequency_interval = frequencyInterval.ToString(),
        amount = GetCurrency(planPrice.ToString()),
        // > NOTE: For `IFNINITE` type plans, `cycles` should be 0 for a `REGULAR` `PaymentDefinition` object.
        cycles = "11",
        charge_models = GetChargeModels(trialPrice, shippingAmount, taxPercentage)
    };
    paymentDefinitions.Add(regularPayment);

    return paymentDefinitions;
}

private static List<ChargeModel> GetChargeModels(decimal planPrice, decimal shippingAmount, decimal taxPercentage)
{
    // Create the Billing Plan
    var chargeModels = new List<ChargeModel>();
    if (shippingAmount > 0)
    {
        chargeModels.Add(new ChargeModel()
        {
            type = "SHIPPING",
            amount = GetCurrency(shippingAmount.ToString())
        });
    }
    if (taxPercentage > 0)
    {
        chargeModels.Add(new ChargeModel()
        {
            type = "TAX",
            amount = GetCurrency(String.Format("{0:f2}", planPrice * taxPercentage / 100))
        });
    }

    return chargeModels;
}

更新结算计划

您可以通过提出“PATCH”请求来更新现有结算方案的信息。这是一个包装该调用的函数:

public static void UpdateBillingPlan(string planId, string path, object value)
{
    // PayPal Authentication tokens
    var apiContext = PayPalConfiguration.GetAPIContext();

    // Retrieve Plan
    var plan = Plan.Get(apiContext, planId);

    // Activate the plan
    var patchRequest = new PatchRequest()
    {
        new Patch()
        {
            op = "replace",
            path = path,
            value = value
        }
    };
    plan.Update(apiContext, patchRequest);
}

要更新计费计划描述,我们可以调用此函数并传递正确的参数:

UpdateBillingPlan(
    planId: "P-5FY40070P6526045UHFWUVEI", 
    path: "/", 
    value: new Plan { description = "new description" });

删除结算计划

理想情况下,当您不想接受新客户加入结算计划时,您需要将其更新为“非活动”状态。这不会影响该计划的现有计费协议。只需调用 UpdateBillingPlan 函数即可完成此操作:

UpdateBillingPlan(
    planId: "P-5FY40070P6526045UHFWUVEI",
    path: "/",
    value: new Plan { state = "INACTIVE" });

计费协议

创建计费协议

创建一个或多个结算计划后,您希望开始让客户注册您的订阅计划。为此,您需要收集客户详细信息并向 PayPal 提出请求。为了能够测试此功能,我向 HomeController 添加了几个操作:

public IActionResult Subscribe()
{
    var plan = PayPalSubscriptionsService.CreateBillingPlan("Tuts+ Plan", "Test plan for this article", GetBaseUrl());

    var subscription = PayPalSubscriptionsService.CreateBillingAgreement(plan.id, 
        new PayPal.Api.ShippingAddress
        {
            city = "London", 
            line1 = "line 1",
            postal_code = "SW1A 1AA",
            country_code = "GB"
        }, "Pedro Alonso", "Tuts+", DateTime.Now);
    
    return Redirect(subscription.GetApprovalUrl());
}

public IActionResult SubscribeSuccess(string token)
{
    // Execute approved agreement
    PayPalSubscriptionsService.ExecuteBillingAgreement(token);

    return View();
}

public IActionResult SubscribeCancel(string token)
{
    // TODO: Handle cancelled payment
    return RedirectToAction("Error");
}
  • 订阅:这是调用的第一个操作。它正在创建一个测试结算计划,然后创建该计划的结算协议(订阅),并将用户重定向到 PayPal 以确认付款。
  • 订阅成功:此操作是成功订阅后用作“返回 URL”的操作。协议令牌标识符在查询字符串中传递,我们使用此令牌来执行计费协议并使其处于活动状态。
  • SubscribeCancel: 此操作用作“取消 URL”。如果由于某种原因付款失败,或者您的客户取消了 PayPal 付款,用户将采取此操作,您需要处理此问题。也许可以提供重试的选项。

正如您在前面的代码片段中看到的,我已将大部分功能包装在几个方法中。第一个是上一节中解释的“CreateBillingPlan”。第二个是“CreateBillingAgreement”,用于为用户订阅计划:

public static Agreement CreateBillingAgreement(string planId, ShippingAddress shippingAddress, 
    string name, string description, DateTime startDate)
{
    // PayPal Authentication tokens
    var apiContext = PayPalConfiguration.GetAPIContext();

    var agreement = new Agreement()
    {
        name = name,
        description = description,
        start_date = startDate.ToString("yyyy-MM-ddTHH:mm:ss") + "Z",
        payer = new Payer() { payment_method = "paypal" },
        plan = new Plan() { id = planId },
        shipping_address = shippingAddress
    };
    
    var createdAgreement = agreement.Create(apiContext);
    return createdAgreement;
}

第三种方法是“ExecuteBillingAgreement”。成功订阅批准后,我们​​使用返回的令牌来激活订阅:

public static void ExecuteBillingAgreement(string token)
{
    // PayPal Authentication tokens
    var apiContext = PayPalConfiguration.GetAPIContext();

    var agreement = new Agreement() { token = token };
    var executedAgreement = agreement.Execute(apiContext);
}

暂停计费协议

使用此方法暂停协议:

public static void SuspendBillingAgreement(string agreementId)
{
    var apiContext = PayPalConfiguration.GetAPIContext();

    var agreement = new Agreement() { id = agreementId };
    agreement.Suspend(apiContext, new AgreementStateDescriptor()
        { note = "Suspending the agreement" });
}

重新激活计费协议

这个与上一个非常相似:

public static void ReactivateBillingAgreement(string agreementId)
{
    var apiContext = PayPalConfiguration.GetAPIContext();

    var agreement = new Agreement() { id = agreementId };
    agreement.ReActivate(apiContext, new AgreementStateDescriptor()
        { note = "Reactivating the agreement" });
}

取消计费协议

使用此功能取消计划:

public static void CancelBillingAgreement(string agreementId)
{
    var apiContext = PayPalConfiguration.GetAPIContext();

    var agreement = new Agreement() { id = agreementId };
    agreement.Cancel(apiContext, new AgreementStateDescriptor()
        { note = "Cancelling the agreement" });
}

更新计费协议

这个选项非常有限,我希望从这次通话中可以更改订阅计划,以升级或降级客户。与 Stripe 不同,单次调用不支持此功能。您需要通过取消当前协议并创建新的升级或降级协议来处理这种情况。这并不理想,但将来可能会改变。

结论

这是人们用来与 PayPal 集成的最常用功能的概述。他们的 API 比本文中解释的集成方法要大得多 - 您还可以发放退款和部分退款,并且他们针对本文涵盖的示例中的边缘情况提供了许多不同的选项。如果您有兴趣获得有关任何特定集成的更多详细信息,请在评论中留下建议。

以上が詳細: PayPal 統合パート 2: PayPal REST APIの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。