diff --git a/README.md b/README.md index 808c2e5..da95718 100644 --- a/README.md +++ b/README.md @@ -2,514 +2,120 @@ This Go package provides a client to interact with the Chargily API, allowing you to manage balances, customers, products, prices, checkouts, and payment links. -## About Chargily Pay™ packages +### About Chargily Pay™ packages Chargily Pay™ packages/plugins are a collection of open source projects published by Chargily to facilitate the integration of our payment gateway into different programming languages and frameworks. Our goal is to empower developers and businesses by providing easy-to-use tools to seamlessly accept payments. -## API Documentation +### API Documentation For detailed instructions on how to integrate with our API and utilize Chargily Pay™ in your projects, please refer to our [API Documentation](https://dev.chargily.com/pay-v2/introduction). ---- - -## Navigation - -- [Chargily Pay™ Gateway - V2.](#chargily-pay-gateway---v2) - - [About Chargily Pay™ packages](#about-chargily-pay-packages) - - [API Documentation](#api-documentation) - - [Navigation](#navigation) - - [Installation](#installation) - - [Usage](#usage) - - [1- Initialize the Client](#1--initialize-the-client) - - [2- Retrieve Balance](#2--retrieve-balance) - - [3- Customers Management](#3--customers-management) - - [1. Create a New Customer](#1-create-a-new-customer) - - [2. Update a Customer](#2-update-a-customer) - - [3. Get a Customer](#3-get-a-customer) - - [4. Get All Customers](#4-get-all-customers) - - [4- Products Management](#4--products-management) - - [1. Create a Product](#1-create-a-product) - - [2. Update a Product](#2-update-a-product) - - [3. Get a Product](#3-get-a-product) - - [4. Get All Products](#4-get-all-products) - - [5. Delete a Product](#5-delete-a-product) - - [6. Get Product Prices](#6-get-product-prices) - - [5- Prices Management](#5--prices-management) - - [1. Create a Price](#1-create-a-price) - - [2. Update a Price Metadata](#2-update-a-price-metadata) - - [4. Get a Price](#4-get-a-price) - - [5. Get All Prices](#5-get-all-prices) - - [6- Checkouts Management](#6--checkouts-management) - - [1. create a checkout](#1-create-a-checkout) - - [2. Get a Checkout](#2-get-a-checkout) - - [3. Get All Checkouts](#3-get-all-checkouts) - - [4. Get Checkout Items](#4-get-checkout-items) - - [5. Expire a Checkout](#5-expire-a-checkout) - - [7- Payment Links Management](#7--payment-links-management) - - [1. Create a Payment Link](#1-create-a-payment-link) - - [2. Update a Payment Link](#2-update-a-payment-link) - - [3. Retrieve payment link](#3-retrieve-payment-link) - - [4. Retrieve All payment links](#4-retrieve-all-payment-links) - - [5. Retrieve Payment Link Items](#5-retrieve-payment-link-items) - - [Developers Community](#developers-community) - - [How to Contribute](#how-to-contribute) - - [Get in Touch](#get-in-touch) - -## Installation - -To install the package, use the following command: +## Table of Contents -```sh -go get github.com/Chargily/chargily-pay-go -``` - -## Usage - -### 1- Initialize the Client - -To create a new Chargily API client, you need to provide an API key and the mode (prod for production or test for development): - -```go -client, err := chargily.NewClient("your-api-key", "prod") -if err != nil { - log.Fatalf("Failed to initialize client: %v", err) -} -``` - -## 2- Retrieve Balance - -You can retrieve your account balance using: - -```go -balance, err := client.GetBalance() -if err != nil { - log.Fatalf("Error fetching balance: %v", err) -} -fmt.Printf("Account Balance: %v\n", balance) - -``` - -## 3- Customers Management - -### 1. Create a New Customer - -```go -// Create a new customer -customerParams := &chargily.CreateCustomerParams{ - Name: "John Doe", - Email: "john.doe@example.com", - Phone: "+1 123 456 7890", - Address: &chargily.Address{ - Address: "123 Main St", - City: "New York", - Country: "US", - }, - Metadata: map[string]any{ - "custom_field": "value", - }, -} -customer, err := client.CreateCustomer(customerParams) -if err!= nil { - fmt.Printf("Error creating customer: %v\n", err) -} -``` - -### 2. Update a Customer - -```go -// update an existing customer -customerParams := &chargily.CreateCustomerParams{ - Name: "John Doe Doe", - Email: "john.doe-updated@example.com", - Phone: "+1 123 456 7891", - Address: &chargily.Address{ - Address: "123 Main St", - City: "New York", - Country: "US", - }, - Metadata: map[string]any{ - "custom_field": "value", - }, -} - -// Get a customer by ID -customerID := string("your-customer-id") // you should always provide a valid customer ID that already Exists -customer, err := client.UpdateCustomer(customerID,customerParams) -if err!= nil { - fmt.Printf("Error getting customer: %v\n", err) - return -} -``` - -### 3. Get a Customer - -```go -customer, err := client.GetCustomer(string("customer_id")) -if err != nil { - fmt.Println("Error retrieving customer:", err) - return -} -fmt.Println("Customer:", customer) -``` - -### 4. Get All Customers - -```go -customers, err := client.GetAllCustomers() -if err != nil { - fmt.Println("Error fetching customers:", err) - return -} -fmt.Println("Customers:", customers) -``` - -## 4- Products Management - -### 1. Create a Product - -```go -// Create a new product -product := &chargily.CreateProductParams{ - Name: "New Product", - Description: "This is a new product", - Images: []string{"link1","link2","link3"}, - Metadata: map[string]any{"key0": "value0","key1":"value1"}, -} - -newProduct, err := client.CreateProduct(product) -if err!= nil { - fmt.Printf("Error creating product: %v\n", err) - return -} -``` - -### 2. Update a Product - -```go -// new data -product := &chargily.CreateProductParams{ - Name: "updated Product", - Description: "This is an updates product", - Images: []string{"link1","link2","link3","link4"}, - Metadata: map[string]any{"key0": "value0"}, -} - -// the id of the product to update -id := "your-product-id" // make sure to provide a valid id for the product -// Update the product -updatedProduct, err := client.UpdateProduct(string(id), product) -if err!= nil { - fmt.Printf("Error updating product: %v\n", err) - return -} -``` - -### 3. Get a Product - -```go -product, err := client.GetProduct("product_id") -if err != nil { - fmt.Println("Error retrieving product:", err) - return -} -// use the product data -fmt.Println("Product:", product) -``` - -### 4. Get All Products - -```go -products, err := client.GetAllProducts() -if err != nil { - fmt.Println("Error fetching products:", err) - return -} -fmt.Println("Products:", products) -``` +1. [Overview](#overview) +2. [Features](#features) +3. [Usage](#usage) +4. [Documentation](#documentation) -### 5. Delete a Product +## Overview -```go +This Golang SDK provides a seamless integration with the [Chargily API](https://chargily.com) for interacting with their payment gateway services. It simplifies the process of integrating Chargily's e-payment solutions into your Go applications, allowing you to handle payments and transactions with ease. -//string() method used here to force the id to be always string -err := client.DeleteProduct(string("product_id")) -if err != nil { - fmt.Println("Error deleting product:", err) - return -} -fmt.Println("Product deleted successfully.") -``` +### Use Cases: -### 6. Get Product Prices +- E-commerce websites that need to process payments through Chargily’s gateway. +- SaaS platforms requiring integration with a local payment processor. +- Any Go-based application that needs to handle payment processing in the Algerian market. -```go -prices, err := client.GetProductPrices("product_id") -if err != nil { - fmt.Println("Error retrieving product prices:", err) - return -} -fmt.Println("Product Prices:", prices) -``` +The SDK abstracts much of the complexity of interacting with the Chargily API, providing a simple and easy-to-use interface for developers to build payment functionalities into their Go applications. -## 5- Prices Management +## Features -### 1. Create a Price +Below are the key functionalities available through the client: -```go -// Create a new customer -price := &chargily.ProductPriceParams{ - ProductID: "your-product-id", - Currency: "USD", - Amount: 100, - Metadata: map[string]any{"key":"value"}, -} - -// create the product price and get back the price object -productPrice, err := client.CreatePrice(price) -if err!= nil { - fmt.Printf("Error creating price: %v\n", err) -} -``` +### 1. Payment Checkout -### 2. Update a Price Metadata +- **Create Checkout**: Create a new checkout session for processing payments. +- **Cancel Checkout**: Cancel an ongoing checkout. +- **Get Checkout**: Retrieve details of a specific checkout. +- **List All Checkouts**: Get a list of all checkout sessions. +- **Get Checkout Items**: Fetch items associated with a specific checkout. -```go -// Create a new customer -price := &chargily.UpdatePriceMetaDataParams{ - Metadata: map[string]any{"key":"val"}, -} +### 2. Customer Management +- **Create Customer**: Add a new customer to the system. +- **Get Customer**: Retrieve information about a specific customer. +- **List All Customers**: Fetch all customers from the system. +- **Update Customer**: Modify existing customer details. +- **Delete Customer**: Remove a customer from the system. -//product ID -prodId := "your-product-id" +### 3. Product Management -// update price metadata -productPrice, err := client.UpdatePrice(prodId,price) -if err!= nil { - fmt.Printf("Error updating price: %v\n", err) -} -``` +- **Create Product**: Add a new product to the inventory. +- **Get Product**: Retrieve details of a specific product. +- **Retrieve Product Prices**: Retrieves all the prices of a product. +- **List All Products**: Fetch a list of all products in the system. +- **Update Product**: Update existing product details. +- **Delete Product**: Remove a product from the inventory. -### 4. Get a Price +### 4. Payment Links -```go -price, err := client.GetPrice("product_id") -if err != nil { - fmt.Println("Error retrieving price:", err) - return -} -fmt.Println("Price:", price) -``` +- **Create Payment Link**: Generate payment links that can be shared and directs your customers to a hosted payment page. +- **Get Payment Link**: Get a specific payment link . +- **Get All Payment Links**: Get all payment links. +- **Get Payment Link Items**: Get all payment link associated items. +- **Update Payment Link**: Updates the information of a payment link. -### 5. Get All Prices +### 5. Price Management -```go -prices, err := client.GetAllPrices() -if err != nil { - fmt.Println("Error fetching prices:", err) - return -} -fmt.Println("Prices:", prices) -``` +- **Get Price**: Retrieve pricing details for a specific product. +- **List All Prices**: Fetch all prices listed in the system. +- **Update Price**: Updates the information of a price of an existing product. -## 6- Checkouts Management +### 6. Webhook Management -### 1. create a checkout +- **Setup Webhook**: Configure webhooks to receive updates from Chargily's server. +- **Verify Webhook Signature**: Ensure security by verifying Chargily webhook signatures. -```go -// Create example items to be added to the checkout. -items := []chargily.CItems{ - { - Price: string(priceID), - Quantity: 2, - }, -} - -// Initialize the CheckoutParams struct with adjusted fields. -checkoutParams := &chargily.CheckoutParams{ - Items: items, - PaymentMethod: "edahabia", - SuccessURL: "https://your-site.com/success", - FailureURL: "https://your-site.com/failure", - WebhookEndpoint: "https://your-site.com/webhook", - Description: "Checkout for Order #12345", - Locale: "en", - PercentageDiscount: 10, -} - -// Create the checkout -checkoutdata, err := client.CreateCheckout(checkoutParams) -if err!= nil { - fmt.Printf("Error creating checkout: %v\n", err) - return -} -``` - -### 2. Get a Checkout - -```go -checkout, err := client.GetCheckout("checkout_id") -if err != nil { - fmt.Println("Error retrieving checkout:", err) - return -} -fmt.Println("Checkout:", checkout) -``` - -### 3. Get All Checkouts - -```go -checkouts, err := client.GetAllCheckouts() -if err != nil { - fmt.Println("Error fetching checkouts:", err) - return -} -fmt.Println("Checkouts:", checkouts) -``` - -### 4. Get Checkout Items - -```go -items, err := client.GetCheckoutItems("checkout_id") -if err != nil { - fmt.Println("Error retrieving checkout items:", err) - return -} -fmt.Println("Checkout Items:", items) -``` +## Usage -### 5. Expire a Checkout +To start using the Chargily SDK in your Go project, you can install it via `go get`: -```go -expiredCheckout, err := client.ExpireCheckout("checkout_id") -if err != nil { - fmt.Println("Error expiring checkout:", err) - return -} -fmt.Println("Checkout expired:", expiredCheckout) +```sh +go get github.com/Chargily/chargily-pay-go ``` -## 7- Payment Links Management +### Initialization -### 1. Create a Payment Link +First, import the SDK into your project: ```go -// Create items to be added to the payment link -items := []chargily.PItems{ - { - Price: "01j9k9m78jp18bdky07s0rxxtg", //id example - Quantity: 2, - AdjustableQuantity: true, - }, -} - -// Create the payment link parameters -paymentLinkParams := &chargily.CreatePaymentLinkParams{ - Name: "Test Order for Payment Link", - Items: items, - AfterCompletionMessage: "Thank you for your order!", - Locale: "en", - PassFeesToCustomer: false, - CollectShippingAddress: 1, - Metadata: map[string]any{ - "order_id": "order_54321", - "notes": "This is a test order for payment link.", - }, -} - -// Create the payment link -paymentLink, err := client.CreatePaymentLink(paymentLinkParams) -if err!= nil { - fmt.Printf("Error creating payment link: %v\n", err) - return -} -``` - -### 2. Update a Payment Link +import ( + //to import the client and the functionalities + "github.com/Chargily/chargily-pay-go/pkg/chargily" -```go -// the items to add to a payment link -items := []chargily.PItems{ - { - Price: "01j9k9m78jp18bdky07s0rxxtg", - Quantity: 2, - AdjustableQuantity: true, - }, -} - -// updated payment link data -paymentLinkParams := &chargily.CreatePaymentLinkParams{ - Name: "Test Order for Payment Link", - Items: items, - AfterCompletionMessage: "Thank you for your order!", - Locale: "en", - PassFeesToCustomer: true, - CollectShippingAddress: 0, - Metadata: map[string]any{ - "order_id": "order_54321", - "notes": "This is a test order for payment link.", - }, -} - -// the id of payment id to be updated -paymentLinkId:= "your-payment-link-id" - -// update -paymentLink, err := client.UpdatePaymentLink(paymentLinkId,paymentLinkParams) -if err!= nil { - fmt.Printf("Error updating payment link: %v\n", err) - return -} + //to import the models (types) and use them in the project (params, types, generic response). + "github.com/Chargily/chargily-pay-go/pkg/models" +) ``` -### 3. Retrieve payment link - -```go -// payment link id -paymentLinkId := "your-payment-link-id" // make sure to be a valid payment link id - -// retrieve the payment link -paymentLink, err := client.GetPaymentLink(paymentLinkId) -if err!= nil { - fmt.Printf("Error retrieving payment link by ID: %v\n", err) - return -} -``` +## Documentation -### 4. Retrieve All payment links +For more detailed information about specific features and usage, check out the documentation: -```go -// Create a new client instance -client, err := chargily.NewClient(apiKey, mode) +- [API Client Setup](./docs/Client.md): Detailed guide on initializing the client and interacting with the API. +- [Customer Management](./docs/Customers.md): Learn how to create, update, delete, and manage customers. +- [Checkouts Management](./docs/Checkouts.md): Find out how to create, cancel, and retrieve checkouts. +- [Payment Links Management](./docs/PaymentLinks.md): Find out how to fully manage payment links. +- [Product Management](./docs/Products.md): Documentation on how to create, update, and manage products and their prices. +- [Prices Management](./docs/Prices.md): Learn how to set products prices,update or retrieve. +- [Webhook Integration](./docs/Webhook.md): Learn how to set up and verify webhooks to receive real-time notifications. -if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return -} +### Additional Resources: -// retrieve all payment links -paymentLinks, err := client.GetAllPaymentLinks() +- [SDK Examples](./pkg/examples): Practical examples on using the SDK in real-world scenarios. -if err!= nil { - fmt.Printf("Error retrieving all payment links: %v\n", err) - return -} -``` - -### 5. Retrieve Payment Link Items - -```go -//payment link ID -paymentLinkId := "existing-payment-link-id" //must be unique and existing - -// retrieve a payment link's items -paymentLinkItems, err := client.GetPaymentLinkItems(string(paymentLinkId)) - -if err!= nil { - fmt.Printf("Error getting payment link items: %v\n", err) - return -} -``` +For any additional questions or further assistance, feel free to reach out via the project's [issues page](#) and Never skip the Api Docs at [Chargily API](https://dev.chargily.com/pay-v2/api-reference/). ## Developers Community @@ -524,7 +130,9 @@ We welcome contributions of all kinds, whether it's bug fixes, feature enhanceme 2. **Clone the Repository:** Clone your forked repository to your local machine using the following command: ``` + git clone https://github.com/Chargily/chargily-pay-go.git + ``` 3. **Make Changes:** Make your desired changes or additions to the codebase. Be sure to follow our coding standards and guidelines. @@ -540,3 +148,7 @@ Have questions or need assistance? Join our developer community on [Telegram](ht We appreciate your interest in contributing to Chargily Pay™! Together, we can build something amazing. Happy coding! + +``` + +``` diff --git a/docs/Balance.md b/docs/Balance.md new file mode 100644 index 0000000..3a15eec --- /dev/null +++ b/docs/Balance.md @@ -0,0 +1,59 @@ +# Balance Struct Documentation + +The `Balance` struct in the `chargily` package is used to retrieve the balance from the Chargily API. + +## Method: `Get` + +This method retrieves the current balance from the Chargily API. + +### Syntax + +```go +func (b *Balance) Get() (*models.Balance, error) +``` + +### Description + +The Get method sends a GET request to the Chargily API to retrieve the current balance. +It returns the balance data in the form of a models.Balance object, along with any error that occurred during the request. + +### Parameters + +No params passed + +### Returns + +\*models.Balance: The current balance as a Balance object. +error: If the request fails, an error is returned. + +### Example Usage + +```go +package main + +import ( + "fmt" + "log" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +func main() { + // Initialize the API client + client := chargily.NewClient("API_KEY") + + + // Retrieve the balance + balance, err := client.Balance.Get() + if err != nil { + log.Fatalf("Error retrieving balance: %v", err) + } + + // Print the balance + fmt.Printf("Current Balance: %+v\n", balance) +} +``` + +### Error Handling + +If an error occurs during the request, the Get method will return an error object. You should always check the error and handle it appropriately. diff --git a/docs/Checkouts.md b/docs/Checkouts.md new file mode 100644 index 0000000..7f21642 --- /dev/null +++ b/docs/Checkouts.md @@ -0,0 +1,189 @@ +# Checkouts Module Documentation + +## Overview + +The `Checkouts` struct in the `chargily` package provides methods for managing checkout functionalities within the Chargily payment API. This module allows users to create, retrieve, and manage checkouts and their associated items. + +## Checkouts Structure + +### Fields + +- **client**: A pointer to the `Client` structure, which holds the API key, endpoint, and other necessary configurations to make API requests. + +## Methods + +### Create + +#### Parameters + +- **checkout**: A pointer to a `models.CheckoutParams` structure containing the details needed to create a new checkout. + +#### Returns + +- **(\*models.Checkout, error)**: A pointer to the newly created `models.Checkout` object and an error, if any occurs during the request. + +#### Description + +The `Create` method sends a request to the Chargily API to create a new checkout with the provided details. It constructs the API request and parses the response into a `models.Checkout` object. + +#### Example + +```go +func CreateCheckout(client *chargily.Client , id string) { + // Create example items to be added to the checkout. + items := []models.CItems{ + { + Price: id, + Quantity: 2, + }, + } + + // Initialize the CheckoutParams struct with required fields. + checkout := &models.CheckoutParams{ + Items: items, + PaymentMethod: "edahabia", + SuccessURL: "https://your-site.com/success", + FailureURL: "https://your-site.com/failure", + WebhookEndpoint: "https://your-site.com/webhook", + Description: "Checkout for Order #12345", + Locale: "en", + PercentageDiscount: 10, + } + + // Create the checkout using the client. + checkoutData, err := client.Checkouts.Create(checkout) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating checkout: %v\n", err) + return + } + + // Output the details of the created checkout. + fmt.Printf("Checkout created successfully: %+v\n", checkoutData) + fmt.Printf("Checkout Parameters: %+v\n", checkout) +} +``` + +--- + +### Get + +#### Parameters + +- **checkoutId**: A string representing the unique identifier of the checkout to be retrieved. + +#### Returns + +- **(\*models.Checkout, error)**: A pointer to the retrieved `models.Checkout` object and an error, if any occurs during the request. + +#### Description + +The `Get` method retrieves the details of a specific checkout identified by `checkoutId`. It sends a GET request to the API and parses the response into a `models.Checkout` object. + +#### Example + +```go +func RetrieveCheckout(client *chargily.Client, checkoutID string) { + // Retrieve the checkout using its ID. + checkoutData, err := client.Checkouts.Get(checkoutID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving checkout: %v\n", err) + return + } + // Output the details of the retrieved checkout. + fmt.Printf("Checkout retrieved successfully: %+v\n", checkoutData) +} +``` + +--- + +### GetAll + +#### Returns + +- **(\*models.RetrieveAll[models.Checkout], error)**: A pointer to a `models.RetrieveAll[models.Checkout]` structure containing an array of all checkouts and an error, if any occurs during the request. + +#### Description + +The `GetAll` method retrieves a list of all available checkouts stored in the Chargily system. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.Checkout]` structure, which includes an array of checkout objects. + +#### Example + +```go +func ListAllCheckouts(client *chargily.Client) { + // Call the GetAll method on the Checkouts service to retrieve all checkouts. + checkouts, err := client.Checkouts.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all checkouts: %v\n", err) + return + } + // Output the list of successfully retrieved checkouts. + fmt.Printf("All checkouts retrieved successfully: %+v\n", checkouts) +} +``` + +--- + +### GetItems + +#### Parameters + +- **checkoutId**: A string representing the unique identifier of the checkout whose items are to be retrieved. + +#### Returns + +- **(\*models.RetrieveAll[models.CheckoutItems], error)**: A pointer to a `models.RetrieveAll[models.CheckoutItems]` structure containing an array of items associated with the checkout and an error, if any occurs during the request. + +#### Description + +The `GetItems` method retrieves the items associated with a specific checkout identified by `checkoutId`. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.CheckoutItems]` structure, which includes an array of item data. + +#### Example + +```go +func RetrieveCheckoutItems(client *chargily.Client, checkoutID string) { + // Retrieve the items from the checkout using its ID. + checkoutItems, err := client.Checkouts.GetItems(checkoutID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving checkout items: %v\n", err) + return + } + // Output the details of the retrieved checkout items. + fmt.Printf("Checkout items retrieved successfully: %+v\n", checkoutItems) +} +``` + +--- + +### Expire + +#### Parameters + +- **checkoutId**: A string representing the unique identifier of the checkout to be expired. + +#### Returns + +- **(\*models.Checkout, error)**: A pointer to the expired `models.Checkout` object and an error, if any occurs during the request. + +#### Description + +The `Expire` method sends a request to the Chargily API to expire a checkout identified by `checkoutId`. It constructs the API request and returns the corresponding checkout object if the expiration is successful. + +#### Example + +```go +func CancelCheckout(client *chargily.Client, checkoutID string) { + // Call the Expire method on the Checkouts service to cancel the checkout. + checkoutEX, err := client.Checkouts.Expire(checkoutID) + if err != nil { + // Handle cancellation error. + fmt.Printf("Error canceling checkout: %v\n", err) + return + } + // Output the details of the successfully canceled checkout. + fmt.Printf("Checkout canceled successfully: %+v\n", checkoutEX) +} +``` diff --git a/docs/Client.md b/docs/Client.md new file mode 100644 index 0000000..04c70cf --- /dev/null +++ b/docs/Client.md @@ -0,0 +1,85 @@ +# Chargily Client Documentation + +## Overview + +The `chargily` package provides a `Client` structure that facilitates interaction with the Chargily payment API. This client serves as a gateway to access various functionalities offered by the Chargily platform, including balance inquiries, customer management, product pricing, payment link generation, checkout processes, and webhook handling. + +## Client Structure + +### Definition + +```go +type Client struct { + apiKey string + endpoint string + rs utils.RequestSenderI // RequestSender for custom HTTP requests + mode Mode + Balance *Balance // Access balance-related functionalities + Customers *Customers // Access customer management functionalities + Prices *Prices // Access pricing-related functionalities + Products *Products // Access product management functionalities + PaymentLinks *PaymentLinks // Access payment link functionalities + Checkouts *Checkouts // Access checkout functionalities + Webhook *Webhook // Access webhook management functionalities +} +``` + +### Fields + +- `apiKey`: A string representing the API key required to authenticate requests to the Chargily API. +- `endpoint`: A string representing the base URL of the Chargily API, which varies based on the operational mode (production or test). +- `rs`: An instance of RequestSenderI, used for sending custom HTTP requests to the API. +- `mode`: An enumeration indicating whether the client operates in "test" or "prod" mode, affecting the API endpoint. +- `Balance`: A pointer to the Balance structure, providing access to balance-related functionalities. +- `Customers`: A pointer to the Customers structure, enabling operations related to customer management. +- `Prices`: A pointer to the Prices structure, facilitating pricing-related actions. +- `Products`: A pointer to the Products structure, offering methods for product management. +- `PaymentLinks`: A pointer to the PaymentLinks structure, used for generating and managing payment links. +- `Checkouts`: A pointer to the Checkouts structure, providing functionality for handling checkout processes. +- `Webhook`: A pointer to the Webhook structure, allowing the client to manage webhook notifications. + +### NewClient Function + +```go +func NewClient(apiKey, mode string) (*Client, error) +``` + +### Parameters + +- apiKey: A string representing the API key used for authenticating requests. +- mode: A string that determines the operating mode of the client. Acceptable values are: + - "prod": Indicates that the client operates in production mode. + - "test": Indicates that the client operates in test mode. + +### Returns + +(\*Client, error): A pointer to the initialized Client and an error, if any occurs during initialization. + +### Description + +The NewClient function initializes a new instance of the Client structure, setting up the necessary configurations based on the provided API key and operational mode. + +- The function verifies the mode parameter to determine the appropriate API base URL: + - If the mode is "prod", it sets the API base URL to the production endpoint. + - If the mode is "test", it sets the API base URL to the test endpoint. + - If the mode is invalid, it returns an ErrInvalidMode error. +- It creates a new request sender to facilitate HTTP communications. +- The resulting Client provides access to all functionalities within the Chargily API ecosystem, enabling efficient management of payments and related services. + +### Example Usage + +```go +client, err := NewClient("your_api_key", "prod") +if err != nil { + // Handle error +} + +// Accessing different functionalities +// client.Balance.Get() +// client.Customers.Crate(), .Update() ... +// client.Prices.Create() ... +// client.Products.Update() ... +// client.PaymentLinks.Create(), ... +// client.Checkouts.GetAll() ... +// client.Webhook.Setup() +``` diff --git a/docs/Customers.md b/docs/Customers.md new file mode 100644 index 0000000..37bc633 --- /dev/null +++ b/docs/Customers.md @@ -0,0 +1,211 @@ +# Customers Module Documentation + +## Overview + +The `Customers` struct in the `chargily` package provides methods for managing customer-related functionalities within the Chargily payment API. This module allows the creation, updating, retrieval, and deletion of customer records, enabling seamless customer management. + +## Customers Structure + +### Definition + +```go +type Customers struct { + client *Client // Reference to the Client for API interactions +} +``` + +### Fields + +client: A pointer to the Client structure, which holds the API key, endpoint, and other necessary configurations to make API requests. + +## Methods + +### Create + +```go +func (c *Customers) Create(customer *models.CreateCustomerParams) (*models.Customer, error) +``` + +#### Parameters + +`customer`: A pointer to a `models.CreateCustomerParams `structure containing the details of the customer to be created. + +#### Returns + +(\*models.Customer, error): A pointer to the newly created models.Customer object and an error, if any occurs during the request. + +#### Description + +The Create method sends a request to the Chargily API to create a new customer with the provided details. It constructs the API request and parses the response into a models.Customer object. + +#### Example + +```go +func CreateCustomer(client * chargily.Client) { + // Param example for a clear example using types. + customerParams := &models.CreateCustomerParams{ + Name: "John Doe", // Customer's name + Email: "john.doe@example.com", // Customer's email + Phone: "+1234567890", // Customer's phone number + Address: &models.Address{ + Address: "123 Main St", // Street address + State: "NY", // State + Country: "US", // Country + }, + } + + // Call the Create method on the Customers service to create the customer. + customer, err := client.Customers.Create(customerParams) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating customer: %v\n", err) + return + } + // Output the successfully created customer details. + fmt.Printf("Customer created successfully: %+v\n", *customer) +} +``` + +### Update + +```go +func (c *Customers) Update(customerID string, customer *models.CreateCustomerParams) (\*models.Customer, error) +``` + +#### Parameters + +`customerID`: A string representing the unique identifier of the customer to be updated. +`customer`: A pointer to a `models.CreateCustomerParams` structure containing the updated customer details. + +#### Returns + +(\*models.Customer, error): A pointer to the updated models.Customer object and an error, if any occurs during the request. + +#### Description + +The Update method sends a request to the Chargily API to update the information of an existing customer specified by customerID. It constructs the API request with the new customer data and returns the updated customer object. + +#### Example + +```go +func UpdateCustomer(customerID string, client * chargily.Client) { + + // Define the parameters for updating the customer. + customerParams := &models.CreateCustomerParams{ + Email: "john.updated.doe@example.com", // Updated email + Address: &models.Address{ + Address: "1234 Main St", // Updated street address + State: "NYC", // State + Country: "USA", // Country + }, + } + + // Call the Update method on the Customers service to update the customer. + customer, err := client.Customers.Update(customerID, customerParams) + if err != nil { + // Handle update error. + fmt.Printf("Error updating customer: %v\n", err) + return + } + // Output the successfully updated customer details. + fmt.Printf("Customer updated successfully: %+v\n", *customer) +} +``` + +### Get + +```go +func (c *Customers) Get(customerID string) (*models.Customer, error) +``` + +#### Parameters + +`customerID`: A string representing the unique identifier of the customer to be retrieved. + +#### Returns + +(\*models.Customer, error): A pointer to the retrieved `models.Customer` object and an error, if any occurs during the request. + +#### Description + +The Get method retrieves the details of a specific customer identified by customerID. It sends a GET request to the API and parses the response into a models.Customer object. + +#### Example + +```go +func GetCustomer(customerID string, client *chargily.Client) { + + // Call the Get method on the Customers service to retrieve the customer by ID. + customer, err := client.Customers.Get(customerID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error getting customer: %v\n", err) + return + } + // Output the successfully retrieved customer details. + fmt.Printf("Customer retrieved successfully: %+v\n", *customer) +} +``` + +### Delete + +```go +func (c \*Customers) Delete(customerID string) error +``` + +#### Parameters + +`customerID`: A string representing the unique identifier of the customer to be deleted. + +#### Returns + +error: An error, if any occurs during the request. + +#### Description + +The Delete method sends a request to the Chargily API to delete a specific customer identified by customerID. If the request is successful, it returns nil; otherwise, it returns an error. + +#### Example + +```go +func DeleteCustomer(customerID string , client * chargily.Client) { + // Call the Delete method on the Customers service to delete the customer by ID. + if err := client.Customers.Delete(customerID); err != nil { + // Handle deletion error. + fmt.Printf("Error deleting customer: %v\n", err) + return + } + // Output a success message for deletion. + fmt.Println("Customer deleted successfully.") +} +``` + +### GetAll + +```go +func (c *Customers) GetAll() (*models.RetrieveAll[models.Customer], error) +``` + +#### Returns + +(\*models.RetrieveAll[models.Customer], error): A pointer to a models.RetrieveAll[models.Customer] structure containing an array of all customers and an error, if any occurs during the request. + +#### Description + +The GetAll method retrieves a list of all customers stored in the Chargily system. It sends a GET request to the API and parses the response into a models.RetrieveAll[models.Customer] structure, which includes an array of customer objects. + +#### Example + +```go +func GetAllCustomers(client * chargily.Client) { + // Call the GetAll method on the Customers service to retrieve all customers. + customers, err := client.Customers.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error getting all customers: %v\n", err) + return + } + // Output the successfully retrieved list of customers. + fmt.Printf("All customers retrieved successfully: %+v\n", customers) +} +``` diff --git a/docs/PaymentLinks.md b/docs/PaymentLinks.md new file mode 100644 index 0000000..244aa9f --- /dev/null +++ b/docs/PaymentLinks.md @@ -0,0 +1,211 @@ +# Payment Links Module Documentation + +## Overview + +The `PaymentLinks` struct in the `chargily` package provides methods for managing payment links within the Chargily payment API. This module allows users to create, update, retrieve, and list payment links. + +## PaymentLinks Structure + +### Fields + +- **client**: A pointer to the `Client` structure, which holds the API key, endpoint, and other necessary configurations to make API requests. + +## Methods + +### Create + +#### Parameters + +- **paymentLink**: A pointer to a `models.CreatePaymentLinkParams` structure containing the details of the payment link to be created. + +#### Returns + +- **(\*models.PaymentLink, error)**: A pointer to the newly created `models.PaymentLink` object and an error, if any occurs during the request. + +#### Description + +The `Create` method sends a request to the Chargily API to create a payment link with the provided details. It constructs the API request and parses the response into a `models.PaymentLink` object. + +#### Example + +```go +func CreatePaymentLink(client *chargily.Client, id string) { + // Create items to be added to the payment link + items := []models.PItems{ + { + Price: id, + Quantity: 2, + AdjustableQuantity: true, + }, + } + + // Create the payment link parameters + paymentLinkParams := &models.CreatePaymentLinkParams{ + Name: "Test Order for Payment Link", + Items: items, + AfterCompletionMessage: "message", + Locale: "en", + PassFeesToCustomer: false, + CollectShippingAddress: 1, + Metadata: map[string]any{ + "order_id": "order_54321", + "notes": "This is a test order for payment link.", + }, + } + + // Create the payment link using the client. + paymentLink, err := client.PaymentLinks.Create(paymentLinkParams) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating payment link: %v\n", err) + return + } + // Output the details of the created payment link. + fmt.Printf("Payment link created successfully: %+v\n", paymentLink) +} +``` + +--- + +### Update + +#### Parameters + +- **paymentLinkId**: A string representing the unique identifier of the payment link to be updated. +- **paymentLink**: A pointer to a `models.CreatePaymentLinkParams` structure containing the updated payment link details. + +#### Returns + +- **(\*models.PaymentLink, error)**: A pointer to the updated `models.PaymentLink` object and an error, if any occurs during the request. + +#### Description + +The `Update` method sends a request to the Chargily API to update an existing payment link identified by `paymentLinkId`. It constructs the API request with the new payment link data and returns the updated payment link object. + +#### Example + +```go +func UpdatePaymentLink(client *chargily.Client, paymentLinkID string) { + // Prepare updated payment link parameters. + updatedPaymentLinkParams := &models.CreatePaymentLinkParams{ + Name: "Updated Test Order for Payment Link", + Items: []models.PItems{ + { + Price: paymentLinkID, + Quantity: 2, + AdjustableQuantity: true, + }, + }, + AfterCompletionMessage: "Thank you for your updated order!", + Locale: "en", + PassFeesToCustomer: false, + CollectShippingAddress: 0, + Metadata: map[string]any{ + "order_id": "updated_order_54321", + "notes": "This is an updated test order for payment link.", + }, + } + + // Update the payment link using the client. + updatedPaymentLink, err := client.PaymentLinks.Update(paymentLinkID, updatedPaymentLinkParams) + if err != nil { + // Handle update error. + fmt.Printf("Error updating payment link: %v\n", err) + return + } + // Output the details of the updated payment link. + fmt.Printf("Payment link updated successfully: %+v\n", updatedPaymentLink) +} +``` + +--- + +### Get + +#### Parameters + +- **paymentLinkId**: A string representing the unique identifier of the payment link to be retrieved. + +#### Returns + +- **(\*models.PaymentLink, error)**: A pointer to the retrieved `models.PaymentLink` object and an error, if any occurs during the request. + +#### Description + +The `Get` method retrieves the details of a specific payment link identified by `paymentLinkId`. It sends a GET request to the API and parses the response into a `models.PaymentLink` object. + +#### Example + +```go +func RetrievePaymentLink(client *chargily.Client, paymentLinkID string) { + // Retrieve the payment link using its ID. + paymentLinkData, err := client.PaymentLinks.Get(paymentLinkID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving payment link: %v\n", err) + return + } + // Output the details of the retrieved payment link. + fmt.Printf("Payment link retrieved successfully: %+v\n", paymentLinkData) +} +``` + +--- + +### GetAll + +#### Returns + +- **(\*models.RetrieveAll[models.PaymentLink], error)**: A pointer to a `models.RetrieveAll[models.PaymentLink]` structure containing an array of all payment links and an error, if any occurs during the request. + +#### Description + +The `GetAll` method retrieves a list of all available payment links stored in the Chargily system. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.PaymentLink]` structure, which includes an array of payment link objects. + +#### Example + +```go +func ListAllPaymentLinks(client *chargily.Client) { + // Call the GetAll method on the PaymentLinks service to retrieve all payment links. + paymentLinks, err := client.PaymentLinks.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all payment links: %v\n", err) + return + } + // Output the list of successfully retrieved payment links. + fmt.Printf("All payment links retrieved successfully: %+v\n", paymentLinks) +} +``` + +--- + +### GetItems + +#### Parameters + +- **productId**: A string representing the unique identifier of the payment link whose items are to be retrieved. + +#### Returns + +- **(\*models.RetrieveAll[models.PItemsData], error)**: A pointer to a `models.RetrieveAll[models.PItemsData]` structure containing an array of items associated with the payment link and an error, if any occurs during the request. + +#### Description + +The `GetItems` method retrieves the items associated with a specific payment link identified by `productId`. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.PItemsData]` structure, which includes an array of item data. + +#### Example + +```go +func RetrievePaymentLinkItems(client *chargily.Client, paymentLinkID string) { + // Retrieve the items from the payment link using its ID. + paymentLinkItems, err := client.PaymentLinks.GetItems(paymentLinkID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving payment link items: %v\n", err) + return + } + // Output the details of the retrieved payment link items. + fmt.Printf("Payment link items retrieved successfully: %+v\n", paymentLinkItems) +} +``` diff --git a/docs/Prices.md b/docs/Prices.md new file mode 100644 index 0000000..7f28da3 --- /dev/null +++ b/docs/Prices.md @@ -0,0 +1,150 @@ +# Prices Module Documentation + +## Overview + +The `Prices` struct in the `chargily` package provides methods for managing product prices within the Chargily payment API. This module allows users to create, update, retrieve, and list product prices. + +## Prices Structure + +### Fields + +- **client**: A pointer to the `Client` structure, which holds the API key, endpoint, and other necessary configurations to make API requests. + +## Methods + +### Create + +#### Parameters + +- **productPrice**: A pointer to a `models.ProductPriceParams` structure containing the details of the product price to be created. + +#### Returns + +- **(\*models.ProductPrice, error)**: A pointer to the newly created `models.ProductPrice` object and an error, if any occurs during the request. + +#### Description + +The `Create` method sends a request to the Chargily API to create a price for a specific product with the provided details. It constructs the API request and parses the response into a `models.ProductPrice` object. + +#### Example + +```go +func CreatePrice(client *chargily.Client, productID string) { + // Define the parameters for the new price. + bodyRequestPrice := &models.ProductPriceParams{ + Amount: 10000, + Currency: "dzd", + ProductID: productID, // Product ID to associate with this price + Metadata: map[string]any{"key": "value"}, + } + + // Call the Create method on the Prices service to create the price. + price, err := client.Prices.Create(bodyRequestPrice) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating price: %v\n", err) + return + } + // Output the details of the successfully created price. + fmt.Printf("Price created successfully: %+v\n", price) +} +``` + +--- + +### Update + +#### Parameters + +- **productId**: A string representing the unique identifier of the product whose price metadata is to be updated. +- **Data**: A pointer to a `models.UpdatePriceMetaDataParams` structure containing the updated price metadata. + +#### Returns + +- **(\*models.ProductPrice, error)**: A pointer to the updated `models.ProductPrice` object and an error, if any occurs during the request. + +#### Description + +The `Update` method sends a request to the Chargily API to update the metadata of a product price identified by `productId`. It constructs the API request with the new metadata and returns the updated product price object. + +#### Example + +```go +func UpdatePrice(client *chargily.Client, priceID string) { + // Define the parameters for updating the price metadata. + data := &models.UpdatePriceMetaDataParams{ + Metadata: map[string]any{"new_key": "new_value", "key3": "keykey"}, + } + + // Call the Update method on the Prices service to update the price. + price, err := client.Prices.Update(priceID, data) + if err != nil { + // Handle update error. + fmt.Printf("Error updating price: %v\n", err) + return + } + // Output the details of the successfully updated price. + fmt.Printf("Price updated successfully: %+v\n", price) +} +``` + +--- + +### Get + +#### Parameters + +- **productId**: A string representing the unique identifier of the product whose price is to be retrieved. + +#### Returns + +- **(\*models.ProductPrice, error)**: A pointer to the retrieved `models.ProductPrice` object and an error, if any occurs during the request. + +#### Description + +The `Get` method retrieves the price details of a specific product identified by `productId`. It sends a GET request to the API and parses the response into a `models.ProductPrice` object. + +#### Example + +```go +func RetrievePrice(client *chargily.Client, priceID string) { + // Retrieve the price by its ID. + price, err := client.Prices.Get(priceID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving price: %v\n", err) + return + } + // Output the details of the retrieved price. + fmt.Printf("Price retrieved successfully: %+v\n", price) +} + +``` + +--- + +### GetAll + +#### Returns + +- **(\*models.RetrieveAll[models.ProductPrice], error)**: A pointer to a `models.RetrieveAll[models.ProductPrice]` structure containing an array of all product prices and an error, if any occurs during the request. + +#### Description + +The `GetAll` method retrieves a list of all available product prices stored in the Chargily system. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.ProductPrice]` structure, which includes an array of product price objects. + +#### Example + +```go +func GetAllPrices(client *chargily.Client) { + // Call the GetAll method on the Prices service to retrieve all prices. + prices, err := client.Prices.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all prices: %v\n", err) + return + } + // Output the list of successfully retrieved prices. + fmt.Printf("All prices retrieved successfully: %+v\n", prices) +} +``` diff --git a/docs/Products.md b/docs/Products.md new file mode 100644 index 0000000..5306aee --- /dev/null +++ b/docs/Products.md @@ -0,0 +1,197 @@ +# Products Module Documentation + +## Overview + +The `Products` struct in the `chargily` package provides methods for managing product-related functionalities within the Chargily payment API. This module allows users to create, update, retrieve, delete products, and manage product prices. + +## Products Structure + +### Fields + +- **client**: A pointer to the `Client` structure, which holds the API key, endpoint, and other necessary configurations to make API requests. + +## Methods + +### Create + +#### Parameters + +- **product**: A pointer to a `models.CreateProductParams` structure containing the details of the product to be created. + +#### Returns + +- **(\*models.Product, error)**: A pointer to the newly created `models.Product` object and an error, if any occurs during the request. + +#### Description + +The `Create` method sends a request to the Chargily API to create a new product with the provided details. It constructs the API request and parses the response into a `models.Product` object. + +#### Example + +```go +func CreateProduct(client *chargily.Client) { + // Define the parameters for the new product. + bodyRequestProduct := &models.CreateProductParams{ + Name: "Test Product", + Description: "This is a test product", + Images: []string{"valid-image-link"}, + Metadata: map[string]any{"key": "value"}, + } + + // Call the Create method on the Products service to create the product. + product, err := client.Products.Create(bodyRequestProduct) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating product: %v\n", err) + return + } + // Output the details of the successfully created product. + fmt.Printf("Product created successfully: %+v\n", product) +} +``` + +--- + +### Update + +#### Parameters + +- **productId**: A string representing the unique identifier of the product to be updated. +- **product**: A pointer to a `models.CreateProductParams` structure containing the updated product details. + +#### Returns + +- **(\*models.Product, error)**: A pointer to the updated `models.Product` object and an error, if any occurs during the request. + +#### Description + +The `Update` method sends a request to the Chargily API to update the information of an existing product specified by `productId`. It constructs the API request with the new product data and returns the updated product object. + +#### Example + +```go +func UpdateProduct(client *chargily.Client, productID string) { + // Define the parameters for updating the product. + bodyRequestProduct := &models.CreateProductParams{ + Name: "Test Product of the Update", + Description: "This is an updated test product", + Images: []string{"valid-image-link"}, + Metadata: map[string]any{"key": "value"}, + } + + // Call the Update method on the Products service to update the product. + product, err := client.Products.Update(productID, bodyRequestProduct) + if err != nil { + // Handle update error. + fmt.Printf("Error updating product: %v\n", err) + return + } + // Output the details of the successfully updated product. + fmt.Printf("Product updated successfully: %+v\n", product) +} +``` + +--- + +### Get + +#### Parameters + +- **productId**: A string representing the unique identifier of the product to be retrieved. + +#### Returns + +- **(\*models.Product, error)**: A pointer to the retrieved `models.Product` object and an error, if any occurs during the request. + +#### Description + +The `Get` method retrieves the details of a specific product identified by `productId`. It sends a GET request to the API and parses the response into a `models.Product` object. + +--- + +### GetAll + +#### Returns + +- **(\*models.RetrieveAll[models.Product], error)**: A pointer to a `models.RetrieveAll[models.Product]` structure containing an array of all products and an error, if any occurs during the request. + +#### Description + +The `GetAll` method retrieves a list of all products stored in the Chargily system. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.Product]` structure, which includes an array of product objects. + +#### Example + +```go +func GetAllProducts(client *chargily.Client) { + // Call the GetAll method on the Products service to retrieve all products. + products, err := client.Products.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all products: %v\n", err) + return + } + // Output the list of successfully retrieved products. + fmt.Printf("All products retrieved successfully: %+v\n", products) +} +``` + +--- + +### Delete + +#### Parameters + +- **productId**: A string representing the unique identifier of the product to be deleted. + +#### Returns + +- **error**: An error, if any occurs during the request. + +#### Description + +The `Delete` method sends a request to the Chargily API to delete a specific product identified by `productId`. If the request is successful, it returns `nil`; otherwise, it returns an error. + +#### Example + +```go +func DeleteProduct(client *chargily.Client, productID string) { + // Call the Delete method on the Products service to delete the product by ID. + if err := client.Products.Delete(productID); err != nil { + // Handle deletion error. + fmt.Printf("Error deleting product: %v\n", err) + return + } + // Output a success message for deletion. + fmt.Println("Product deleted successfully.") +} +``` + +--- + +### GetPrices + +#### Parameters + +- **productId**: A string representing the unique identifier of the product whose prices are to be retrieved. + +#### Returns + +- **(\*models.RetrieveAll[models.ProductPrice], error)**: A pointer to a `models.RetrieveAll[models.ProductPrice]` structure containing the prices of the specified product and an error, if any occurs during the request. + +#### Description + +The `GetPrices` method retrieves the prices associated with a specific product identified by `productId`. It sends a GET request to the API and parses the response into a `models.RetrieveAll[models.ProductPrice]` structure, which includes an array of product prices. + +#### Example + +```go +func GetProductPrices(productId string, client * chargily.Client){ + // Get a product price + prices, err := client.Products.GetPrices(productId) + if err!= nil { + fmt.Println("Error retrieving product price:", err) + } + + fmt.Printf("Product prices : %v", prices) +} +``` diff --git a/docs/Webhook.md b/docs/Webhook.md new file mode 100644 index 0000000..a990d67 --- /dev/null +++ b/docs/Webhook.md @@ -0,0 +1,70 @@ +# Webhook Module Documentation + +## Overview + +The `Webhook` struct in the `chargily` package is designed to handle webhook events from the Chargily payment API. It provides methods for setting up handlers to process incoming webhook notifications securely, ensuring that only valid requests are processed. + +## Webhook Structure + +### Fields + +- **client**: A pointer to the `Client` structure, which contains the API key and endpoint necessary for making API requests and verifying webhook signatures. + +## Methods + +### SetupHandler + +#### Parameters + +- **path**: A string representing the HTTP path where the webhook notifications will be received. +- **handler**: A function that takes an `eventType` (string) and a `models.WebhookEvent`. This function will be called when a webhook event is received. + +#### Returns + +- **void** + +#### Description + +The `SetupHandler` method sets up an HTTP handler for incoming webhook notifications. It performs the following tasks: + +1. Validates the presence of a signature in the request header. +2. Reads and verifies the payload using the provided signature. +3. Parses the JSON payload into a `models.WebhookEvent` object. +4. Identifies the event type and invokes the user-defined event handler with the event type and parsed event data. +5. Sends a 200 OK response back to the Chargily server upon successful processing of the webhook. + +#### Example + +```go +func SetupWebhook(client * chargily.Client){ + // Setup the webhook endpoint to listen for webhook events on `/webhook` + client.Webhook.SetupHandler("/webhook", handleEvent) + // Start the server + log.Fatal(http.ListenAndServe(":8080", nil)) +} + + +// Add your custom event handler function that processes events you can see examples folder +func handleEvent(eventType string, event models.WebhookEvent) {...} +``` + +--- + +### VerifySignature + +#### Parameters + +- **payload**: A byte slice containing the raw data received in the webhook request. +- **signature**: A string containing the signature from the request header. + +#### Returns + +- **error**: An error object if the signature verification fails; otherwise, returns `nil`. + +#### Description + +The `VerifySignature` method checks the validity of the provided webhook signature against a computed HMAC signature generated from the payload. It performs the following: + +1. Computes the HMAC signature using the payload and the API key. +2. Compares the computed signature with the received signature. +3. Returns an error if the signatures do not match, indicating an invalid signature; otherwise, it returns `nil`, indicating that the signature is valid. diff --git a/pkg/chargily/balance.go b/pkg/chargily/balance.go new file mode 100644 index 0000000..68535de --- /dev/null +++ b/pkg/chargily/balance.go @@ -0,0 +1,26 @@ +package chargily + +import ( + "strings" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + + +type Balance struct { + client * Client +} + +//retrieve the balance example +func (b * Balance) Get() (*models.Balance, error) { + + var balance models.Balance + //send the request + err := b.client.rs.SendRequest("GET", strings.Join([]string{b.client.endpoint, "balance"}, ""), nil, &balance) + + if err != nil { + return nil, err + } + // Return the parsed balance object + return &balance, nil +} \ No newline at end of file diff --git a/pkg/chargily/checkouts.go b/pkg/chargily/checkouts.go new file mode 100644 index 0000000..b12c155 --- /dev/null +++ b/pkg/chargily/checkouts.go @@ -0,0 +1,90 @@ +package chargily + +import ( + "strings" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +//============ CHECKOUT FUNCTIONALITIES =================// + +type Checkouts struct { + client * Client +} + + + + +//create a checkout +func (c * Checkouts) Create(checkout *models.CheckoutParams) (*models.Checkout, error) { + var checkoutResp models.Checkout + //send the request + err := c.client.rs.SendRequest("POST", strings.Join([]string{c.client.endpoint, "checkouts"}, ""), checkout, &checkoutResp) + + if err!= nil { + return nil, err + } + // Return the parsed checkout object + return &checkoutResp, nil +} + + +// retrieve a checkout +func (c * Checkouts) Get(checkoutId string) (*models.Checkout, error) { + + var checkout models.Checkout + //send the request + err := c.client.rs.SendRequest("GET", strings.Join([]string{c.client.endpoint, "checkouts/", checkoutId }, ""), nil, &checkout) + + if err!= nil { + return nil, err + } + // Return the parsed checkout object + return &checkout, nil +} + + +// retrieve all checkouts +func (c * Checkouts) GetAll() (*models.RetrieveAll[models.Checkout], error) { + + var checkouts models.RetrieveAll[models.Checkout] + //send the request + err := c.client.rs.SendRequest("GET", strings.Join([]string{c.client.endpoint, "checkouts"}, ""), nil, &checkouts) + + if err!= nil { + return nil, err + } + // Return the parsed checkout object + return &checkouts, nil +} + + + +// retrieve a checkout's items +func (c * Checkouts) GetItems(checkoutId string) (*models.RetrieveAll[models.CheckoutItems], error) { + + var items models.RetrieveAll[models.CheckoutItems] + //send the request + err := c.client.rs.SendRequest("GET", strings.Join([]string{c.client.endpoint, "checkouts/", checkoutId, "/items"}, ""), nil, &items) + + if err!= nil { + return nil, err + } + // Return the parsed checkout items object + return &items, nil +} + + +// expires a checkout +func (c * Checkouts) Expire(checkoutId string) (*models.Checkout ,error) { + + //send the request + var checkout models.Checkout + err := c.client.rs.SendRequest("POST", strings.Join([]string{c.client.endpoint, "checkouts/", checkoutId, "/expire"}, ""), nil, &checkout) + + if err!= nil { + return nil, err + } + // Return nil if the request was successful + return &checkout ,nil +} diff --git a/pkg/chargily/client.go b/pkg/chargily/client.go index 75240c0..25fa3a5 100644 --- a/pkg/chargily/client.go +++ b/pkg/chargily/client.go @@ -1,15 +1,22 @@ package chargily import ( - "strings" + "github.com/Chargily/chargily-pay-go/pkg/chargily/utils" ) // Client is the structure that holds the API key , the endpoint for the Chargily API and the development mode. type Client struct { apiKey string endpoint string - rs RequestSenderI // rs: stands for RequestSender and used to send custom http requests + rs utils.RequestSenderI // rs: stands for RequestSender and used to send custom http requests mode Mode + Balance *Balance + Customers *Customers + Prices *Prices + Products *Products + PaymentLinks *PaymentLinks + Checkouts *Checkouts + Webhook *Webhook } @@ -27,419 +34,29 @@ func NewClient(apiKey , mode string) (*Client, error) { } else if mode == "test" { api_baseUrl = TestAPIBaseUrl } else { - return nil, ErrInvalidMode + return nil, utils.ErrInvalidMode } //new request sender - requestSender := NewRequestSender(apiKey) + requestSender := utils.NewRequestSender(apiKey) //return the client with it's configurations - return &Client{ + client := &Client{ apiKey: apiKey, endpoint: api_baseUrl, rs: requestSender, mode: Mode(mode), //test: for testing/development stage , prod: for production applications - }, nil -} - - - -//retrieve the balance example -func (c *Client) GetBalance() (*Balance, error) { - - var balance Balance - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "balance"}, ""), nil, &balance) - - if err != nil { - return nil, err - } - // Return the parsed balance object - return &balance, nil -} - - - -//=========== CUSTOMERS AREA ==============// - -// create a new customer -func (c *Client) CreateCustomer(customer *CreateCustomerParams) (*Customer, error){ - - var customerResp Customer - //create new customer request with the customer data - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "customers"}, ""), customer, &customerResp) - - if err!= nil { - return nil, err - } - // Return the parsed customer object - return &customerResp, nil -} - - -// update the customer -func (c *Client) UpdateCustomer(customerID string, customer *CreateCustomerParams) (*Customer, error){ - - var customerResp Customer - //update the customer data request with the new updated customer data - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "customers/", customerID}, ""), customer, &customerResp) - - if err!= nil { - return nil, err } - // Return the parsed customer object - return &customerResp, nil -} - -// retrieve a costumer -func (c *Client) GetCustomer(customerID string) (*Customer, error) { - - var customer Customer - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "customers/",customerID }, ""), nil, &customer) - - if err != nil { - return nil, err - } - // Return the parsed customer object - return &customer, nil -} - - -// delete a specific customer -func (c *Client) DeleteCustomer(customerID string) error { - - //send the request - err := c.rs.SendRequest("DELETE", strings.Join([]string{c.endpoint, "customers/", customerID}, ""), nil, nil) - - if err != nil { - return err - } - // Return nil if the request was successful - return nil -} - -// retrieve all customers ( an array of customers ) -func (c *Client) GetAllCustomers() (*RetrieveAll[Customer], error) { + client.Balance = &Balance{client: client} + client.Customers = &Customers{client: client} + client.Prices = &Prices{client: client} + client.Products = &Products{client: client} + client.PaymentLinks = &PaymentLinks{client: client} + client.Checkouts = &Checkouts{client: client} + client.Webhook = &Webhook{client: client} - var customers RetrieveAll[Customer] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "customers"}, ""), nil, &customers) - - if err != nil { - return nil, err - } - // Return the parsed customer object - return &customers, nil + return client, nil } - - - -//========= PRODUCTS AREA ===========// -/////////////////////////////////////// - - -//create a new product -func (c *Client) CreateProduct(product *CreateProductParams) (*Product, error){ - - var productResp Product - //create new product request with the product data - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "products"}, ""), product, &productResp) - - if err!= nil { - return nil, err - } - // Return the parsed product object - return &productResp, nil -} - - -// Update the product with it's unique ID -func (c *Client) UpdateProduct(productId string,product *CreateProductParams) (*Product, error){ - var productResp Product - - //update existing product request with the new product data - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "products/",productId}, ""), product, &productResp) - - if err!= nil { - return nil, err - } - // Return the parsed product object - return &productResp, nil -} - - -//retrieve a product using its unique ID -func (c *Client) GetProduct(productId string) (*Product, error) { - - var product Product - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "products/", productId }, ""), nil, &product) - - if err != nil { - return nil, err - } - // Return the parsed product object - return &product, nil -} - - -// retrieve all products -func (c *Client) GetAllProducts() (*RetrieveAll[Product], error) { - - var products RetrieveAll[Product] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "products"}, ""), nil, &products) - - if err!= nil { - return nil, err - } - // Return the parsed product object - return &products, nil -} - - -// delete a specific product -func (c *Client) DeleteProduct(productId string) error { - - //send the request - err := c.rs.SendRequest("DELETE", strings.Join([]string{c.endpoint, "products/", productId}, ""), nil, nil) - - if err!= nil { - return err - } - // Return nil if the request was successful - return nil -} - - -// Retrieve a products's prices using its ID -func (c *Client) GetProductPrices(productId string) (*RetrieveAll[ProductPrice], error) { - - var prices RetrieveAll[ProductPrice] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "products/", productId, "/prices"}, ""), nil, &prices) - - if err!= nil { - return nil, err - } - // Return the parsed product prices object - return &prices, nil -} - - -//============PRICES AREA ==============// -//Create Price of a product for a specific product -func (c *Client) CreatePrice(productPrice * ProductPriceParams) (*ProductPrice, error) { - var price ProductPrice - //send the request - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "prices"}, ""), productPrice, &price) - - if err!= nil { - return nil, err - } - // Return the parsed product price object - return &price, nil -} - - -// update the product price data (not the price itself as mentioned in the docs of Chargily) for a specific product -func (c *Client) UpdatePrice(productId string, Data * UpdatePriceMetaDataParams ) (*ProductPrice, error) { - var price ProductPrice - //send the request - - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "prices/", productId}, ""), Data , &price) - - if err!= nil { - return nil, err - } - // Return the parsed product price object - return &price, nil -} - - -// retrieve a price -func (c *Client) GetPrice(productId string) (*ProductPrice, error) { - - var price ProductPrice - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "prices/", productId }, ""), nil, &price) - - if err!= nil { - return nil, err - } - // Return the parsed product price object - return &price, nil -} - - -// retrieve a list of all prices available -func (c *Client) GetAllPrices() (*RetrieveAll[ProductPrice], error) { - - var prices RetrieveAll[ProductPrice] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "prices"}, ""), nil, &prices) - - if err!= nil { - return nil, err - } - // Return the parsed product price object - return &prices, nil -} - - - -//============ CHECKOUT FUNCTIONALITIES =================// - -//create a checkout -func (c *Client) CreateCheckout(checkout *CheckoutParams) (*Checkout, error) { - var checkoutResp Checkout - //send the request - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "checkouts"}, ""), checkout, &checkoutResp) - - if err!= nil { - return nil, err - } - // Return the parsed checkout object - return &checkoutResp, nil -} - - -// retrieve a checkout -func (c *Client) GetCheckout(checkoutId string) (*Checkout, error) { - - var checkout Checkout - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "checkouts/", checkoutId }, ""), nil, &checkout) - - if err!= nil { - return nil, err - } - // Return the parsed checkout object - return &checkout, nil -} - - -// retrieve all checkouts -func (c *Client) GetAllCheckouts() (*RetrieveAll[Checkout], error) { - - var checkouts RetrieveAll[Checkout] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "checkouts"}, ""), nil, &checkouts) - - if err!= nil { - return nil, err - } - // Return the parsed checkout object - return &checkouts, nil -} - - - -// retrieve a checkout's items -func (c *Client) GetCheckoutItems(checkoutId string) (*RetrieveAll[CheckoutItems], error) { - - var items RetrieveAll[CheckoutItems] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "checkouts/", checkoutId, "/items"}, ""), nil, &items) - - if err!= nil { - return nil, err - } - // Return the parsed checkout items object - return &items, nil -} - - -// expires a checkout -func (c *Client) ExpireCheckout(checkoutId string) (*Checkout ,error) { - - //send the request - var checkout Checkout - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "checkouts/", checkoutId, "/expire"}, ""), nil, &checkout) - - if err!= nil { - return nil, err - } - // Return nil if the request was successful - return &checkout ,nil -} - - - -//================== PAYMENT LINKS =====================// - -//create payment link -func (c *Client) CreatePaymentLink(paymentLink *CreatePaymentLinkParams) (*PaymentLink, error) { - var link PaymentLink - //send the request - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "payment-links"}, ""), paymentLink, &link) - - if err!= nil { - return nil, err - } - // Return the parsed payment link object - return &link, nil -} - -// update a Payment Link -func (c *Client) UpdatePaymentLink(paymentLinkId string, paymentLink *CreatePaymentLinkParams) (*PaymentLink, error) { - var link PaymentLink - //send the request - err := c.rs.SendRequest("POST", strings.Join([]string{c.endpoint, "payment-links/", paymentLinkId}, ""), paymentLink, &link) - - if err!= nil { - return nil, err - } - // Return the parsed payment link object - return &link, nil -} - - -// retrieve a payment link -func (c *Client) GetPaymentLink(paymentLinkId string) (*PaymentLink, error) { - - var link PaymentLink - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "payment-links/", paymentLinkId }, ""), nil, &link) - - if err!= nil { - return nil, err - } - // Return the parsed payment link object - return &link, nil -} - - -// retrieve all payment links -func (c *Client) GetAllPaymentLinks() (*RetrieveAll[PaymentLink], error) { - - var links RetrieveAll[PaymentLink] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "payment-links"}, ""), nil, &links) - - if err!= nil { - return nil, err - } - // Return the parsed payment link object - return &links, nil -} - - - -// retrieve a payment link's items -func (c *Client) GetPaymentLinkItems(productId string) (*RetrieveAll[PItemsData], error) { - - var items RetrieveAll[PItemsData] - //send the request - err := c.rs.SendRequest("GET", strings.Join([]string{c.endpoint, "payment-links/", productId , "/items"}, ""), nil, &items) - - if err!= nil { - return nil, err - } - // Return the parsed payment link items object - return &items, nil -} \ No newline at end of file diff --git a/pkg/chargily/customers.go b/pkg/chargily/customers.go new file mode 100644 index 0000000..23bdc6c --- /dev/null +++ b/pkg/chargily/customers.go @@ -0,0 +1,86 @@ +package chargily + +import ( + "strings" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +//=========== CUSTOMERS AREA ==============// +type Customers struct { + client * Client +} + +// create a new customer +func (c * Customers) Create(customer *models.CreateCustomerParams) (*models.Customer, error){ + + var customerResp models.Customer + //create new customer request with the customer data + err := c.client.rs.SendRequest("POST", strings.Join([]string{c.client.endpoint, "customers"}, ""), customer, &customerResp) + + if err!= nil { + return nil, err + } + // Return the parsed customer object + return &customerResp, nil +} + + +// update the customer +func (c * Customers) Update(customerID string, customer *models.CreateCustomerParams) (*models.Customer, error){ + + var customerResp models.Customer + //update the customer data request with the new updated customer data + err := c.client.rs.SendRequest("POST", strings.Join([]string{c.client.endpoint, "customers/", customerID}, ""), customer, &customerResp) + + if err!= nil { + return nil, err + } + // Return the parsed customer object + return &customerResp, nil +} + +// retrieve a costumer +func (c * Customers) Get(customerID string) (*models.Customer, error) { + + var customer models.Customer + //send the request + err := c.client.rs.SendRequest("GET", strings.Join([]string{c.client.endpoint, "customers/",customerID }, ""), nil, &customer) + + if err != nil { + return nil, err + } + // Return the parsed customer object + return &customer, nil +} + + +// delete a specific customer +func (c * Customers) Delete(customerID string) error { + + //send the request + err := c.client.rs.SendRequest("DELETE", strings.Join([]string{c.client.endpoint, "customers/", customerID}, ""), nil, nil) + + if err != nil { + return err + } + // Return nil if the request was successful + return nil +} + + +// retrieve all customers ( an array of customers ) +func (c * Customers) GetAll() (*models.RetrieveAll[models.Customer], error) { + + var customers models.RetrieveAll[models.Customer] + //send the request + err := c.client.rs.SendRequest("GET", strings.Join([]string{c.client.endpoint, "customers"}, ""), nil, &customers) + + if err != nil { + return nil, err + } + // Return the parsed customer object + return &customers, nil +} + + diff --git a/pkg/chargily/paymentLinks.go b/pkg/chargily/paymentLinks.go new file mode 100644 index 0000000..299c7d3 --- /dev/null +++ b/pkg/chargily/paymentLinks.go @@ -0,0 +1,86 @@ +package chargily + +import ( + "strings" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +//================== PAYMENT LINKS =====================// + + +type PaymentLinks struct { + client * Client +} + +//create payment link +func (p * PaymentLinks) Create(paymentLink *models.CreatePaymentLinkParams) (*models.PaymentLink, error) { + var link models.PaymentLink + //send the request + err := p.client.rs.SendRequest("POST", strings.Join([]string{p.client.endpoint, "payment-links"}, ""), paymentLink, &link) + + if err!= nil { + return nil, err + } + // Return the parsed payment link object + return &link, nil +} + +// update a Payment Link +func (p * PaymentLinks) Update(paymentLinkId string, paymentLink *models.CreatePaymentLinkParams) (*models.PaymentLink, error) { + var link models.PaymentLink + //send the request + err := p.client.rs.SendRequest("POST", strings.Join([]string{p.client.endpoint, "payment-links/", paymentLinkId}, ""), paymentLink, &link) + + if err!= nil { + return nil, err + } + // Return the parsed payment link object + return &link, nil +} + + +// retrieve a payment link +func (p * PaymentLinks) Get(paymentLinkId string) (*models.PaymentLink, error) { + + var link models.PaymentLink + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "payment-links/", paymentLinkId }, ""), nil, &link) + + if err!= nil { + return nil, err + } + // Return the parsed payment link object + return &link, nil +} + + +// retrieve all payment links +func (p * PaymentLinks) GetAll() (*models.RetrieveAll[models.PaymentLink], error) { + + var links models.RetrieveAll[models.PaymentLink] + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "payment-links"}, ""), nil, &links) + + if err!= nil { + return nil, err + } + // Return the parsed payment link object + return &links, nil +} + + + +// retrieve a payment link's items +func (p * PaymentLinks) GetItems(productId string) (*models.RetrieveAll[models.PItemsData], error) { + + var items models.RetrieveAll[models.PItemsData] + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "payment-links/", productId , "/items"}, ""), nil, &items) + + if err!= nil { + return nil, err + } + // Return the parsed payment link items object + return &items, nil +} \ No newline at end of file diff --git a/pkg/chargily/prices.go b/pkg/chargily/prices.go new file mode 100644 index 0000000..7dbc20d --- /dev/null +++ b/pkg/chargily/prices.go @@ -0,0 +1,71 @@ +package chargily + +import ( + "strings" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +//============PRICES AREA ==============// + +type Prices struct { + client * Client +} + +//Create Price of a product for a specific product +func (p * Prices) Create(productPrice * models.ProductPriceParams) (*models.ProductPrice, error) { + var price models.ProductPrice + //send the request + err := p.client.rs.SendRequest("POST", strings.Join([]string{p.client.endpoint, "prices"}, ""), productPrice, &price) + + if err!= nil { + return nil, err + } + // Return the parsed product price object + return &price, nil +} + + +// update the product price data (not the price itself as mentioned in the docs of Chargily) for a specific product +func (p * Prices) Update(productId string, Data * models.UpdatePriceMetaDataParams ) (*models.ProductPrice, error) { + var price models.ProductPrice + //send the request + + err := p.client.rs.SendRequest("POST", strings.Join([]string{p.client.endpoint, "prices/", productId}, ""), Data , &price) + + if err!= nil { + return nil, err + } + // Return the parsed product price object + return &price, nil +} + + +// retrieve a price +func (p * Prices) Get(productId string) (*models.ProductPrice, error) { + + var price models.ProductPrice + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "prices/", productId }, ""), nil, &price) + + if err!= nil { + return nil, err + } + // Return the parsed product price object + return &price, nil +} + + +// retrieve a list of all prices available +func (p * Prices) GetAll() (*models.RetrieveAll[models.ProductPrice], error) { + + var prices models.RetrieveAll[models.ProductPrice] + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "prices"}, ""), nil, &prices) + + if err!= nil { + return nil, err + } + // Return the parsed product price object + return &prices, nil +} diff --git a/pkg/chargily/products.go b/pkg/chargily/products.go new file mode 100644 index 0000000..6d7d797 --- /dev/null +++ b/pkg/chargily/products.go @@ -0,0 +1,105 @@ +package chargily + +import ( + "strings" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +//========= PRODUCTS AREA ===========// +/////////////////////////////////////// + + +type Products struct { + client * Client +} + + + +//create a new product +func (p * Products) Create(product *models.CreateProductParams) (*models.Product, error){ + + var productResp models.Product + //create new product request with the product data + err := p.client.rs.SendRequest("POST", strings.Join([]string{p.client.endpoint, "products"}, ""), product, &productResp) + + if err!= nil { + return nil, err + } + // Return the parsed product object + return &productResp, nil +} + + +// Update the product with it's unique ID +func (p * Products) Update(productId string,product *models.CreateProductParams) (*models.Product, error){ + var productResp models.Product + + //update existing product request with the new product data + err := p.client.rs.SendRequest("POST", strings.Join([]string{p.client.endpoint, "products/",productId}, ""), product, &productResp) + + if err!= nil { + return nil, err + } + // Return the parsed product object + return &productResp, nil +} + + +//retrieve a product using its unique ID +func (p * Products) Get(productId string) (*models.Product, error) { + + var product models.Product + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "products/", productId }, ""), nil, &product) + + if err != nil { + return nil, err + } + // Return the parsed product object + return &product, nil +} + + +// retrieve all products +func (p * Products) GetAll() (*models.RetrieveAll[models.Product], error) { + + var products models.RetrieveAll[models.Product] + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "products"}, ""), nil, &products) + + if err!= nil { + return nil, err + } + // Return the parsed product object + return &products, nil +} + + +// delete a specific product +func (p * Products) Delete(productId string) error { + + //send the request + err := p.client.rs.SendRequest("DELETE", strings.Join([]string{p.client.endpoint, "products/", productId}, ""), nil, nil) + + if err!= nil { + return err + } + // Return nil if the request was successful + return nil +} + + +// Retrieve a products's prices using its ID +func (p * Products) GetPrices(productId string) (*models.RetrieveAll[models.ProductPrice], error) { + + var prices models.RetrieveAll[models.ProductPrice] + //send the request + err := p.client.rs.SendRequest("GET", strings.Join([]string{p.client.endpoint, "products/", productId, "/prices"}, ""), nil, &prices) + + if err!= nil { + return nil, err + } + // Return the parsed product prices object + return &prices, nil +} \ No newline at end of file diff --git a/pkg/chargily/errors.go b/pkg/chargily/utils/custom_errors.go similarity index 96% rename from pkg/chargily/errors.go rename to pkg/chargily/utils/custom_errors.go index 5f4435e..2b6cefa 100644 --- a/pkg/chargily/errors.go +++ b/pkg/chargily/utils/custom_errors.go @@ -1,4 +1,4 @@ -package chargily +package utils import "errors" diff --git a/pkg/chargily/utils.go b/pkg/chargily/utils/requests_sender.go similarity index 99% rename from pkg/chargily/utils.go rename to pkg/chargily/utils/requests_sender.go index c4ffaf5..56f09ca 100644 --- a/pkg/chargily/utils.go +++ b/pkg/chargily/utils/requests_sender.go @@ -1,4 +1,4 @@ -package chargily +package utils import ( "bytes" diff --git a/pkg/chargily/webhook.go b/pkg/chargily/webhook.go new file mode 100644 index 0000000..b5416e2 --- /dev/null +++ b/pkg/chargily/webhook.go @@ -0,0 +1,96 @@ +package chargily + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +type Webhook struct { + client * Client +} + +type EventHandler func(eventType string ,event models.WebhookEvent) + +//wh : webhook +func (wh * Webhook) SetupHandler(path string, handler EventHandler) { + http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { + // Extract signature + signature := r.Header.Get("signature") + + // Check if signature is present + if signature == "" { + http.Error(w, "Missing signature", http.StatusBadRequest) + return + } + + // Read payload + payload, err := io.ReadAll(r.Body) + // Close the request body to free up resources + defer r.Body.Close() + if err != nil { + http.Error(w, "Failed to read payload", http.StatusInternalServerError) + return + } + + + // Verify signature + err = wh.VerifySignature(payload, signature) + if err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return + } + + // Parse JSON payload + var event models.WebhookEvent + if err := json.Unmarshal(payload, &event); err != nil { + http.Error(w, "Invalid JSON payload", http.StatusInternalServerError) + return + } + + // Identify event type and call handler + eventType := string(event.Type) + + // Call user-defined handler + handler(eventType, event) + + // Respond with 200 OK + w.WriteHeader(http.StatusOK) + }) +} + + + +// Reuseable signature verifier function +func (wh * Webhook) VerifySignature(payload []byte, signature string) error{ + //compute the HMAC signature + computedSignature := computeHMAC(payload, wh.client.apiKey) + // Compare the computed signature with the received signature + if !hmac.Equal([]byte(computedSignature), []byte(signature)) { + // If they don't match, return an error indicating invalid signature + return errors.New("invalid signature") + } + // If they match, return nil indicating valid signature + return nil; +} + + +// Helper function to compute HMAC +func computeHMAC(data []byte, key string) string { + // Create a new HMAC hash using SHA256 and the provided API key + h := hmac.New(sha256.New, []byte(key)) + + // Write the data to the hasher and compute the final HMAC + h.Write(data) + + // Return the computed HMAC as a hexadecimal string + return hex.EncodeToString(h.Sum(nil)) +} + + diff --git a/pkg/examples/checkouts/cancel.go b/pkg/examples/checkouts/cancel.go new file mode 100644 index 0000000..0ae40f5 --- /dev/null +++ b/pkg/examples/checkouts/cancel.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// CancelCheckout demonstrates how to cancel a checkout using the Chargily SDK. +func CancelCheckout(client *chargily.Client, checkoutID string) { + // Call the Expire method on the Checkouts service to cancel the checkout. + checkoutEX, err := client.Checkouts.Expire(checkoutID) + if err != nil { + // Handle cancellation error. + fmt.Printf("Error canceling checkout: %v\n", err) + return + } + // Output the details of the successfully canceled checkout. + fmt.Printf("Checkout canceled successfully: %+v\n", checkoutEX) +} diff --git a/pkg/examples/checkouts/create-checkouts/create-checkout.go b/pkg/examples/checkouts/create-checkouts/create-checkout.go deleted file mode 100644 index 6bc367e..0000000 --- a/pkg/examples/checkouts/create-checkouts/create-checkout.go +++ /dev/null @@ -1,59 +0,0 @@ -package createcheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - - //price id - priceID := "price-id" // must be an existing one - - - // Create example items to be added to the checkout. - items := []chargily.CItems{ - { - Price: string(priceID), - Quantity: 2, - }, - } - - - // Initialize the CheckoutParams struct with adjusted fields. - checkoutParams := &chargily.CheckoutParams{ - Items: items, - PaymentMethod: "edahabia", - SuccessURL: "https://your-site.com/success", - FailureURL: "https://your-site.com/failure", - WebhookEndpoint: "https://your-site.com/webhook", - Description: "Checkout for Order #12345", - Locale: "en", - PercentageDiscount: 10, - } - - // Create the checkout - checkoutdata, err := client.CreateCheckout(checkoutParams) - if err!= nil { - fmt.Printf("Error creating checkout: %v\n", err) - return - } - - fmt.Printf("Created checkout: %+v\n", checkoutdata) -} \ No newline at end of file diff --git a/pkg/examples/checkouts/create.go b/pkg/examples/checkouts/create.go new file mode 100644 index 0000000..c39b2e1 --- /dev/null +++ b/pkg/examples/checkouts/create.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// CreateCheckout demonstrates how to create a checkout using the Chargily SDK. +func CreateCheckout(client *chargily.Client , id string) { + // Create example items to be added to the checkout. + items := []models.CItems{ + { + Price: id, + Quantity: 2, + }, + } + + // Initialize the CheckoutParams struct with required fields. + checkout := &models.CheckoutParams{ + Items: items, + PaymentMethod: "edahabia", + SuccessURL: "https://your-site.com/success", + FailureURL: "https://your-site.com/failure", + WebhookEndpoint: "https://your-site.com/webhook", + Description: "Checkout for Order #12345", + Locale: "en", + PercentageDiscount: 10, + } + + // Create the checkout using the client. + checkoutData, err := client.Checkouts.Create(checkout) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating checkout: %v\n", err) + return + } + + // Output the details of the created checkout. + fmt.Printf("Checkout created successfully: %+v\n", checkoutData) + fmt.Printf("Checkout Parameters: %+v\n", checkout) +} diff --git a/pkg/examples/checkouts/expires-checkout/expires-checkout.go b/pkg/examples/checkouts/expires-checkout/expires-checkout.go deleted file mode 100644 index 4236462..0000000 --- a/pkg/examples/checkouts/expires-checkout/expires-checkout.go +++ /dev/null @@ -1,36 +0,0 @@ -package expirescheckout - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // checkout id - checkoutId := "your-checkout-id" // make sure to be a valid checkout id - - // expires the checkout - checkout, err := client.ExpireCheckout(checkoutId) - if err!= nil { - fmt.Printf("Error expiring checkout: %v\n", err) - return - } - - fmt.Printf("expired checkout: %+v\n", checkout) -} \ No newline at end of file diff --git a/pkg/examples/checkouts/get.go b/pkg/examples/checkouts/get.go new file mode 100644 index 0000000..a75bead --- /dev/null +++ b/pkg/examples/checkouts/get.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// RetrieveCheckout demonstrates how to retrieve a specific checkout using the Chargily SDK. +func RetrieveCheckout(client *chargily.Client, checkoutID string) { + // Retrieve the checkout using its ID. + checkoutData, err := client.Checkouts.Get(checkoutID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving checkout: %v\n", err) + return + } + // Output the details of the retrieved checkout. + fmt.Printf("Checkout retrieved successfully: %+v\n", checkoutData) +} diff --git a/pkg/examples/checkouts/get_all.go b/pkg/examples/checkouts/get_all.go new file mode 100644 index 0000000..fd1e03a --- /dev/null +++ b/pkg/examples/checkouts/get_all.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// ListAllCheckouts demonstrates how to retrieve all checkouts using the Chargily SDK. +func ListAllCheckouts(client *chargily.Client) { + // Call the GetAll method on the Checkouts service to retrieve all checkouts. + checkouts, err := client.Checkouts.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all checkouts: %v\n", err) + return + } + // Output the list of successfully retrieved checkouts. + fmt.Printf("All checkouts retrieved successfully: %+v\n", checkouts) +} diff --git a/pkg/examples/checkouts/get_items.go b/pkg/examples/checkouts/get_items.go new file mode 100644 index 0000000..85f9c3f --- /dev/null +++ b/pkg/examples/checkouts/get_items.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// RetrieveCheckoutItems demonstrates how to retrieve items from a specific checkout using the Chargily SDK. +func RetrieveCheckoutItems(client *chargily.Client, checkoutID string) { + // Retrieve the items from the checkout using its ID. + checkoutItems, err := client.Checkouts.GetItems(checkoutID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving checkout items: %v\n", err) + return + } + // Output the details of the retrieved checkout items. + fmt.Printf("Checkout items retrieved successfully: %+v\n", checkoutItems) +} diff --git a/pkg/examples/checkouts/retrieve-all-checkouts/retrieve-all-checkouts.go b/pkg/examples/checkouts/retrieve-all-checkouts/retrieve-all-checkouts.go deleted file mode 100644 index c5009de..0000000 --- a/pkg/examples/checkouts/retrieve-all-checkouts/retrieve-all-checkouts.go +++ /dev/null @@ -1,33 +0,0 @@ -package retrieveallcheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // retrieve all checkouts - checkouts, err := client.GetAllCheckouts() - if err!= nil { - fmt.Printf("Error retrieving all checkouts: %v\n", err) - return - } - - fmt.Printf("checkout: %+v\n", checkouts) -} \ No newline at end of file diff --git a/pkg/examples/checkouts/retrieve-checkouts-items/retrieve-chekout-items.go b/pkg/examples/checkouts/retrieve-checkouts-items/retrieve-chekout-items.go deleted file mode 100644 index 9c7e00f..0000000 --- a/pkg/examples/checkouts/retrieve-checkouts-items/retrieve-chekout-items.go +++ /dev/null @@ -1,36 +0,0 @@ -package retrievecheckoutsitems - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // checkout id - checkoutId := "your-checkout-id" // make sure to be a valid checkout id - - // retrieve the checkout's items - checkout, err := client.GetCheckoutItems(checkoutId) - if err!= nil { - fmt.Printf("Error retrieving checkout's items: %v\n", err) - return - } - - fmt.Printf("checkout's items: %+v\n", checkout) -} \ No newline at end of file diff --git a/pkg/examples/checkouts/retrieve-checkouts/retrieve-checkout.go b/pkg/examples/checkouts/retrieve-checkouts/retrieve-checkout.go deleted file mode 100644 index 9554fcf..0000000 --- a/pkg/examples/checkouts/retrieve-checkouts/retrieve-checkout.go +++ /dev/null @@ -1,36 +0,0 @@ -package retrievecheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // checkout id - checkoutId := "your-checkout-id" // make sure to be a valid checkout id - - // retrieve the checkout - checkout, err := client.GetCheckout(checkoutId) - if err!= nil { - fmt.Printf("Error retrieving checkout: %v\n", err) - return - } - - fmt.Printf("checkout: %+v\n", checkout) -} \ No newline at end of file diff --git a/pkg/examples/client/create.go b/pkg/examples/client/create.go new file mode 100644 index 0000000..f6d22ea --- /dev/null +++ b/pkg/examples/client/create.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + + + +func main(){ + // Define your API key and mode + apiKey := "your-api-key" + mode := "test" // Could be "prod" or "test" + + // Create a new client instance + client, err := chargily.NewClient(apiKey, mode) + + // error handling + if err!= nil { + fmt.Printf("Error creating client: %v\n", err) + return + } + + // Usage Example: + client.Balance.Get() + + // Use the client to make API requests + //... + // Example usage: + // client.Customers.(Get(), Update(...), Delete() ...). + // client.Products.(Get(), Update(...), Delete() ...). + // client.Prices + // client.PaymentLinks.(Get(), Create(...), Delete() ...). + // client.Checkouts.(Get(), Create(...), Delete() ...). + //... + // Read the documentation (README.md) for more information + // Or navigate to the examples folder +} \ No newline at end of file diff --git a/pkg/examples/customers/create-customers/create-customer.go b/pkg/examples/customers/create-customers/create-customer.go deleted file mode 100644 index fb59689..0000000 --- a/pkg/examples/customers/create-customers/create-customer.go +++ /dev/null @@ -1,46 +0,0 @@ -package createcustomers - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Create a new customer - customerParams := &chargily.CreateCustomerParams{ - Name: "John Doe", - Email: "john.doe@example.com", - Phone: "+1 123 456 7890", - Address: &chargily.Address{ - Address: "123 Main St", - City: "New York", - State: "NY", - ZipCode: "10001", - Country: "US", - }, - Metadata: map[string]any{ - "custom_field": "value", - }, - } - - customer, err := client.CreateCustomer(customerParams) - if err!= nil { - fmt.Printf("Error creating customer: %v\n", err) - } - - fmt.Printf("Created customer: %+v\n", customer) -} \ No newline at end of file diff --git a/pkg/examples/customers/create.go b/pkg/examples/customers/create.go new file mode 100644 index 0000000..ac28f95 --- /dev/null +++ b/pkg/examples/customers/create.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// CreateCustomer demonstrates how to create a new customer using the Chargily SDK. +func CreateCustomer(client * chargily.Client) { + // Param example for a clear example using types. + customerParams := &models.CreateCustomerParams{ + Name: "John Doe", // Customer's name + Email: "john.doe@example.com", // Customer's email + Phone: "+1234567890", // Customer's phone number + Address: &models.Address{ + Address: "123 Main St", // Street address + State: "NY", // State + Country: "US", // Country + }, + } + + // Call the Create method on the Customers service to create the customer. + customer, err := client.Customers.Create(customerParams) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating customer: %v\n", err) + return + } + // Output the successfully created customer details. + fmt.Printf("Customer created successfully: %+v\n", *customer) +} diff --git a/pkg/examples/customers/delete-customers/delete-customer.go b/pkg/examples/customers/delete-customers/delete-customer.go deleted file mode 100644 index 2ec6d2b..0000000 --- a/pkg/examples/customers/delete-customers/delete-customer.go +++ /dev/null @@ -1,32 +0,0 @@ -package deletecustomers - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Create a new customer - customerID := "your-customer-id" // you should always provide a valid customer ID that already Exists - err = client.DeleteCustomer(customerID) - if err!= nil { - fmt.Printf("Error deleting customer: %v\n", err) - return - } - - fmt.Printf("Deleted customer with ID: %s\n", customerID) -} \ No newline at end of file diff --git a/pkg/examples/customers/delete.go b/pkg/examples/customers/delete.go new file mode 100644 index 0000000..2ebdcdc --- /dev/null +++ b/pkg/examples/customers/delete.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// DeleteCustomer demonstrates how to delete an existing customer using the Chargily SDK. +func DeleteCustomer(customerID string , client * chargily.Client) { + // Call the Delete method on the Customers service to delete the customer by ID. + if err := client.Customers.Delete(customerID); err != nil { + // Handle deletion error. + fmt.Printf("Error deleting customer: %v\n", err) + return + } + // Output a success message for deletion. + fmt.Println("Customer deleted successfully.") +} diff --git a/pkg/examples/customers/get.go b/pkg/examples/customers/get.go new file mode 100644 index 0000000..3f9b65d --- /dev/null +++ b/pkg/examples/customers/get.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// GetCustomer demonstrates how to retrieve an existing customer's details using the Chargily SDK. +func GetCustomer(customerID string, client *chargily.Client) { + + // Call the Get method on the Customers service to retrieve the customer by ID. + customer, err := client.Customers.Get(customerID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error getting customer: %v\n", err) + return + } + // Output the successfully retrieved customer details. + fmt.Printf("Customer retrieved successfully: %+v\n", *customer) +} diff --git a/pkg/examples/customers/get_all.go b/pkg/examples/customers/get_all.go new file mode 100644 index 0000000..3f04708 --- /dev/null +++ b/pkg/examples/customers/get_all.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// GetAllCustomers demonstrates how to retrieve all customers using the Chargily SDK. +func GetAllCustomers(client * chargily.Client) { + // Call the GetAll method on the Customers service to retrieve all customers. + customers, err := client.Customers.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error getting all customers: %v\n", err) + return + } + // Output the successfully retrieved list of customers. + fmt.Printf("All customers retrieved successfully: %+v\n", customers) +} diff --git a/pkg/examples/customers/retrieve-all-customers/retrieve-all-customers.go b/pkg/examples/customers/retrieve-all-customers/retrieve-all-customers.go deleted file mode 100644 index 0e3b364..0000000 --- a/pkg/examples/customers/retrieve-all-customers/retrieve-all-customers.go +++ /dev/null @@ -1,31 +0,0 @@ -package retrieveallcustomers - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Retrieve all customers - customers, err := client.GetAllCustomers() - if err!= nil { - fmt.Printf("Error retrieving customers: %v\n", err) - return - } - - fmt.Printf("Retrieved customers: %+v\n", customers) -} \ No newline at end of file diff --git a/pkg/examples/customers/retrieve-customers/retrieve-customer.go b/pkg/examples/customers/retrieve-customers/retrieve-customer.go deleted file mode 100644 index bf58265..0000000 --- a/pkg/examples/customers/retrieve-customers/retrieve-customer.go +++ /dev/null @@ -1,31 +0,0 @@ -package retrievecustomers - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Retrieve a single customer by ID - customerID := "your-customer-id" // you should always provide a valid customer ID that already Exists - customer, err := client.GetCustomer(customerID) - if err!= nil { - fmt.Printf("Error retrieving customer: %v\n", err) - return - } - - fmt.Printf("Retrieved customer: %+v\n", customer) -} \ No newline at end of file diff --git a/pkg/examples/customers/update-customers/update-customer.go b/pkg/examples/customers/update-customers/update-customer.go deleted file mode 100644 index f460abb..0000000 --- a/pkg/examples/customers/update-customers/update-customer.go +++ /dev/null @@ -1,48 +0,0 @@ -package customers - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Update a customer data - customerParams := &chargily.CreateCustomerParams{ - Name: "John Doe", - Email: "john.doe@example.com", - Phone: "+1 123 456 7890", - Address: &chargily.Address{ - Address: "123 Main St", - City: "New York", - State: "NY", - ZipCode: "10001", - Country: "US", - }, - Metadata: map[string]any{ - "custom_field": "value", - }, - } - - // Get a customer by ID - customerID := "your-customer-id" // you should always provide a valid customer ID that already Exists - customer, err := client.UpdateCustomer(customerID,customerParams) - if err!= nil { - fmt.Printf("Error getting customer: %v\n", err) - return - } - - fmt.Printf("Updated customer: %+v\n", customer) -} \ No newline at end of file diff --git a/pkg/examples/customers/update.go b/pkg/examples/customers/update.go new file mode 100644 index 0000000..d1880c3 --- /dev/null +++ b/pkg/examples/customers/update.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// UpdateCustomer demonstrates how to update an existing customer's details using the Chargily SDK. +func UpdateCustomer(customerID string, client * chargily.Client) { + + // Define the parameters for updating the customer. + customerParams := &models.CreateCustomerParams{ + Email: "john.updated.doe@example.com", // Updated email + Address: &models.Address{ + Address: "1234 Main St", // Updated street address + State: "NYC", // State + Country: "USA", // Country + }, + } + + // Call the Update method on the Customers service to update the customer. + customer, err := client.Customers.Update(customerID, customerParams) + if err != nil { + // Handle update error. + fmt.Printf("Error updating customer: %v\n", err) + return + } + // Output the successfully updated customer details. + fmt.Printf("Customer updated successfully: %+v\n", *customer) +} diff --git a/pkg/examples/payments/create-payment-link/create-payment-links.go b/pkg/examples/payments/create-payment-link/create-payment-links.go deleted file mode 100644 index 0252ec8..0000000 --- a/pkg/examples/payments/create-payment-link/create-payment-links.go +++ /dev/null @@ -1,57 +0,0 @@ -package retrievecheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - - // Create items to be added to the payment link - itemss := []chargily.PItems{ - { - Price: "01j9k9m78jp18bdky07s0rxxtg", - Quantity: 2, - AdjustableQuantity: true, - }, - } - - // Create the payment link parameters - paymentLinkParams := &chargily.CreatePaymentLinkParams{ - Name: "Test Order for Payment Link", - Items: itemss, - AfterCompletionMessage: "Thank you for your order!", - Locale: "en", - PassFeesToCustomer: false, - CollectShippingAddress: 1, - Metadata: map[string]any{ - "order_id": "order_54321", - "notes": "This is a test order for payment link.", - }, - } - - // Create the payment link - paymentLink, err := client.CreatePaymentLink(paymentLinkParams) - if err!= nil { - fmt.Printf("Error creating payment link: %v\n", err) - return - } - - fmt.Printf("created payment link: %+v\n", paymentLink) -} \ No newline at end of file diff --git a/pkg/examples/payments/create.go b/pkg/examples/payments/create.go new file mode 100644 index 0000000..e56e490 --- /dev/null +++ b/pkg/examples/payments/create.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// CreatePaymentLink demonstrates how to create a payment link using the Chargily SDK. +func CreatePaymentLink(client *chargily.Client, id string) { + // Create items to be added to the payment link + items := []models.PItems{ + { + Price: id, + Quantity: 2, + AdjustableQuantity: true, + }, + } + + // Create the payment link parameters + paymentLinkParams := &models.CreatePaymentLinkParams{ + Name: "Test Order for Payment Link", + Items: items, + AfterCompletionMessage: "message", + Locale: "en", + PassFeesToCustomer: false, + CollectShippingAddress: 1, + Metadata: map[string]any{ + "order_id": "order_54321", + "notes": "This is a test order for payment link.", + }, + } + + // Create the payment link using the client. + paymentLink, err := client.PaymentLinks.Create(paymentLinkParams) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating payment link: %v\n", err) + return + } + // Output the details of the created payment link. + fmt.Printf("Payment link created successfully: %+v\n", paymentLink) +} diff --git a/pkg/examples/payments/get.go b/pkg/examples/payments/get.go new file mode 100644 index 0000000..7806de0 --- /dev/null +++ b/pkg/examples/payments/get.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// RetrievePaymentLink demonstrates how to retrieve a specific payment link using the Chargily SDK. +func RetrievePaymentLink(client *chargily.Client, paymentLinkID string) { + // Retrieve the payment link using its ID. + paymentLinkData, err := client.PaymentLinks.Get(paymentLinkID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving payment link: %v\n", err) + return + } + // Output the details of the retrieved payment link. + fmt.Printf("Payment link retrieved successfully: %+v\n", paymentLinkData) +} diff --git a/pkg/examples/payments/get_all.go b/pkg/examples/payments/get_all.go new file mode 100644 index 0000000..03bacd0 --- /dev/null +++ b/pkg/examples/payments/get_all.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// ListAllPaymentLinks demonstrates how to retrieve all payment links using the Chargily SDK. +func ListAllPaymentLinks(client *chargily.Client) { + // Call the GetAll method on the PaymentLinks service to retrieve all payment links. + paymentLinks, err := client.PaymentLinks.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all payment links: %v\n", err) + return + } + // Output the list of successfully retrieved payment links. + fmt.Printf("All payment links retrieved successfully: %+v\n", paymentLinks) +} diff --git a/pkg/examples/payments/get_items.go b/pkg/examples/payments/get_items.go new file mode 100644 index 0000000..6ff8f9f --- /dev/null +++ b/pkg/examples/payments/get_items.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// RetrievePaymentLinkItems demonstrates how to retrieve items from a specific payment link using the Chargily SDK. +func RetrievePaymentLinkItems(client *chargily.Client, paymentLinkID string) { + // Retrieve the items from the payment link using its ID. + paymentLinkItems, err := client.PaymentLinks.GetItems(paymentLinkID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving payment link items: %v\n", err) + return + } + // Output the details of the retrieved payment link items. + fmt.Printf("Payment link items retrieved successfully: %+v\n", paymentLinkItems) +} diff --git a/pkg/examples/payments/retrieve-all-payment-links/retrieve-all-payment-links.go b/pkg/examples/payments/retrieve-all-payment-links/retrieve-all-payment-links.go deleted file mode 100644 index b239a29..0000000 --- a/pkg/examples/payments/retrieve-all-payment-links/retrieve-all-payment-links.go +++ /dev/null @@ -1,33 +0,0 @@ -package retrieveallpaymentlinks - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // retrieve all payment links - paymentLinks, err := client.GetAllPaymentLinks() - if err!= nil { - fmt.Printf("Error retrieving all payment links: %v\n", err) - return - } - - fmt.Printf("payment-links: %+v\n", paymentLinks) -} \ No newline at end of file diff --git a/pkg/examples/payments/retrieve-payment-links/retrieve-payment-link.go b/pkg/examples/payments/retrieve-payment-links/retrieve-payment-link.go deleted file mode 100644 index 733eac5..0000000 --- a/pkg/examples/payments/retrieve-payment-links/retrieve-payment-link.go +++ /dev/null @@ -1,37 +0,0 @@ -package retrievecheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - - // payment link id - paymentLinkId := "your-payment-link-id" // make sure to be a valid payment link id - - // retrieve the payment link - paymentLink, err := client.GetPaymentLink(paymentLinkId) - if err!= nil { - fmt.Printf("Error retrieving payment link by ID: %v\n", err) - return - } - - fmt.Printf("retrieved payment link: %+v\n", paymentLink) -} \ No newline at end of file diff --git a/pkg/examples/payments/retrieve-paymentlink-items/retrieve-payment-link-items.go b/pkg/examples/payments/retrieve-paymentlink-items/retrieve-payment-link-items.go deleted file mode 100644 index b249e16..0000000 --- a/pkg/examples/payments/retrieve-paymentlink-items/retrieve-payment-link-items.go +++ /dev/null @@ -1,35 +0,0 @@ -package retrievecheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - - //payment link ID - paymentLinkId := "existing-payment-link-id" //must be unique and existing - - // retrieve a payment link's items - paymentLinkItems, err := client.GetPaymentLinkItems(string(paymentLinkId)) - if err!= nil { - fmt.Printf("Error getting payment link items: %v\n", err) - return - } - fmt.Printf("Payment link items retrieved successfully: %+v\n\n\n\n", paymentLinkItems) -} \ No newline at end of file diff --git a/pkg/examples/payments/update-payment-link/update-payment-link.go b/pkg/examples/payments/update-payment-link/update-payment-link.go deleted file mode 100644 index 1ced949..0000000 --- a/pkg/examples/payments/update-payment-link/update-payment-link.go +++ /dev/null @@ -1,60 +0,0 @@ -package retrievecheckouts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - - // Create items to be added to the payment link - itemss := []chargily.PItems{ - { - Price: "01j9k9m78jp18bdky07s0rxxtg", - Quantity: 2, - AdjustableQuantity: true, - }, - } - - // updated payment link data - paymentLinkParams := &chargily.CreatePaymentLinkParams{ - Name: "Test Order for Payment Link", - Items: itemss, - AfterCompletionMessage: "Thank you for your order!", - Locale: "en", - PassFeesToCustomer: true, - CollectShippingAddress: 0, - Metadata: map[string]any{ - "order_id": "order_54321", - "notes": "This is a test order for payment link.", - }, - } - - - // the id of payment id to be updated - paymentLinkId:= "your-payment-link-id" - - // update - paymentLink, err := client.UpdatePaymentLink(paymentLinkId,paymentLinkParams) - if err!= nil { - fmt.Printf("Error updating payment link: %v\n", err) - return - } - - fmt.Printf("updated payment link: %+v\n", paymentLink) -} \ No newline at end of file diff --git a/pkg/examples/payments/update.go b/pkg/examples/payments/update.go new file mode 100644 index 0000000..93c5213 --- /dev/null +++ b/pkg/examples/payments/update.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// UpdatePaymentLink demonstrates how to update an existing payment link using the Chargily SDK. +func UpdatePaymentLink(client *chargily.Client, paymentLinkID string) { + // Prepare updated payment link parameters. + updatedPaymentLinkParams := &models.CreatePaymentLinkParams{ + Name: "Updated Test Order for Payment Link", + Items: []models.PItems{ + { + Price: paymentLinkID, + Quantity: 2, + AdjustableQuantity: true, + }, + }, + AfterCompletionMessage: "Thank you for your updated order!", + Locale: "en", + PassFeesToCustomer: false, + CollectShippingAddress: 0, + Metadata: map[string]any{ + "order_id": "updated_order_54321", + "notes": "This is an updated test order for payment link.", + }, + } + + // Update the payment link using the client. + updatedPaymentLink, err := client.PaymentLinks.Update(paymentLinkID, updatedPaymentLinkParams) + if err != nil { + // Handle update error. + fmt.Printf("Error updating payment link: %v\n", err) + return + } + // Output the details of the updated payment link. + fmt.Printf("Payment link updated successfully: %+v\n", updatedPaymentLink) +} diff --git a/pkg/examples/prices/create-prices/create-price.go b/pkg/examples/prices/create-prices/create-price.go deleted file mode 100644 index 79c8a98..0000000 --- a/pkg/examples/prices/create-prices/create-price.go +++ /dev/null @@ -1,38 +0,0 @@ -package createprices - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Create a new price - price := &chargily.ProductPriceParams{ - ProductID: "your-product-id", - Currency: "USD", - Amount: 100, - Metadata: map[string]any{"key":"value"}, - } - - // update the price metadata - productPrice, err := client.CreatePrice(price) - if err!= nil { - fmt.Printf("Error creating price: %v\n", err) - } - - - fmt.Printf("Created price: %+v\n", productPrice) -} \ No newline at end of file diff --git a/pkg/examples/prices/create_price.go b/pkg/examples/prices/create_price.go new file mode 100644 index 0000000..9cf45a1 --- /dev/null +++ b/pkg/examples/prices/create_price.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// CreatePrice demonstrates how to create a price for a product using the Chargily SDK. +func CreatePrice(client *chargily.Client, productID string) { + // Define the parameters for the new price. + bodyRequestPrice := &models.ProductPriceParams{ + Amount: 10000, + Currency: "dzd", + ProductID: productID, // Product ID to associate with this price + Metadata: map[string]any{"key": "value"}, + } + + // Call the Create method on the Prices service to create the price. + price, err := client.Prices.Create(bodyRequestPrice) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating price: %v\n", err) + return + } + // Output the details of the successfully created price. + fmt.Printf("Price created successfully: %+v\n", price) +} diff --git a/pkg/examples/prices/get.go b/pkg/examples/prices/get.go new file mode 100644 index 0000000..e5ae816 --- /dev/null +++ b/pkg/examples/prices/get.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// RetrievePrice demonstrates how to retrieve a specific price using the Chargily SDK. +func RetrievePrice(client *chargily.Client, priceID string) { + // Retrieve the price by its ID. + price, err := client.Prices.Get(priceID) + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving price: %v\n", err) + return + } + // Output the details of the retrieved price. + fmt.Printf("Price retrieved successfully: %+v\n", price) +} diff --git a/pkg/examples/prices/get_all.go b/pkg/examples/prices/get_all.go new file mode 100644 index 0000000..4631679 --- /dev/null +++ b/pkg/examples/prices/get_all.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// GetAllPrices demonstrates how to retrieve all prices using the Chargily SDK. +func GetAllPrices(client *chargily.Client) { + // Call the GetAll method on the Prices service to retrieve all prices. + prices, err := client.Prices.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all prices: %v\n", err) + return + } + // Output the list of successfully retrieved prices. + fmt.Printf("All prices retrieved successfully: %+v\n", prices) +} diff --git a/pkg/examples/prices/reterive-all-prices/retrieve-all-prices.go b/pkg/examples/prices/reterive-all-prices/retrieve-all-prices.go deleted file mode 100644 index 3a700ab..0000000 --- a/pkg/examples/prices/reterive-all-prices/retrieve-all-prices.go +++ /dev/null @@ -1,30 +0,0 @@ -package reteriveallprices - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // create the product price and get back the price object - prices, err := client.GetAllPrices() - if err!= nil { - fmt.Printf("Error while retrieving price: %v\n", err) - } - - - fmt.Printf("all prices: %+v\n", prices) -} \ No newline at end of file diff --git a/pkg/examples/prices/retrieve-prices/retrieve-price.go b/pkg/examples/prices/retrieve-prices/retrieve-price.go deleted file mode 100644 index 98898ec..0000000 --- a/pkg/examples/prices/retrieve-prices/retrieve-price.go +++ /dev/null @@ -1,33 +0,0 @@ -package retrieveprices - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - //product ID - prodId := "your-product-id" - - // create the product price and get back the price object - productPrice, err := client.GetPrice(prodId) - if err!= nil { - fmt.Printf("Error while retrieving price: %v\n", err) - } - - - fmt.Printf("price: %+v\n", productPrice) -} \ No newline at end of file diff --git a/pkg/examples/prices/update-prices/update-price.go b/pkg/examples/prices/update-prices/update-price.go deleted file mode 100644 index a5c6273..0000000 --- a/pkg/examples/prices/update-prices/update-price.go +++ /dev/null @@ -1,39 +0,0 @@ -package updateprices - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Create a new customer - price := &chargily.UpdatePriceMetaDataParams{ - Metadata: map[string]any{"key":"val"}, - } - - - //product ID - prodId := "your-product-id" - - // create the product price and get back the price object - productPrice, err := client.UpdatePrice(prodId,price) - if err!= nil { - fmt.Printf("Error updating price: %v\n", err) - } - - - fmt.Printf("updated price: %+v\n", productPrice) -} \ No newline at end of file diff --git a/pkg/examples/prices/update.go b/pkg/examples/prices/update.go new file mode 100644 index 0000000..48f93a6 --- /dev/null +++ b/pkg/examples/prices/update.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// UpdatePrice demonstrates how to update an existing price's metadata using the Chargily SDK. +func UpdatePrice(client *chargily.Client, priceID string) { + // Define the parameters for updating the price metadata. + data := &models.UpdatePriceMetaDataParams{ + Metadata: map[string]any{"new_key": "new_value", "key3": "keykey"}, + } + + // Call the Update method on the Prices service to update the price. + price, err := client.Prices.Update(priceID, data) + if err != nil { + // Handle update error. + fmt.Printf("Error updating price: %v\n", err) + return + } + // Output the details of the successfully updated price. + fmt.Printf("Price updated successfully: %+v\n", price) +} diff --git a/pkg/examples/products/create-products/create-product.go b/pkg/examples/products/create-products/create-product.go deleted file mode 100644 index 41313d9..0000000 --- a/pkg/examples/products/create-products/create-product.go +++ /dev/null @@ -1,36 +0,0 @@ -package createproducts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // Create a new product - product := &chargily.CreateProductParams{ - Name: "New Product", - Description: "This is a new product", - Images: []string{"link1","link2","link3"}, - Metadata: map[string]any{"key0": "value0","key1":"value1"}, - } - - newProduct, err := client.CreateProduct(product) - if err!= nil { - fmt.Printf("Error creating product: %v\n", err) - return - } - fmt.Printf("Created product: %+v\n", newProduct) -} \ No newline at end of file diff --git a/pkg/examples/products/create.go b/pkg/examples/products/create.go new file mode 100644 index 0000000..7c0c83a --- /dev/null +++ b/pkg/examples/products/create.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// CreateProduct demonstrates how to create a new product using the Chargily SDK. +func CreateProduct(client *chargily.Client) { + // Define the parameters for the new product. + bodyRequestProduct := &models.CreateProductParams{ + Name: "Test Product", + Description: "This is a test product", + Images: []string{"valid-image-link"}, + Metadata: map[string]any{"key": "value"}, + } + + // Call the Create method on the Products service to create the product. + product, err := client.Products.Create(bodyRequestProduct) + if err != nil { + // Handle creation error. + fmt.Printf("Error creating product: %v\n", err) + return + } + // Output the details of the successfully created product. + fmt.Printf("Product created successfully: %+v\n", product) +} diff --git a/pkg/examples/products/delete-products/delete-product.go b/pkg/examples/products/delete-products/delete-product.go deleted file mode 100644 index dde4a48..0000000 --- a/pkg/examples/products/delete-products/delete-product.go +++ /dev/null @@ -1,32 +0,0 @@ -package deleteproducts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // the id of the product to update - id := "your-product-id" // make sure to provide a valid id for the product - - // Update the product - err = client.DeleteProduct(string(id)) - if err!= nil { - fmt.Printf("Error updating product: %v\n", err) - return - } - fmt.Print("Product Deleted successfully") -} \ No newline at end of file diff --git a/pkg/examples/products/delete.go b/pkg/examples/products/delete.go new file mode 100644 index 0000000..b08c6b7 --- /dev/null +++ b/pkg/examples/products/delete.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// DeleteProduct demonstrates how to delete an existing product using the Chargily SDK. +func DeleteProduct(client *chargily.Client, productID string) { + // Call the Delete method on the Products service to delete the product by ID. + if err := client.Products.Delete(productID); err != nil { + // Handle deletion error. + fmt.Printf("Error deleting product: %v\n", err) + return + } + // Output a success message for deletion. + fmt.Println("Product deleted successfully.") +} diff --git a/pkg/examples/products/get_all.go b/pkg/examples/products/get_all.go new file mode 100644 index 0000000..45d061b --- /dev/null +++ b/pkg/examples/products/get_all.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// GetAllProducts demonstrates how to retrieve all products using the Chargily SDK. +func GetAllProducts(client *chargily.Client) { + // Call the GetAll method on the Products service to retrieve all products. + products, err := client.Products.GetAll() + if err != nil { + // Handle retrieval error. + fmt.Printf("Error retrieving all products: %v\n", err) + return + } + // Output the list of successfully retrieved products. + fmt.Printf("All products retrieved successfully: %+v\n", products) +} diff --git a/pkg/examples/products/get_price.go b/pkg/examples/products/get_price.go new file mode 100644 index 0000000..452d730 --- /dev/null +++ b/pkg/examples/products/get_price.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + + + + +func GetProductPrices(productId string, client * chargily.Client){ + // Get a product price + prices, err := client.Products.GetPrices(productId) + if err!= nil { + fmt.Println("Error retrieving product price:", err) + } + + fmt.Printf("Product prices : %v", prices) +} \ No newline at end of file diff --git a/pkg/examples/products/retrieve-all-products/retrieve-all-products.go b/pkg/examples/products/retrieve-all-products/retrieve-all-products.go deleted file mode 100644 index 41b7dcf..0000000 --- a/pkg/examples/products/retrieve-all-products/retrieve-all-products.go +++ /dev/null @@ -1,29 +0,0 @@ -package retrieveallproducts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // get all products - products, err := client.GetAllProducts() - if err!= nil { - fmt.Printf("Error updating product: %v\n", err) - return - } - fmt.Printf("products : %+v\n", products.Data) -} \ No newline at end of file diff --git a/pkg/examples/products/retrieve-products-price/retrieve-products-price.go b/pkg/examples/products/retrieve-products-price/retrieve-products-price.go deleted file mode 100644 index b93ff6d..0000000 --- a/pkg/examples/products/retrieve-products-price/retrieve-products-price.go +++ /dev/null @@ -1,32 +0,0 @@ -package retrieveproductsprice - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // the id of the product to update - id := "your-product-id" // make sure to provide a valid id for the product - - // grab the product prices - productPrices, err := client.GetProductPrices(string(id)) - if err!= nil { - fmt.Printf("Error updating product: %v\n", err) - return - } - fmt.Printf("product prices: %+v\n", productPrices) -} \ No newline at end of file diff --git a/pkg/examples/products/retrieve-products/retrieve-product.go b/pkg/examples/products/retrieve-products/retrieve-product.go deleted file mode 100644 index 5f23a6c..0000000 --- a/pkg/examples/products/retrieve-products/retrieve-product.go +++ /dev/null @@ -1,32 +0,0 @@ -package retrieveproducts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // the id of the product to update - id := "your-product-id" // make sure to provide a valid id for the product - - // Update the product - product, err := client.GetProduct(string(id)) - if err!= nil { - fmt.Printf("Error updating product: %v\n", err) - return - } - fmt.Printf("product: %+v\n", product) -} \ No newline at end of file diff --git a/pkg/examples/products/update-products/update-product.go b/pkg/examples/products/update-products/update-product.go deleted file mode 100644 index 42577d1..0000000 --- a/pkg/examples/products/update-products/update-product.go +++ /dev/null @@ -1,41 +0,0 @@ -package updateproducts - -import ( - "fmt" - - "github.com/Chargily/chargily-pay-go/pkg/chargily" -) - - -func main(){ - // Define your API key and mode - apiKey := "your-api-key" - mode := "test" // Could be "prod" or "test" - - // Create a new client instance - client, err := chargily.NewClient(apiKey, mode) - if err!= nil { - fmt.Printf("Error creating client: %v\n", err) - return - } - - // new data - product := &chargily.CreateProductParams{ - Name: "updated Product", - Description: "This is an updates product", - Images: []string{"link1","link2","link3","link4"}, - Metadata: map[string]any{"key0": "value0"}, - } - - - // the id of the product to update - id := "your-product-id" // make sure to provide a valid id for the product - - // Update the product - updatedProduct, err := client.UpdateProduct(string(id), product) - if err!= nil { - fmt.Printf("Error updating product: %v\n", err) - return - } - fmt.Printf("Updated product: %+v\n", updatedProduct) -} \ No newline at end of file diff --git a/pkg/examples/products/update.go b/pkg/examples/products/update.go new file mode 100644 index 0000000..ec09b47 --- /dev/null +++ b/pkg/examples/products/update.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + +// UpdateProduct demonstrates how to update an existing product's details using the Chargily SDK. +func UpdateProduct(client *chargily.Client, productID string) { + // Define the parameters for updating the product. + bodyRequestProduct := &models.CreateProductParams{ + Name: "Test Product of the Update", + Description: "This is an updated test product", + Images: []string{"valid-image-link"}, + Metadata: map[string]any{"key": "value"}, + } + + // Call the Update method on the Products service to update the product. + product, err := client.Products.Update(productID, bodyRequestProduct) + if err != nil { + // Handle update error. + fmt.Printf("Error updating product: %v\n", err) + return + } + // Output the details of the successfully updated product. + fmt.Printf("Product updated successfully: %+v\n", product) +} diff --git a/pkg/examples/webhook/setup.go b/pkg/examples/webhook/setup.go new file mode 100644 index 0000000..a910e0d --- /dev/null +++ b/pkg/examples/webhook/setup.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "log" + "net/http" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/models" +) + + +func SetupWebhook(client * chargily.Client){ + // Setup the webhook endpoint to listen for webhook events on `/webhook` + client.Webhook.SetupHandler("/webhook", handleEvent) + // Start the server + log.Fatal(http.ListenAndServe(":8080", nil)) +} + + +// Custom event handler function that processes events +func handleEvent(eventType string, event models.WebhookEvent) { + // Handle different event types (e.g., `checkout.paid`, etc.) + switch eventType { + case "checkout.paid": + // Process a successful payment + fmt.Printf("Received paid event: %+v\n", event) + // Do something with the event data (e.g., update order status) + case "checkout.failed": + // Handle failed payment + fmt.Println("Payment failed for event ID:", event.ID) + default: + fmt.Printf("Unhandled event type: %s\n", eventType) + } +} \ No newline at end of file diff --git a/pkg/examples/webhook/verify-sig.go b/pkg/examples/webhook/verify-sig.go new file mode 100644 index 0000000..116dc84 --- /dev/null +++ b/pkg/examples/webhook/verify-sig.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + + "github.com/Chargily/chargily-pay-go/pkg/chargily" +) + +// Example function to verify the signature +func VerifySig( payload []byte, signature string , client * chargily.Client){ + // pass the payload and the signature into the client verifier + err := client.Webhook.VerifySignature(payload, signature) + + // Handle errors + if err != nil { + fmt.Printf("Error verifying signature %v\n", err) + } +} \ No newline at end of file diff --git a/pkg/models/params.go b/pkg/models/params.go new file mode 100644 index 0000000..e8d53d8 --- /dev/null +++ b/pkg/models/params.go @@ -0,0 +1,75 @@ +package models + +//******************************************************************// +//=========================== PARAMS ===============================// +///////////////////////////////////////////////////////////////////// + +// CreateCustomerParams represents the parameters for creating a customer. +type CreateCustomerParams struct { + Name string `json:"name,omitempty"` // The name of the customer. + Email string `json:"email,omitempty"` // The email address of the customer. + Phone string `json:"phone,omitempty"` // The phone number of the customer. + Address *Address `json:"address,omitempty"` // The address of the customer. + Metadata map[string]any `json:"metadata,omitempty"` // Additional info about the customer. +} + + +// price operations related structs +type ProductPriceParams struct { + Amount int64 `json:"amount"` // The price amount in cents. + Currency string `json:"currency"` // The currency code (e.g., "dzd", "usd", "eur"). + ProductID string `json:"product_id"` // The ID of the product to which the price applies. + Metadata map[string]any `json:"metadata,omitempty"` // Additional information about the price. +} + + +// Creating a new product params +type CreateProductParams struct { + Name string `json:"name,omitempty"` // The name of the product. + Description string `json:"description,omitempty"` // The description of the product. + Images []string `json:"images,omitempty"` // The URLs of images of the product, up to 8. + Metadata map[string]any `json:"metadata,omitempty"` // A set of key-value pairs for additional information about the product. +} + + + +//update PriceMetaData +type UpdatePriceMetaDataParams struct { + Metadata map[string]any `json:"metadata"` // Additional information about the price. +} + + + +// CheckoutParams represents the parameters required to create a checkout. +type CheckoutParams struct { + Items []CItems `json:"items,omitempty"` // Optional. The items to be added to the checkout. + Amount int `json:"amount,omitempty"` // Required if items are not provided. The total amount in cents. + Currency string `json:"currency,omitempty"` // Required if amount is provided. ISO currency code (e.g., "dzd"). + PaymentMethod string `json:"payment_method,omitempty"` // Optional. Payment method (e.g., "edahabia", "cib"). + SuccessURL string `json:"success_url"` // Required. URL to redirect after successful payment. + CustomerID string `json:"customer_id,omitempty"` // Optional. ID of the existing customer. + FailureURL string `json:"failure_url,omitempty"` // Optional. URL to redirect after failed/canceled payment. + WebhookEndpoint string `json:"webhook_endpoint,omitempty"` // Optional. URL to receive webhook events after checkout. + Description string `json:"description,omitempty"` // Optional. Description of the checkout. + Locale string `json:"locale,omitempty"` // Optional. Checkout page language (e.g., "en", "fr", "ar"). + ShippingAddress string `json:"shipping_address,omitempty"` // Optional. Customer's shipping address. + CollectShippingAddress bool `json:"collect_shipping_address,omitempty"` // Optional. Whether to collect the shipping address from the customer. + PercentageDiscount int `json:"percentage_discount,omitempty"` // Optional. Percentage discount, prohibited if amount discount is provided. + AmountDiscount int `json:"amount_discount,omitempty"` // Optional. Amount discount in cents, prohibited if percentage discount is provided. + Metadata map[string]any `json:"metadata,omitempty"` // Optional. Additional key-value pairs for extra checkout information. +} + + + +// Create a new payment link +type CreatePaymentLinkParams struct { + Name string `json:"name"` // The name associated with the order. + Items []PItems `json:"items"` // A list of items in the order. + AfterCompletionMessage string `json:"after_completion_message"` // A message displayed after order completion. + Locale string `json:"locale"` // The locale (e.g., "en", "fr"). + PassFeesToCustomer bool `json:"pass_fees_to_customer"` // Indicates if fees are passed to the customer. + CollectShippingAddress int32 `json:"collect_shipping_address"` // Indicates whether to collect a shipping address. + Metadata map[string]any `json:"metadata"` // Additional metadata for the order. +} + +//////////////////////////////////////////////////////////////////// diff --git a/pkg/models/responses.go b/pkg/models/responses.go new file mode 100644 index 0000000..0518283 --- /dev/null +++ b/pkg/models/responses.go @@ -0,0 +1,19 @@ +package models + +//================= GENERIC RESPONSES FOR AN ARRAY OF DATA OF THE SAME TYPE =========================// +/////////////////////////////////////////////////////////////////////////////////////////////////////// +// Generic response for retrieving all entries of any type +type RetrieveAll[T any] struct { + Livemode bool `json:"livemode"` + CurrentPage int `json:"current_page"` + Data []T `json:"data"` + FirstPageURL string `json:"first_page_url"` + LastPage int `json:"last_page"` + LastPageURL string `json:"last_page_url"` + NextPageURL *string `json:"next_page_url"` + Path string `json:"path"` + PerPage int `json:"per_page"` + PrevPageURL *string `json:"prev_page_url"` + Total int `json:"total"` +} +///////////////////////////////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/pkg/chargily/chargily.go b/pkg/models/types.go similarity index 63% rename from pkg/chargily/chargily.go rename to pkg/models/types.go index 24cd3a4..5bb802c 100644 --- a/pkg/chargily/chargily.go +++ b/pkg/models/types.go @@ -1,25 +1,25 @@ -package chargily +package models //******************************************************************// -//=========================== COMMON TYPES =========================// +//=========================== TYPES =========================// ///////////////////////////////////////////////////////////////////// // Address represents a customer's address. type Address struct { - Address string `json:"address,omitempty"` - City string `json:"city,omitempty"` - State string `json:"state,omitempty"` - ZipCode string `json:"zip_code,omitempty"` - Country string `json:"country,omitempty"` + Address string `json:"address,omitempty"` + City string `json:"city,omitempty"` + State string `json:"state,omitempty"` + ZipCode string `json:"zip_code,omitempty"` + Country string `json:"country,omitempty"` } // Wallet represents the balance details for a specific currency. type Wallet struct { - Currency string `json:"currency"` // The currency of the wallet (e.g., "dzd", "usd", "eur") - Balance int64 `json:"balance"` // The total balance in the wallet - ReadyForPayout string `json:"ready_for_payout"` // The amount ready for payout - OnHold int64 `json:"on_hold"` // The amount on hold + Currency string `json:"currency"` // The currency of the wallet (e.g., "dzd", "usd", "eur") + Balance int64 `json:"balance"` // The total balance in the wallet + ReadyForPayout string `json:"ready_for_payout"` // The amount ready for payout + OnHold int64 `json:"on_hold"` // The amount on hold } @@ -84,106 +84,6 @@ type PItemsData struct { -///////////////////////////////////////////////////////////////////// - - - - - - -//******************************************************************// -//=========================== PARAMS ===============================// -///////////////////////////////////////////////////////////////////// - -// CreateCustomerParams represents the parameters for creating a customer. -type CreateCustomerParams struct { - Name string `json:"name,omitempty"` // The name of the customer. - Email string `json:"email,omitempty"` // The email address of the customer. - Phone string `json:"phone,omitempty"` // The phone number of the customer. - Address *Address `json:"address,omitempty"` // The address of the customer. - Metadata map[string]any `json:"metadata,omitempty"` // Additional info about the customer. -} - - -// price operations related structs -type ProductPriceParams struct { - Amount int64 `json:"amount"` // The price amount in cents. - Currency string `json:"currency"` // The currency code (e.g., "dzd", "usd", "eur"). - ProductID string `json:"product_id"` // The ID of the product to which the price applies. - Metadata map[string]any `json:"metadata,omitempty"` // Additional information about the price. -} - - -// Creating a new product params -type CreateProductParams struct { - Name string `json:"name,omitempty"` // The name of the product. - Description string `json:"description,omitempty"` // The description of the product. - Images []string `json:"images,omitempty"` // The URLs of images of the product, up to 8. - Metadata map[string]any `json:"metadata,omitempty"` // A set of key-value pairs for additional information about the product. -} - - - -//update PriceMetaData -type UpdatePriceMetaDataParams struct { - Metadata map[string]any `json:"metadata"` // Additional information about the price. -} - - - -// CheckoutParams represents the parameters required to create a checkout. -type CheckoutParams struct { - Items []CItems `json:"items,omitempty"` // Optional. The items to be added to the checkout. - Amount int `json:"amount,omitempty"` // Required if items are not provided. The total amount in cents. - Currency string `json:"currency,omitempty"` // Required if amount is provided. ISO currency code (e.g., "dzd"). - PaymentMethod string `json:"payment_method,omitempty"` // Optional. Payment method (e.g., "edahabia", "cib"). - SuccessURL string `json:"success_url"` // Required. URL to redirect after successful payment. - CustomerID string `json:"customer_id,omitempty"` // Optional. ID of the existing customer. - FailureURL string `json:"failure_url,omitempty"` // Optional. URL to redirect after failed/canceled payment. - WebhookEndpoint string `json:"webhook_endpoint,omitempty"` // Optional. URL to receive webhook events after checkout. - Description string `json:"description,omitempty"` // Optional. Description of the checkout. - Locale string `json:"locale,omitempty"` // Optional. Checkout page language (e.g., "en", "fr", "ar"). - ShippingAddress string `json:"shipping_address,omitempty"` // Optional. Customer's shipping address. - CollectShippingAddress bool `json:"collect_shipping_address,omitempty"` // Optional. Whether to collect the shipping address from the customer. - PercentageDiscount int `json:"percentage_discount,omitempty"` // Optional. Percentage discount, prohibited if amount discount is provided. - AmountDiscount int `json:"amount_discount,omitempty"` // Optional. Amount discount in cents, prohibited if percentage discount is provided. - Metadata map[string]any `json:"metadata,omitempty"` // Optional. Additional key-value pairs for extra checkout information. -} - - - -// Create a new payment link -type CreatePaymentLinkParams struct { - Name string `json:"name"` // The name associated with the order. - Items []PItems `json:"items"` // A list of items in the order. - AfterCompletionMessage string `json:"after_completion_message"` // A message displayed after order completion. - Locale string `json:"locale"` // The locale (e.g., "en", "fr"). - PassFeesToCustomer bool `json:"pass_fees_to_customer"` // Indicates if fees are passed to the customer. - CollectShippingAddress int32 `json:"collect_shipping_address"` // Indicates whether to collect a shipping address. - Metadata map[string]any `json:"metadata"` // Additional metadata for the order. -} - - - -//////////////////////////////////////////////////////////////////// - - - - - - - - - - - - - - -///******************************************************************// -//====================== Responses and Types ========================// - - // Balance represents the overall balance entity. type Balance struct { Entity string `json:"entity"` // The entity type (e.g., "balance") @@ -254,7 +154,6 @@ type Checkout struct { } - // Payment Links type PaymentLink struct { ID string `json:"id"` // The unique identifier of the payment link. @@ -273,28 +172,42 @@ type PaymentLink struct { } -//////////////////////////////////////////////////////////////////// - - - - -//=================G GENERIC RESPONSES =========================// -////////////////////////////////////////////////////////////////// - - -// Generic response for retrieving all entries of any type -type RetrieveAll[T any] struct { - Livemode bool `json:"livemode"` - CurrentPage int `json:"current_page"` - Data []T `json:"data"` - FirstPageURL string `json:"first_page_url"` - LastPage int `json:"last_page"` - LastPageURL string `json:"last_page_url"` - NextPageURL *string `json:"next_page_url"` - Path string `json:"path"` - PerPage int `json:"per_page"` - PrevPageURL *string `json:"prev_page_url"` - Total int `json:"total"` -} - -///////////////////////////////////////////////////////////////// \ No newline at end of file +// event structure +type WebhookEvent struct { + ID string `json:"id"` + Entity string `json:"entity"` + LiveMode bool `json:"livemode,string"` + Type string `json:"type"` + Data eventData `json:"data"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` +} + +// Nested checkout data structure +type eventData struct { + ID string `json:"id"` + Entity string `json:"entity"` + Fees int `json:"fees"` + Amount int `json:"amount"` + Locale string `json:"locale"` + Status string `json:"status"` + Metadata *string `json:"metadata"` // nullable field + CreatedAt int64 `json:"created_at"` + InvoiceID *string `json:"invoice_id"` // nullable field + UpdatedAt int64 `json:"updated_at"` + CustomerID string `json:"customer_id"` + Description *string `json:"description"` // nullable field + FailureURL *string `json:"failure_url"` // nullable field + SuccessURL string `json:"success_url"` + PaymentMethod *string `json:"payment_method"` // nullable field + PaymentLinkID *string `json:"payment_link_id"` // nullable field + PassFeesToCustomer *bool `json:"pass_fees_to_customer"` // nullable field + ChargilyPayFeesAllocation string `json:"chargily_pay_fees_allocation"` + ShippingAddress *string `json:"shipping_address"` // nullable field + CollectShippingAddress int `json:"collect_shipping_address"` + Discount *int `json:"discount"` // nullable field + AmountWithoutDiscount *int `json:"amount_without_discount"` // nullable field + URL string `json:"url"` +} + +///////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/pkg/unit_tests/client_test.go b/pkg/unit_tests/client_test.go index 2a5bdf5..8e874ab 100644 --- a/pkg/unit_tests/client_test.go +++ b/pkg/unit_tests/client_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/chargily/utils" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) @@ -22,7 +23,7 @@ func TestNewClient(t *testing.T) { }{ {"Valid Prod Client", "test-api-key", "prod", nil}, {"Valid Test Client", "test-api-key", "test", nil}, - {"Invalid Mode", "test-api-key", "invalid", chargily.ErrInvalidMode}, + {"Invalid Mode", "test-api-key", "invalid", utils.ErrInvalidMode}, } for _, tt := range tests { diff --git a/pkg/unit_tests/requests_sender_test.go b/pkg/unit_tests/requests_sender_test.go index 3fe394c..ccc7a66 100644 --- a/pkg/unit_tests/requests_sender_test.go +++ b/pkg/unit_tests/requests_sender_test.go @@ -7,16 +7,16 @@ import ( "testing" "time" - "github.com/Chargily/chargily-pay-go/pkg/chargily" + "github.com/Chargily/chargily-pay-go/pkg/chargily/utils" "github.com/stretchr/testify/assert" ) func TestNewRequestSender(t *testing.T) { apiKey := "test_api_key" - rs := chargily.NewRequestSender(apiKey) + rs := utils.NewRequestSender(apiKey) assert.NotNil(t, rs) - assert.IsType(t, &chargily.RequestSender{}, rs) + assert.IsType(t, &utils.RequestSender{}, rs) // Type assertion to access the unexported field //concreteRS, ok := rs.(*chargily.RequestSender) @@ -49,7 +49,7 @@ func TestSendRequest(t *testing.T) { defer server.Close() // Create RequestSender - rs := chargily.NewRequestSender("test_api_key") + rs := utils.NewRequestSender("test_api_key") // Prepare request body and result requestBody := map[string]string{"test_key": "test_value"} @@ -71,7 +71,7 @@ func TestSendRequestError(t *testing.T) { defer server.Close() // Create RequestSender - rs := chargily.NewRequestSender("test_api_key") + rs := utils.NewRequestSender("test_api_key") // Send request var result map[string]string @@ -90,7 +90,7 @@ func TestSendRequestTimeout(t *testing.T) { defer server.Close() // Create RequestSender - rs := chargily.NewRequestSender("test_api_key") + rs := utils.NewRequestSender("test_api_key") // Send request var result map[string]string