Giter Club home page Giter Club logo

conekta-.net's Introduction

NET api

Conekta .NET API Library

nuget nugetdotnet CI

This is the officially supported .NET library for using Conekta's APIs.

Supported API versions

The library supports all APIs under the following services:

API Description Service Name Supported version
Payments API Our classic integration for online payments. Current supported version Payments API v2.1.0

For more information, refer to our documentation.

Prerequisites

  • Conekta account
  • API key. your API credential .
  • Conekta dotnet API Library supports .net standard 2.0 and above

Installation

Simply download and restore nuget packages https://www.nuget.org/packages/Conekta.net/ or install it from package manager

PM> Install-Package Conekta.net -Version x.x.x

Using the library

In order to submit http request to Conekta API you need to initialize the client. The following example makes a order request:

// Create a OrderRequest
using System;
using System.Collections.Generic;
using Conekta.net.Client;
using Conekta.net.Api;
using Conekta.net.Model;

// create the http client

string acceptLanguage = "en";
Configuration configuration = new()
{
    AccessToken = "Your merchant XAPI key"
};
var ordersApi = new OrdersApi(configuration);
var customerApi = new CustomersApi(config);

// create customer
var customer = new Customer(
    name: "test dot",
    phone: "+573143159063",
    email: "[email protected]"
);
CustomerResponse customerResponse = customerApi.CreateCustomer(customer);
// Create OrderRequest

var lineItems = new List<LineItems>{new (
        name: "toshiba",
        quantity: 1,
        unitPrice: 1555
    )};
var charges = new List<ChargeRequest>{new (
    amount: 1555,
    paymentMethod: new ChargeRequestPaymentMethod("cash")
)};
var customerInfo = new OrderRequestCustomerInfo(new CustomerInfoJustCustomerId(customerResponse.Id));
OrderRequest orderRequest = new OrderRequest(
    currency: "MXN",
    customerInfo: customerInfo,
    lineItems: lineItems,
    charges: charges
);
            
//Make the call to the service. This example code makes a call to /orders
OrderResponse response = ordersApi.CreateOrder(orderRequest, acceptLanguage);

Catching exception

Example

using System.Collections.Generic;
using System.Diagnostics;
using Conekta.net.Api;
using Conekta.net.Client;
using Conekta.net.Model;

namespace Example
{
    public class CreatePlanExample
    {
        public static void Main()
        {
            Configuration config = new Configuration( AccessToken = "Your merchant XAPI key");

            var apiInstance = new PlansApi(config);
            var planRequest = new PlanRequest(); // PlanRequest | requested field for plan
            var acceptLanguage = "es";  // string | Use for knowing which language to use (optional)  (default to es)

            try
            {
                // Create Plan
                PlanResponse result = apiInstance.CreatePlan(planRequest, acceptLanguage);
                Debug.WriteLine(result);
            }
            catch (ApiException  e)
            {
                Debug.Print("Exception when calling PlansApi.CreatePlan: " + e.Message);
                Debug.Print("Status Code: " + e.ErrorCode);
                Debug.Print(e.StackTrace);
            }
        }
    }
}

Running the tests

Navigate to conekta-.net folder and run the following commands.

dotnet build
dotnet test

Contributing

We encourage you to contribute to this repository, so everyone can benefit from new features, bug fixes, and any other improvements. Have a look at our contributing guidelines to find out how to raise a pull request.

Support

If you have a feature request, or spotted a bug or a technical problem, create an issue here.

For other questions, contact our Support Team.

Licence

This repository is available under the MIT license.

See also

conekta-.net's People

Contributors

andreasantillana avatar dependabot[bot] avatar fcarrero avatar hectorgool avatar jakumx avatar janee avatar julsdelatierra avatar leofischer avatar luiscarlos-gonzalez avatar mauroarcet avatar richpeniche avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

conekta-.net's Issues

Buscar Orden por referencia

Hay un método para buscar una Orden mandando como parámetro la Referencia de un pago offline? (Oxxo Pay)

Implement call to void order resource

The .net library doesn't include a call to the void resource needed to cancel a pre-authorized order.

The java and nodejs versions added this endpoint as seen here and here I could submit the code if you are open to pull requests just let me know 👍

SendFailure ó ProtocolError

Bajé la úlitma versión y al hacer la prueba de crear un customer con el ApiKey que vienen por default funciona bien, pero si pones uno tuyo, marca ProtocolError, comenté la línea: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; en Requestor.cs, pero ahora manda SendFailure.

¿Cómo lo puedo arreglar?

Async/wait methods

Hi everyone, I dont see every codes of the lib yet but, the library do has methods non blocking?

I have methods for create costumers from api rest but this methods are non blocking, I decided to change the api rest raw for this lib, but I see that for example: Customer customer = new conekta.Customer().create is bloking, then my fastest solution at the moment is it:

await Task.Run(
                () => {

                    customer = new conekta.Customer().create(json);

                });

is not elegant by I need using await by standardize, In the future you add this type method?

if not maybe I can help you with it :p

Falta campo clabe en clase charge

Hola que tal. Estamos usando la clase Charge de Conekta y al generar la referencia para spei, no existe un campo llamado clabe en la clase Charge del sdk.

var conektaCharge = new Charge().toClass(jObject.ToString());
Respuesta de sdk conekta
image

clase actual de conekta_dot_net v1.1.0
image

The token has already been used

Hi! i have a problem when a make a charge,this show me this error:

"The token has already been used"
"La tarjeta no pudo ser procesada"

when i do this with a test token this works fine but when i do it with another token this don´t work, this is my implementation.

    bool band = true;
    Order order;
    Expression<Func<Usuario, bool>> exp = (x) => x.IdUsuario == IdUsuario;
    UsuarioLoader uLoader = new UsuarioLoader();
    var usuario = uLoader.GetElementByProperty(exp);
    try
    {
        
        order = new conekta.Order().create(@"{
          ""currency"":""MXN"",
          ""customer_info"": {
            ""customer_id"": """+usuario.TokenConekta+@""" 
          },
          ""line_items"": [{
            ""name"": ""Cobro Union"",
            ""unit_price"": 1000,
            ""quantity"": 1
          }],
          ""charges"": [{
            ""payment_method"": {
               ""type"": ""card"",
                ""token_id"": """+tokenTarjeta+@"""
            },""amount"":1000
          }]
        }");

    }
    catch (ConektaException e)
    {
        band = false;
        foreach (JObject obj in e.details)
        {
            System.Console.WriteLine("\n [ERROR]:\n");
            System.Console.WriteLine("message:\t" + obj.GetValue("message"));
            System.Console.WriteLine("debug:\t" + obj.GetValue("debug_message"));
            System.Console.WriteLine("code:\t" + obj.GetValue("code"));
        }
    }

Shipment is needed for physical goods

Cuando hago el llamado de prueba que existe en Tests.cs para hacer un cargo me regresa el siguiente error:

Conekta API Implementation Error (422 - 422) :: {"object":"error","type":"parameter_validation_error","message":"Shipment is needed for physical goods.","message_to_purchaser":"El campo de shipment es obligatorio para productos f??sicos.","param":null,"code":"parameter_validation"}

Descripción: Excepción no controlada al ejecutar la solicitud Web actual. Revise el seguimiento de la pila para obtener más información acerca del error y dónde se originó en el código. 

Detalles de la excepción: System.Exception: Conekta API Implementation Error (422 - 422) :: {"object":"error","type":"parameter_validation_error","message":"Shipment is needed for physical goods.","message_to_purchaser":"El campo de shipment es obligatorio para productos f??sicos.","param":null,"code":"parameter_validation"}

Error de código fuente: 


Línea 51:                      string responseText = reader.ReadToEnd();
Línea 52: 
Línea 53:                      throw new Exception ("Conekta API Implementation Error (" + (int)httpResponse.StatusCode + " - " + httpResponse.StatusCode + ") :: " + responseText);
Línea 54:                  }
Línea 55:              }

Archivo de origen: C:\Users\Yushell\Documents\Github\Repos\conekta-.net\src\conekta\conekta\Base\Requestor.cs    Línea: 53 

Seguimiento de la pila: 


[Exception: Conekta API Implementation Error (422 - 422) :: {"object":"error","type":"parameter_validation_error","message":"Shipment is needed for physical goods.","message_to_purchaser":"El campo de shipment es obligatorio para productos f??sicos.","param":null,"code":"parameter_validation"}]
   conekta.Requestor.request(String method, String resource_uri, String data) in C:\Users\Yushell\Documents\Github\Repos\conekta-.net\src\conekta\conekta\Base\Requestor.cs:53
   conekta.Resource.create(String resource_uri, String data) in C:\Users\Yushell\Documents\Github\Repos\conekta-.net\src\conekta\conekta\Base\Resource.cs:41
   conekta.Charge.create(String data) in C:\Users\Yushell\Documents\Github\Repos\conekta-.net\src\conekta\conekta\Models\Charge.cs:30
   Payments.Card.ChargeCard(String token) in c:\users\yushell\documents\visual studio 2015\Projects\Payments\Payments\Card.aspx.cs:24
   Payments.Card.Page_Load(Object sender, EventArgs e) in c:\users\yushell\documents\visual studio 2015\Projects\Payments\Payments\Card.aspx.cs:15
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2952

Se supone que ese es el llamado correcto para productos digitales. Por que sale ese error?

Unprocessable Entity.

Estoy tratando de configurar en un nuevo proyecto la opcion de Oxxo PAY.
Usando el ejemplo de la documentacion.
conekta.Order order = new conekta.Order ().create(@"{
""line_items"": [{
""name"": ""Tacos"",
""unit_price"": 1000,
""quantity"": 12
}],
""shipping_lines"": [{
""amount"": 1500,
""carrier"": ""FEDEX""
}]," + //shipping_lines - physical goods only
@"""currency"": ""MXN"",
""customer_info"": {
""name"": ""Fulanito Pérez"",
""email"": ""[email protected]"",
""phone"": ""+5218181818181""
},
""shipping_contact"":{
""address"": {
""street1"": ""Calle 123, int 2"",
""postal_code"": ""06100"",
""country"": ""MX""
}
}," + //shipping_contact - required only for physical goods only
@"""charges"":[{
""payment_method"": {
""type"": ""oxxo_cash"",
""expires_at"": " + thirtyDaysFromNow + @"
}
}]
}");

Pero siempre devuelve.
Remote server returned an error: (422) Unprocessable Entity.

Order support

Support Conekta /Orders support

  • refund
  • capture
  • create
  • find
  • where

Al crear un pedido, no permite procesarlo

Al crear un pedido, no permite procesarlo.

{
"details": [
{
"debug_message": "The "shipping_lines" is missing.",
"message": "El parametro "shipping_lines" es requerido.",
"param": "shipping_lines",
"code": "conekta.errors.parameter_validation.shipping_lines.missing"
}
],
"object": "error",
"type": "parameter_validation_error",
"log_id": "5a1f0d50b795b078f2d0e73e"
}

shipping_lines ese campo es opcional

image

parameter_validation_error

Al crear una orden, el retorno de la petición es un error con "parameter_validation_error". Hace un par de meses funcionaba, ahora que retomé el desarrollo no lo hace más (sobre sandbox).
Esta es la petición:
{
"line_items": [
{
"name": "Estacionario ",
"unit_price": 50000,
"quantity": 1
}
],
"shipping_lines": [
{
"amount": 0,
"carrier": "No Aplica",
"method": "No Aplica",
"metadata": {
"random_key": "No Aplica"
}
}
],
"customer_info": {
"name": "Jesús Martínez",
"phone": "4524176759",
"email": "[email protected]",
"corporate": false,
"vertical_info": {}
},
"shipping_contact": {
"phone": "4524176759",
"receiver": "Jesús Martínez",
"between_streets": "casa naranja ",
"address": {
"street1": "Mil cumbres",
"state": "Chihuahua/Ojinaga",
"country": "MX",
"postal_code": "60160",
"metadata": {
"soft_validations": true
}
}
},
"charges": [
{
"payment_method": {
"type": "card",
"token_id": "tok_test_mastercard_4444"
},
"amount": 50000
}
],
"currency": "mxn"
}

En en el detalle de la excepción, me menciona que: "The order amount does not match with the sum of charges amounts". Pero siempre he manejado un campo "amount", cambió el API?
Gracias por adelantado.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.