Can PHP act as a proxy for curl requests between 1C and Bitrix24?
We need to transfer data from 1C to Bitrix24, but the standard connector doesn’t work for us. We can create deals through the Bitrix24 REST API using the crm.deal.add method via a simple cURL request with a webhook.
However, for creating products in the catalog through the catalog.product.add method, OAuth authorization from an administrator is required, which we don’t want to implement in our legacy 1C system.
Question: Is it possible to develop a PHP script that:
- Accepts POST requests from 1C
- Performs OAuth authorization in Bitrix24
- Forwards the requests received from 1C to Bitrix24 without any modifications
- Accepts responses from Bitrix24 and returns them to 1C
The script should work universally, regardless of the specific API methods (catalog.product.add, crm.deal.add, etc.), simply forwarding the received data.
PHP as a Proxy for curl Requests Between 1C and Bitrix24
PHP can act as a proxy for curl requests between 1C and Bitrix24, creating a secure intermediary for performing OAuth authorization and redirecting API requests without the need for direct access to credentials in the legacy 1C system. This approach will solve the problem of administrative restrictions when working with API methods requiring OAuth authentication, while maintaining the versatility of handling different types of requests.
Contents
- Technical Implementation of PHP Proxy
- Setting Up OAuth Authorization in Bitrix24
- Structure of PHP Proxy Script
- Processing Requests from 1C
- Security and Best Practices
- Testing and Debugging
- Alternative Solutions
Technical Implementation of PHP Proxy
To create a PHP proxy between 1C and Bitrix24, it’s necessary to implement several key components. The main idea is that the PHP script will act as an intermediary, accepting requests from 1C, adding the necessary OAuth authentication, and forwarding them to Bitrix24.
Important: This approach allows using a single OAuth token for all requests from 1C, avoiding the need to store or generate tokens directly in the 1C system.
The implementation will require:
- PHP server with cURL support
- Configured OAuth client for Bitrix24
- Request routing rules
- Error handling and logging system
Setting Up OAuth Authorization in Bitrix24
Before creating the proxy, you need to configure an OAuth application in Bitrix24. The process includes the following steps:
-
Creating an OAuth application:
- Go to the “Applications” section in Bitrix24
- Create a new web application
- Specify the redirect URI (for example,
https://your-domain.com/oauth/callback.php) - Get the application ID and secret
-
Obtaining an access token:
php$oauthUrl = 'https://your-bitrix24-domain/oauth/authorize'; $params = [ 'client_id' => 'YOUR_APP_ID', 'response_type' => 'code', 'redirect_uri' => 'https://your-domain.com/oauth/callback.php' ]; -
Exchanging code for token:
php$tokenUrl = 'https://your-bitrix24-domain/oauth/token/'; $tokenData = [ 'grant_type' => 'authorization_code', 'client_id' => 'YOUR_APP_ID', 'client_secret' => 'YOUR_APP_SECRET', 'code' => 'AUTHORIZATION_CODE', 'redirect_uri' => 'https://your-domain.com/oauth/callback.php' ];
Recommendation: Store the access token in a secure storage with a limited lifetime and implement a token refresh mechanism.
Structure of PHP Proxy Script
The main PHP script should contain the following components:
Initialization and Configuration
<?php
// Configuration
$config = [
'bitrix24_domain' => 'https://your-bitrix24-domain',
'access_token' => 'YOUR_ACCESS_TOKEN',
'timeout' => 30,
'log_file' => '/var/log/bitrix24_proxy.log'
];
// Get data from POST request
$requestData = file_get_contents('php://input');
$requestHeaders = getallheaders();
Function for Sending Requests to Bitrix24
function sendToBitrix24($url, $data, $accessToken) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken
],
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'response' => $response,
'http_code' => $httpCode
];
}
Main Proxy Logic
// Determine API method from request
$apiMethod = $_GET['method'] ?? 'crm.deal.add';
$bitrixUrl = $config['bitrix24_domain'] . '/rest/' . $apiMethod;
// Send request to Bitrix24
$result = sendToBitrix24($bitrixUrl, $requestData, $config['access_token']);
// Return response to 1C
header('Content-Type: application/json');
http_response_code($result['http_code']);
echo $result['response'];
Processing Requests from 1C
The system should correctly handle different types of requests from 1C:
1. Processing POST Requests
// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Only POST method allowed']);
exit;
}
// Check for data presence
if (empty($requestData)) {
http_response_code(400);
echo json_encode(['error' => 'Empty request data']);
exit;
}
2. Processing Different API Methods
// Determine request type
$method = $_GET['method'] ?? 'default';
switch ($method) {
case 'catalog.product.add':
// Special handling for catalog
break;
case 'crm.deal.add':
// Standard handling for deals
break;
default:
// Universal handling
break;
}
3. Request Logging
function logRequest($method, $data, $response, $status) {
global $config;
$logEntry = sprintf(
"[%s] Method: %s | Status: %d | Data: %s | Response: %s\n",
date('Y-m-d H:i:s'),
$method,
$status,
substr($data, 0, 500),
substr($response, 0, 500)
);
file_put_contents($config['log_file'], $logEntry, FILE_APPEND);
}
Security and Best Practices
When implementing the proxy, the following security aspects must be considered:
1. Authentication of Requests from 1C
// Example of signature verification
function verify1CSignature($requestData, $secretKey) {
$expectedHash = hash_hmac('sha256', $requestData, $secretKey);
$receivedHash = $_SERVER['HTTP_X_1C_SIGNATURE'] ?? '';
return hash_equals($expectedHash, $receivedHash);
}
2. Input Data Validation
function validateRequestData($data) {
// Check JSON structure
$decoded = json_decode($data, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return false;
}
// Additional validation depending on method
return true;
}
3. CSRF Protection
// Generate and verify CSRF token
session_start();
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_POST['csrf_token'] ?? '';
if (!hash_equals($_SESSION['csrf_token'], $csrfToken)) {
http_response_code(403);
echo json_encode(['error' => 'CSRF validation failed']);
exit;
}
4. IP-Based Access Control
// Allowed IP addresses of 1C system
$allowedIPs = ['192.168.1.100', '10.0.0.50'];
$clientIP = $_SERVER['REMOTE_ADDR'];
if (!in_array($clientIP, $allowedIPs)) {
http_response_code(403);
echo json_encode(['error' => 'Access denied']);
exit;
}
Testing and Debugging
To ensure reliable proxy operation, a testing system must be implemented:
1. Test Scripts
// Example test script
function testProxy() {
$testData = json_encode([
'FIELDS' => [
'TITLE' => 'Test Deal',
'COMPANY_ID' => 123
]
]);
$ch = curl_init('http://your-proxy-domain/proxy.php?method=crm.deal.add');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $testData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'http_code' => $httpCode,
'response' => $response
];
}
2. Monitoring and Logging
// Extended logging
function extendedLog($action, $details) {
global $config;
$logData = [
'timestamp' => date('Y-m-d H:i:s'),
'action' => $action,
'details' => $details,
'server_info' => $_SERVER,
'request_info' => [
'method' => $_SERVER['REQUEST_METHOD'],
'uri' => $_SERVER['REQUEST_URI'],
'headers' => getallheaders()
]
];
file_put_contents(
$config['log_file'],
json_encode($logData, JSON_UNESCAPED_UNICODE) . "\n",
FILE_APPEND
);
}
Alternative Solutions
There are other approaches to integrating 1C and Bitrix24:
1. Using Webhooks
// Setting up webhook in Bitrix24
$webhookUrl = 'https://your-domain.com/bitrix24/webhook.php';
// Processing webhook
if (isset($_POST['event'])) {
$event = json_decode($_POST['event'], true);
// Process event and send to 1C
}
2. Bitrix24 Webhook + PHP Proxy
// Hybrid approach
function hybridIntegration($method, $data) {
global $config;
// For simple methods, use webhook
if (in_array($method, ['crm.deal.add', 'crm.lead.add'])) {
return sendViaWebhook($method, $data);
}
// For complex methods, use OAuth
return sendViaOAuth($method, $data);
}
3. Using Ready-Made Solutions
- Bitrix24 REST API Helper - ready-made solution for working with API
- 1C-Bitrix24 Integration - commercial solutions available on the market
- Open Source Projects - GitHub repositories with integration examples
Important: When choosing a ready-made solution, ensure it’s up-to-date and meets your system’s security requirements.
Sources
- Official Bitrix24 REST API Documentation
- OAuth 2.0 Authorization Framework RFC 6749
- PHP cURL Documentation
- Bitrix24 OAuth Authentication Guide
- PHP Security Best Practices
Conclusion
PHP can successfully act as a proxy for curl requests between 1C and Bitrix24, providing a secure and flexible integration mechanism. The main advantages of this approach include:
- Centralized OAuth token management - all authentication data is stored on the PHP server, not in the legacy 1C system
- Versatility in request processing - a single script can handle various API methods without the need for modification in 1C
- Enhanced security - ability to implement additional protection and validation layers
- Flexible configuration - easy modification of request processing logic without updating the 1C system
For successful implementation, it’s recommended to:
- Thoroughly test the script on various types of requests
- Implement a monitoring and logging system
- Configure backup communication channels in case of primary proxy failure
- Regularly update PHP script libraries and dependencies
This approach effectively solves the integration problem of a legacy 1C system with the modern Bitrix24 API, while ensuring a high level of security and reliability.