以下是一个使用PHP进行支付对接的实例,我们将使用一个通用的支付接口来演示如何实现支付功能。这个例子将包括创建订单、发起支付请求、处理支付结果等步骤。
1. 创建订单
我们需要创建一个订单,并获取订单号和订单详情。
```php
// 创建订单
$order = [
'order_id' => '1234567890',
'amount' => 100.00,
'currency' => 'CNY',
'product_name' => '商品名称',
'product_desc' => '商品描述'
];
// 将订单信息发送到支付接口
// 这里使用假设的支付接口URL
$api_url = 'https://example.com/api/create_order';
$post_data = json_encode($order);
// 初始化CURL会话
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($post_data)
]);
// 执行CURL会话
$response = curl_exec($ch);
curl_close($ch);
// 解析响应
$order_response = json_decode($response, true);
>
```
2. 发起支付请求
一旦订单被创建,我们可以使用订单号来发起支付请求。
```php
// 发起支付请求
$payment_url = 'https://example.com/api/pay?order_id=' . $order_response['order_id'];
// 引导用户访问支付页面
header('Location: ' . $payment_url);
>
```
3. 处理支付结果
用户完成支付后,支付接口会返回支付结果。
```php
// 处理支付结果
$api_url = 'https://example.com/api/pay_result';
$post_data = [
'order_id' => $order_response['order_id'],
'payment_status' => 'success' // 假设支付成功
];
// 初始化CURL会话
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($post_data))
]);
// 执行CURL会话
$response = curl_exec($ch);
curl_close($ch);
// 解析响应
$payment_response = json_decode($response, true);
>
```
表格总结
| 步骤 | 操作 | 代码 |
|---|---|---|
| 创建订单 | 发送订单信息到支付接口 | 使用CURL发送POST请求 |
| 发起支付请求 | 引导用户到支付页面 | 使用HTTP重定向 |
| 处理支付结果 | 接收支付结果 | 使用CURL发送POST请求并解析响应 |
这个实例展示了如何使用PHP进行支付对接的基本流程。在实际应用中,你可能需要处理更多的异常情况和安全性问题。

