Przejdź do treści stopki
POMOC .NET

Stripe .NET (jak to działa dla programistów)

Integracja Stripe.Net z IronPDF

Stripe.Net is a powerful .NET library that allows developers to integrate Stripe's payment processing capabilities into .NET applications. Stripe is a popular payment gateway that enables businesses to accept payments online. With Stripe.Net, developers can manage transactions, customers, subscriptions, and more using the robust features provided by the Stripe API. W tym artykule omówimy, jak korzystać ze Stripe w połączeniu z IronPDF do tworzenia plików PDF.

Pierwsze kroki ze Stripe.Net

Create a New Visual Studio Project

To get started with Stripe.Net, we need to create a new Visual Studio project or open an existing one. W tym samouczku wykorzystamy projekt aplikacji konsolowej.

  1. Open Visual Studio and click on "Create a New Project".

    Stripe .NET (How It Works For Developers): Figure 1 - Open Visual Studio and click on Create a new project option.

  2. Pojawi się nowe okno. Wybierz opcję Aplikacja konsolowa i kliknij Dalej.

    Stripe .NET (Jak to działa dla programistów): Rysunek 2 – Wybierz aplikację konsolową C# jako typ projektu. Kliknij Dalej.

  3. W kolejnym oknie wprowadź nazwę projektu i wybierz lokalizację, a następnie kliknij Dalej.

    Stripe .NET (Jak to działa dla programistów): Rysunek 3 – Skonfiguruj swój projekt, podając nazwę projektu, lokalizację i nazwę rozwiązania. Następnie kliknij Dalej.

  4. W kolejnym oknie wybierz framework i kliknij Utwórz.

    Stripe .NET (How It Works For Developers): Figure 4 - Select the appropriate .NET Framework for your project and click on Create.

W ten sposób tworzony jest nowy projekt aplikacji konsolowej Visual Studio.

Instalacja

To start using Stripe.Net in your project, you need to install the Stripe.Net package via NuGet. Można to zrobić za pomocą konsoli menedżera pakietów lub menedżera pakietów NuGet w programie Visual Studio.

Korzystanie z konsoli menedżera pakietów:

Install-Package Stripe.net

Lub

dotnet add package Stripe.net

Za pomocą menedżera pakietów NuGet wyszukaj "Stripe.net" i zainstaluj pakiet.

Configuration

Po zainstalowaniu należy skonfigurować klucz API Stripe, który można znaleźć na koncie Stripe. Ten klucz jest niezbędny do uwierzytelniania żądań kierowanych do API Stripe. Zazwyczaj klucz ten jest przechowywany w pliku konfiguracyjnym lub zmiennej środowiskowej ze względów bezpieczeństwa.

Oto przykład konfiguracji klucza API:

StripeConfiguration.ApiKey = "your_secret_api_key";
StripeConfiguration.ApiKey = "your_secret_api_key";
StripeConfiguration.ApiKey = "your_secret_api_key"
$vbLabelText   $csharpLabel

Podstawowe operacje w Stripe.Net

Tworzenie klienta

Creating a customer is one of the fundamental operations when working with Stripe.Net. Klienci mogą być powiązani z metodami płatności i subskrypcjami.

var options = new CustomerCreateOptions
{
    Email = "customer@example.com",
    Name = "John Doe",
};
var service = new CustomerService();
Customer customer = service.Create(options);
var options = new CustomerCreateOptions
{
    Email = "customer@example.com",
    Name = "John Doe",
};
var service = new CustomerService();
Customer customer = service.Create(options);
Dim options = New CustomerCreateOptions With {
	.Email = "customer@example.com",
	.Name = "John Doe"
}
Dim service = New CustomerService()
Dim customer As Customer = service.Create(options)
$vbLabelText   $csharpLabel

Wynik: Pulpit nawigacyjny Stripe

Stripe .NET (How It Works For Developers): Figure 5 - Stripe Dashboard for Customers

Tworzenie intencji płatności

A PaymentIntent is an object that represents a payment process in Stripe. It is designed to track the lifecycle of a payment from creation through completion.

var options = new PaymentIntentCreateOptions
{
    Amount = 2000,
    Currency = "usd",
    PaymentMethodTypes = new List<string>
    {
        "card",
    },
};
var service = new PaymentIntentService();
PaymentIntent paymentIntent = service.Create(options);
var options = new PaymentIntentCreateOptions
{
    Amount = 2000,
    Currency = "usd",
    PaymentMethodTypes = new List<string>
    {
        "card",
    },
};
var service = new PaymentIntentService();
PaymentIntent paymentIntent = service.Create(options);
Dim options = New PaymentIntentCreateOptions With {
	.Amount = 2000,
	.Currency = "usd",
	.PaymentMethodTypes = New List(Of String) From {"card"}
}
Dim service = New PaymentIntentService()
Dim paymentIntent As PaymentIntent = service.Create(options)
$vbLabelText   $csharpLabel

Stripe .NET (How It Works For Developers): Figure 6 - Stripe Payment Intent

Zaawansowane funkcje

Subskrypcje

Stripe supports various subscription models, and managing subscriptions via Stripe.Net is straightforward. Możesz tworzyć, aktualizować i anulować subskrypcje.

var options = new SubscriptionCreateOptions
{
    Customer = "cus_123456789",
    Items = new List<SubscriptionItemOptions>
    {
        new SubscriptionItemOptions
        {
            Plan = "plan_123456789",
        },
    },
};
var service = new SubscriptionService();
Subscription subscription = service.Create(options);
var options = new SubscriptionCreateOptions
{
    Customer = "cus_123456789",
    Items = new List<SubscriptionItemOptions>
    {
        new SubscriptionItemOptions
        {
            Plan = "plan_123456789",
        },
    },
};
var service = new SubscriptionService();
Subscription subscription = service.Create(options);
Dim options = New SubscriptionCreateOptions With {
	.Customer = "cus_123456789",
	.Items = New List(Of SubscriptionItemOptions) From {
		New SubscriptionItemOptions With {.Plan = "plan_123456789"}
	}
}
Dim service = New SubscriptionService()
Dim subscription As Subscription = service.Create(options)
$vbLabelText   $csharpLabel

Stripe .NET (How It Works For Developers): Figure 7 - Stripe Subscription Service

Rozstrzyganie sporów

Spory mają miejsce, gdy klient kwestionuje opłatę w swoim banku lub firmie obsługującej kartę kredytową. Stripe.Net allows you to list, retrieve, and respond to disputes.

var service = new DisputeService();
Dispute dispute = service.Get("dp_123456789");
var service = new DisputeService();
Dispute dispute = service.Get("dp_123456789");
Dim service = New DisputeService()
Dim dispute As Dispute = service.Get("dp_123456789")
$vbLabelText   $csharpLabel

Najlepsze praktyki

  1. Bezpieczeństwo: Zawsze zabezpieczaj swoje klucze API i nigdy nie zapisuj ich na stałe w plikach źródłowych.
  2. Obsługa błędów: Wprowadź solidną obsługę błędów w celu zarządzania wyjątkami i nieudanymi wywołaniami API.
  3. Testowanie: Skorzystaj z trybu testowego Stripe i podaj numery kart testowych, aby dokładnie przetestować integrację.
  4. Documentation: Refer to the official Stripe API documentation and the Stripe.Net library documentation for up-to-date information and examples.

Introducing IronPDF for C

Stripe .NET (How It Works For Developers): Figure 8 - IronPDF for .NET: The C# PDF Library

IronPDF is a C# library that allows developers to create, edit, and extract content from PDF documents. Jest to idealne narzędzie do generowania plików PDF w aplikacjach .NET, zarówno w przypadku raportów, faktur, jak i innych potrzeb związanych z dokumentacją.

IronPDF może dokładnie konwertować strony internetowe, adresy URL i kod HTML do formatu PDF, co czyni go idealnym narzędziem do tworzenia dokumentów PDF z treści internetowych, takich jak raporty i faktury.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Najważniejsze cechy

1. HTML do PDF

IronPDF pozwala programistom na łatwe tworzenie dokumentów PDF poprzez konwersję ciągów znaków HTML, adresów URL i plików HTML do formatu PDF.

2. Edycja plików PDF

Z łatwością edytuj istniejące dokumenty PDF. IronPDF umożliwia manipulowanie istniejącymi plikami PDF, pozwalając użytkownikom dodawać strony w określonych miejscach, kopiować lub usuwać strony, dzielić pliki PDF oraz wyodrębniać strony w celu tworzenia nowych plików PDF itp.

3. Łączenie plików PDF

Funkcja scalania IronPDF pozwala programistom łączyć dwa lub więcej dokumentów PDF w jeden.

4. Zabezpieczenia plików PDF

IronPDF umożliwia użytkownikom dodawanie haseł i uprawnień do plików PDF w celu zwiększenia ich bezpieczeństwa.

5. Szyfrowanie i deszyfrowanie plików PDF

IronPDF obsługuje 128-bitowe szyfrowanie, deszyfrowanie oraz ochronę hasłem dokumentów PDF.

6. Podpisywanie cyfrowym podpisem dokumentu PDF

Programiści mogą programowo dodawać podpisy cyfrowe do plików PDF za pomocą IronPDF. It supports multiple ways to sign a PDF with a digital signature certificate of .pfx and .p12 formats.

Przykład: Generowanie faktury w formacie PDF za pomocą Stripe.Net i IronPDF

Let's create a practical example where we generate a PDF invoice using IronPDF after processing a payment with Stripe.Net.

Zainstaluj bibliotekę IronPDF .NET

Kroki instalacji IronPDF przy użyciu menedżera pakietów NuGet:

  1. Otwórz projekt ASP.NET w programie Visual Studio i przejdź do menu "Narzędzia".
  2. Wybierz "NuGet Package Manager", a następnie kliknij "Manage NuGet Packages for Solution".
  3. W zakładce "Przeglądaj" wyszukaj "IronPDF" i wybierz żądaną wersję. Kliknij "Zainstaluj", aby dodać pakiet do swojego projektu. IronPDF i jego zależności zostaną automatycznie pobrane i zintegrowane, co pozwoli na płynne wykorzystanie jego funkcjonalności w aplikacji ASP.NET.

    Stripe .NET (How It Works For Developers): Figure 9 - Install IronPDF using the Manage NuGet Package for Solution by searching IronPDF in the search bar of NuGet Package Manager, then select the project and click on the Install button.

Przetwarzanie płatności i generowanie faktur

Here's a complete example that demonstrates creating a new payment with Stripe.Net API and generating a PDF invoice with IronPDF.

using Stripe;
using IronPdf;
using System;
using System.Collections.Generic;

public class PaymentService
{
    public void ProcessPaymentAndGenerateInvoice()
    {
        // Configure Stripe API key
        StripeConfiguration.ApiKey = "your_secret_key";

        // Create a PaymentIntent
        var paymentIntentOptions = new PaymentIntentCreateOptions
        {
            Amount = 2000, // Amount in cents
            Currency = "usd",
            PaymentMethodTypes = new List<string> { "card" },
        };
        var paymentIntentService = new PaymentIntentService();
        PaymentIntent paymentIntent = paymentIntentService.Create(paymentIntentOptions);

        // Assuming payment succeeded, create a PDF invoice
        GeneratePdfInvoice(paymentIntent);
    }

    private void GeneratePdfInvoice(PaymentIntent paymentIntent)
    {
        // Create HTML content for the invoice
        var htmlContent = $@"
        <html>
        <head>
            <title>Invoice</title>
        </head>
        <body>
            <h1>Invoice</h1>
            <p>Payment ID: {paymentIntent.Id}</p>
            <p>Amount: {paymentIntent.Amount / 100.0:C}</p>
            <p>Status: {paymentIntent.Status}</p>
        </body>
        </html>";

        // Convert the HTML content to a PDF document
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document to a file
        var filePath = "invoice.pdf";
        pdfDocument.SaveAs(filePath);
        Console.WriteLine($"Invoice saved to {filePath}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new PaymentService();
        service.ProcessPaymentAndGenerateInvoice();
    }
}
using Stripe;
using IronPdf;
using System;
using System.Collections.Generic;

public class PaymentService
{
    public void ProcessPaymentAndGenerateInvoice()
    {
        // Configure Stripe API key
        StripeConfiguration.ApiKey = "your_secret_key";

        // Create a PaymentIntent
        var paymentIntentOptions = new PaymentIntentCreateOptions
        {
            Amount = 2000, // Amount in cents
            Currency = "usd",
            PaymentMethodTypes = new List<string> { "card" },
        };
        var paymentIntentService = new PaymentIntentService();
        PaymentIntent paymentIntent = paymentIntentService.Create(paymentIntentOptions);

        // Assuming payment succeeded, create a PDF invoice
        GeneratePdfInvoice(paymentIntent);
    }

    private void GeneratePdfInvoice(PaymentIntent paymentIntent)
    {
        // Create HTML content for the invoice
        var htmlContent = $@"
        <html>
        <head>
            <title>Invoice</title>
        </head>
        <body>
            <h1>Invoice</h1>
            <p>Payment ID: {paymentIntent.Id}</p>
            <p>Amount: {paymentIntent.Amount / 100.0:C}</p>
            <p>Status: {paymentIntent.Status}</p>
        </body>
        </html>";

        // Convert the HTML content to a PDF document
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Save the PDF document to a file
        var filePath = "invoice.pdf";
        pdfDocument.SaveAs(filePath);
        Console.WriteLine($"Invoice saved to {filePath}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new PaymentService();
        service.ProcessPaymentAndGenerateInvoice();
    }
}
Imports Stripe
Imports IronPdf
Imports System
Imports System.Collections.Generic

Public Class PaymentService
	Public Sub ProcessPaymentAndGenerateInvoice()
		' Configure Stripe API key
		StripeConfiguration.ApiKey = "your_secret_key"

		' Create a PaymentIntent
		Dim paymentIntentOptions = New PaymentIntentCreateOptions With {
			.Amount = 2000,
			.Currency = "usd",
			.PaymentMethodTypes = New List(Of String) From {"card"}
		}
		Dim paymentIntentService As New PaymentIntentService()
		Dim paymentIntent As PaymentIntent = paymentIntentService.Create(paymentIntentOptions)

		' Assuming payment succeeded, create a PDF invoice
		GeneratePdfInvoice(paymentIntent)
	End Sub

	Private Sub GeneratePdfInvoice(ByVal paymentIntent As PaymentIntent)
		' Create HTML content for the invoice
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
		Dim htmlContent = $"
        <html>
        <head>
            <title>Invoice</title>
        </head>
        <body>
            <h1>Invoice</h1>
            <p>Payment ID: {paymentIntent.Id}</p>
            <p>Amount: {paymentIntent.Amount / 100.0:C}</p>
            <p>Status: {paymentIntent.Status}</p>
        </body>
        </html>"

		' Convert the HTML content to a PDF document
		Dim renderer = New ChromePdfRenderer()
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

		' Save the PDF document to a file
		Dim filePath = "invoice.pdf"
		pdfDocument.SaveAs(filePath)
		Console.WriteLine($"Invoice saved to {filePath}")
	End Sub
End Class

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim service = New PaymentService()
		service.ProcessPaymentAndGenerateInvoice()
	End Sub
End Class
$vbLabelText   $csharpLabel

Wynik

Stripe .NET (How It Works For Developers): Figure 10 - PDF invoice generated using IronPDF via Stripe Service

Wnioski

Stripe.Net is a comprehensive and powerful library that simplifies integrating Stripe's payment processing into .NET applications. Dzięki funkcjom obejmującym zarówno podstawową obsługę transakcji, jak i zarządzanie subskrypcjami oraz sporami, rozwiązanie to zaspokaja szeroki zakres potrzeb związanych z płatnościami.

IronPDF complements Stripe.Net by enabling developers to generate, edit, and manage PDF documents. W połączeniu biblioteki te stanowią solidne rozwiązanie do obsługi płatności i generowania odpowiedniej dokumentacji w aplikacjach .NET.

By leveraging the capabilities of both Stripe.Net and IronPDF, developers can create seamless and efficient workflows that handle everything from payment processing to document generation, enhancing the overall functionality and user experience of their applications.

IronPDF oferuje programistom możliwość przetestowania swoich rozbudowanych funkcji, udostępniając bezpłatną wersję próbną IronPDF.

IronPDF zapewnia obsługę klienta i aktualizacje, a także przykłady kodu i obszerną dokumentację, aby pomóc użytkownikom w jak najlepszym wykorzystaniu produktu. Aby zgłębić ten temat, zapoznaj się z naszym obszernym samouczkiem dotyczącym konwersji HTML do PDF za pomocą IronPDF.

Często Zadawane Pytania

Jak zintegrować obsługę płatności z aplikacją .NET?

Możesz zintegrować obsługę płatności z aplikacją .NET za pomocą biblioteki `Stripe.Net`, która pozwala zarządzać płatnościami, tworzyć klientów i obsługiwać rozliczenia w Twojej aplikacji.

Jakie kroki należy wykonać, aby skonfigurować Stripe.Net w nowym projekcie Visual Studio?

Aby skonfigurować Stripe.Net w nowym projekcie Visual Studio, zacznij od utworzenia nowego projektu, zainstaluj pakiet `Stripe.Net` za pośrednictwem NuGet i skonfiguruj swój klucz API Stripe w celu uwierzytelniania żądań API.

Jak zarządzać subskrypcjami w aplikacji .NET?

Stripe.Net udostępnia wbudowane metody zarządzania subskrypcjami, umożliwiające tworzenie, aktualizowanie i anulowanie subskrypcji bezpośrednio za pośrednictwem API.

Jakie są najlepsze praktyki dotyczące zabezpieczania kluczy API w Stripe.Net?

Najlepsze praktyki dotyczące zabezpieczania kluczy API w Stripe.Net obejmują bezpieczne przechowywanie kluczy przy użyciu zmiennych środowiskowych lub plików konfiguracyjnych oraz upewnienie się, że nie są one zakodowane na stałe w kodzie źródłowym.

Jak mogę wygenerować dokumentację lub faktury po przetworzeniu płatności w aplikacji .NET?

Po przetworzeniu płatności za pomocą Stripe.Net można wygenerować dokumentację lub faktury, używając IronPDF do konwersji treści HTML na pliki PDF, zapewniając profesjonalny wynik dostosowany do potrzeb rozliczeniowych.

Jakie są zalety korzystania z biblioteki C# do obsługi plików PDF w połączeniu z Stripe.Net?

Korzystanie z biblioteki PDF dla języka C#, takiej jak IronPDF z Stripe.Net, pozwala w łatwy sposób tworzyć, zarządzać i dostosowywać dokumenty PDF, takie jak faktury, zwiększając funkcjonalność aplikacji .NET.

Jak utworzyć PaymentIntent w Stripe.Net?

Aby utworzyć PaymentIntent w Stripe.Net, należy użyć klasy `PaymentIntentService` wraz z `PaymentIntentCreateOptions` w celu określenia szczegółów płatności i śledzenia cyklu życia płatności.

Jak mogę rozwiązywać typowe problemy podczas integracji Stripe.Net?

Typowe problemy związane z integracją Stripe.Net można rozwiązać, sprawdzając konfiguracje kluczy API, upewniając się co do prawidłowego użycia metod biblioteki Stripe oraz przeglądając komunikaty o błędach w celu uzyskania konkretnych wskazówek.

Jakie zaawansowane funkcje oferuje Stripe.Net?

Zaawansowane funkcje oferowane przez Stripe.Net obejmują obsługę sporów dotyczących płatności, zarządzanie cyklicznymi rozliczeniami oraz wdrażanie bezpiecznego przetwarzania płatności z solidną obsługą błędów.

Jak mogę przekonwertować zawartość HTML do formatu PDF w aplikacji .NET?

W aplikacji .NET można konwertować zawartość HTML do formatu PDF, korzystając z metod IronPDF, takich jak RenderHtmlAsPdf dla ciągów znaków HTML lub RenderHtmlFileAsPdf dla plików HTML.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie