Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Runtime enviroment (skip SSL on localhost) #487

Merged
147 changes: 142 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,14 @@ composer require "mercadopago/dx-php:3.0.0"

That's it! Mercado Pago SDK has been successfully installed.

## 🌟 Getting Started
## Useful links

- [SDK Docs](https://www.mercadopago.com.br/developers/pt/docs/sdks-library/server-side)
- [REST API (consumed by the SDK)](https://www.mercadopago.com.br/developers/en/reference)

Here you can check eg. data structures for each parameter used by the SDK for each class.

## 🌟 Getting Started with payment via your own website forms

Simple usage looks like:

Expand All @@ -45,6 +52,9 @@ Simple usage looks like:

// Step 2: Set production or sandbox access token
MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
// Step 2.1 (optional - default is SERVER): Set your runtime enviroment from MercadoPagoConfig::RUNTIME_ENVIROMENTS
// In case you want to test in your local machine first, set runtime enviroment to LOCAL
MercadoPagoConfig::setRuntimeEnviroment(MercadoPagoConfig::LOCAL);

// Step 3: Initialize the API client
$client = new PaymentClient();
Expand Down Expand Up @@ -77,6 +87,7 @@ Simple usage looks like:
```

### Step 1: Require the library from your Composer vendor folder

```php
require_once 'vendor/autoload.php';

Expand All @@ -86,18 +97,21 @@ use MercadoPago\MercadoPagoConfig;
```

### Step 2: Set production or sandbox access token

```php
MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
```

You can also set another properties as quantity of retries, tracking headers, timeouts and a custom http client.

### Step 3: Initialize the API client

```php
$client = new PaymentClient();
```

### Step 4: Create the request array

```php
$request = [
"transaction_amount" => 100,
Expand All @@ -112,24 +126,146 @@ $request = [
```

### Step 5: Make the request

```php
$payment = $client->create($request);
```

### Step 6: Handle exceptions

```php
...
// Handle API exceptions
try{
// Do your stuff here
} catch (MPApiException $e) {
// Handle API exceptions
echo "Status code: " . $e->getApiResponse()->getStatusCode() . "\n";
echo "Content: " . $e->getApiResponse()->getContent() . "\n";

// Handle all other exceptions
} catch (\Exception $e) {
// Handle all other exceptions
echo $e->getMessage();
}
```

## 🌟 Getting started with payment via Checkout Pro

### Step 1: Require the libraries

```php
use MercadoPago\MercadoPagoConfig;
use MercadoPago\Client\Preference\PreferenceClient;
use MercadoPago\Exceptions\MPApiException;
```

### Step 2: Create an authentication function

```php
protected function authenticate()
{
// Getting the access token from .env file (create your own function)
$mpAccessToken = getVariableFromEnv('mercado_pago_access_token');
// Set the token the SDK's config
MercadoPagoConfig::setAccessToken($mpAccessToken);
// (Optional) Set the runtime enviroment to LOCAL if you want to test on localhost
// Default value is set to SERVER
MercadoPagoConfig::setRuntimeEnviroment(MercadoPagoConfig::LOCAL);
}
```

### Step 3: Create customer's preference before proceeding to Checkout Pro page

```php
// Function that will return a request object to be sent to Mercado Pago API
function createPreferenceRequest($items, $payer): array
{
$paymentMethods = [
"excluded_payment_methods" => [],
"installments" => 12,
"default_installments" => 1
];

$backUrls = array(
'success' => route('mercadopago.success'),
'failure' => route('mercadopago.failed')
);

$request = [
"items" => $items,
"payer" => $payer,
"payment_methods" => $paymentMethods,
"back_urls" => $backUrls,
"statement_descriptor" => "NAME_DISPLAYED_IN_USER_BILLING",
"external_reference" => "1234567890",
"expires" => false,
"auto_return" => 'approved',
];

return $request;
}
```

### Step 4: Create the preference on Mercado Pago ([DOCS](https://www.mercadopago.com.br/developers/pt/docs/sdks-library/server-side/php/preferences))

```php
public function createPaymentPreference(): ?Preference
{
// Fill the data about the product(s) being pruchased
$product1 = array(
"id" => "1234567890",
"title" => "Product 1 Title",
"description" => "Product 1 Description",
"currency_id" => "BRL",
"quantity" => 12,
"unit_price" => 9.90
);

$product2 = array(
"id" => "9012345678",
"title" => "Product 2 Title",
"description" => "Product 2 Description",
"currency_id" => "BRL",
"quantity" => 5,
"unit_price" => 19.90
);

// Mount the array of products that will integrate the purchase amount
$items = array($product1, $product2);

// Retrieve information about the user (use your own function)
$user = getSessionUser();

$payer = array(
"name" => $user->name,
"surname" => $user->surname,
"email" => $user->email,
);

// Create the request object to be sent to the API when the preference is created
$request = createPreferenceRequest($item, $payer);

// Instantiate a new Preference Client
$client = new PreferenceClient();

try {
// Send the request that will create the new preference for user's checkout flow
$preference = $client->create($request);

// Useful props you could use from this object is 'init_point' (URL to Checkout Pro) or the 'id'
return $preference;
} catch (MPApiException $error) {
// Here you might return whatever your app needs.
// We are returning null here as an example.
return null;
}
}
```

In case you need to retrieve the preference by ID:

```php
$client = new PreferenceClient();
$client->get("123456789");
```

## 📚 Documentation

See our documentation for more details.
Expand All @@ -144,6 +280,7 @@ Please read and follow our [contribution guidelines](CONTRIBUTING.md). Contribut
be disregarded. The guidelines are in place to make all of our lives easier and make contribution a consistent process for everyone.

### Patches to version 2.x.x

Since the release of version 3.0.0, version 2 is deprecated and will not be receiving new features, only bug fixes. If you need to submit PRs for that version, please do so by using [master-v2](https://github.com/mercadopago/sdk-php/tree/master-v2) as your base branch.

## ❤️ Support
Expand Down
10 changes: 10 additions & 0 deletions src/MercadoPago/Exceptions/InvalidArgumentException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace MercadoPago\Exceptions;

use Exception;

/** InvalidArgumentException class. */
class InvalidArgumentException extends Exception
{
}
32 changes: 32 additions & 0 deletions src/MercadoPago/MercadoPagoConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MercadoPago;

use MercadoPago\Exceptions\InvalidArgumentException;
use MercadoPago\Net\MPDefaultHttpClient;
use MercadoPago\Net\MPHttpClient;

Expand All @@ -17,6 +18,15 @@ class MercadoPagoConfig
/** @var string Mercado Pago SDK PHP product version */
public static string $PRODUCT_ID = "BC32A7RU643001OI3940";

/** @var string Class constant for local runtime enviroment */
const LOCAL = 'local';

/** @var string Class constant for server runtime enviroment */
const SERVER = 'server';

/** @var string Actual enviroment the user is running at. Default is SERVER */
private static string $runtime_enviroment = self::SERVER;

/** @var string access token */
private static string $access_token = "";

Expand Down Expand Up @@ -216,4 +226,26 @@ public static function setConnectionTimeout(int $connection_timeout): void
{
self::$connection_timeout = $connection_timeout;
}

/**
* Gets the enviroment the user is running at.
* @return string enviroment
*/
public static function getRuntimeEnviroment(): string
{
return self::$runtime_enviroment;
}

/**
* Sets the enviroment the user is running at.
* @param string $enviroment one of the ENVIROMENT_TYPES
* @return void
*/
public static function setRuntimeEnviroment(string $enviroment): void
{
if ($enviroment != self::LOCAL && $enviroment != self::SERVER) {
throw new InvalidArgumentException("Enviroment must be equal to MercadoPagoConfig::LOCAL or MercadoPagoConfig::SERVER.");
}
self::$runtime_enviroment = $enviroment;
}
}
9 changes: 8 additions & 1 deletion src/MercadoPago/Net/MPDefaultHttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private function createHttpRequestOptions(MPRequest $request): array
{
$connection_timeout = $request->getConnectionTimeout() ?: MercadoPagoConfig::getConnectionTimeout();

return array(
$options = array(
CURLOPT_URL => MercadoPagoConfig::$BASE_URL . $request->getUri(),
CURLOPT_CUSTOMREQUEST => $request->getMethod(),
CURLOPT_HTTPHEADER => $request->getHeaders(),
Expand All @@ -98,6 +98,13 @@ private function createHttpRequestOptions(MPRequest $request): array
CURLOPT_MAXCONNECTS => MercadoPagoConfig::getMaxConnections(),
CURLOPT_RETURNTRANSFER => true
);

if (MercadoPagoConfig::getRuntimeEnviroment() === MercadoPagoConfig::LOCAL) {
$options += [CURLOPT_SSL_VERIFYHOST => false];
$options += [CURLOPT_SSL_VERIFYPEER => false];
}

return $options;
}

private function isServerError(int $status_code): bool
Expand Down