当前位置:首页 > PHP

php实现付款代码

2026-02-15 04:37:46PHP

PHP实现付款功能

使用PHP实现付款功能通常需要集成第三方支付网关或API。以下是几种常见支付方式的实现方法。

支付宝支付集成

支付宝提供官方SDK用于PHP集成。下载官方SDK后,通过以下代码实现支付请求:

require_once 'alipay.config.php';
require_once 'lib/alipay_submit.class.php';

$alipaySubmit = new AlipaySubmit($alipay_config);
$parameter = array(
    "service" => "create_direct_pay_by_user",
    "partner" => trim($alipay_config['partner']),
    "payment_type" => "1",
    "notify_url" => "http://商户网址/create_direct_pay_by_user-PHP-UTF-8/notify_url.php",
    "return_url" => "http://商户网址/create_direct_pay_by_user-PHP-UTF-8/return_url.php",
    "out_trade_no" => date('YmdHis').mt_rand(1000,9999),
    "subject" => "测试订单",
    "total_fee" => "0.01",
    "body" => "测试订单描述",
    "show_url" => "http://www.xxx.com/myorder.html",
    "anti_phishing_key" => "",
    "exter_invoke_ip" => "",
    "_input_charset" => trim(strtolower($alipay_config['input_charset']))
);

$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
echo $html_text;

微信支付集成

微信支付需要通过官方提供的PHP SDK实现。配置好商户信息后,使用以下代码发起支付:

require_once "WxPay.Api.php";
require_once 'WxPay.Notify.php';

$input = new WxPayUnifiedOrder();
$input->SetBody("测试商品");
$input->SetAttach("测试附加数据");
$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("test");
$input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
$input->SetTrade_type("NATIVE");
$input->SetProduct_id("123456789");

$result = WxPayApi::unifiedOrder($input);
$url2 = $result["code_url"];

PayPal支付集成

PayPal提供REST API接口。使用以下代码实现PayPal支付:

require __DIR__ . '/vendor/autoload.php';

$apiContext = new \PayPal\Rest\ApiContext(
    new \PayPal\Auth\OAuthTokenCredential(
        'client_id',     // ClientID
        'client_secret'      // ClientSecret
    )
);

$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod('paypal');

$amount = new \PayPal\Api\Amount();
$amount->setTotal('1.00');
$amount->setCurrency('USD');

$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount);

$redirectUrls = new \PayPal\Api\RedirectUrls();
$redirectUrls->setReturnUrl("https://example.com/your_redirect_url.html")
    ->setCancelUrl("https://example.com/your_cancel_url.html");

$payment = new \PayPal\Api\Payment();
$payment->setIntent('sale')
    ->setPayer($payer)
    ->setTransactions(array($transaction))
    ->setRedirectUrls($redirectUrls);

try {
    $payment->create($apiContext);
    echo $payment;
    echo "\n\nRedirect user to approval URL: " . $payment->getApprovalLink() . "\n";
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
    echo $ex->getData();
}

Stripe支付集成

Stripe的PHP集成需要安装官方库。使用以下代码处理支付:

require_once('vendor/autoload.php');

\Stripe\Stripe::setApiKey("sk_test_your_key");

$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create([
    'amount' => 1000,
    'currency' => 'usd',
    'description' => 'Example charge',
    'source' => $token,
]);

数据库记录支付信息

无论使用哪种支付方式,都应该在数据库中记录交易信息:

$conn = new mysqli("localhost", "username", "password", "database");

$order_id = uniqid();
$amount = 100;
$status = 'pending';
$payment_method = 'alipay';

$stmt = $conn->prepare("INSERT INTO payments (order_id, amount, status, payment_method) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sdss", $order_id, $amount, $status, $payment_method);
$stmt->execute();

支付回调处理

支付完成后需要处理回调通知验证支付状态:

// 支付宝回调验证示例
function verifyNotify($notify_id) {
    $veryfy_url = "https://mapi.alipay.com/gateway.do?service=notify_verify&partner=".$partner."&notify_id=".$notify_id;
    $responseTxt = getHttpResponse($veryfy_url);
    return preg_match("/true$/i",$responseTxt);
}

// 微信支付回调验证示例
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

if($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
    // 更新订单状态为已支付
    updateOrderStatus($data['out_trade_no'], 'paid');
}

安全注意事项

支付系统涉及金融交易,必须重视安全性:

  • 使用HTTPS加密所有支付相关请求
  • 验证所有回调通知的真实性
  • 记录完整的交易日志
  • 实现防重复支付机制
  • 定期对账确保账务一致

以上代码示例展示了不同支付平台的PHP集成方法。实际应用中需要根据具体业务需求进行调整,并严格遵守各支付平台的API规范和安全要求。

php实现付款代码

标签: 代码php
分享给朋友:

相关文章

vue实现通讯录代码

vue实现通讯录代码

实现思路 Vue实现通讯录的核心在于数据管理和组件交互。通常需要包含联系人列表、搜索功能、分组索引以及添加/编辑功能。 基本结构 创建Vue组件时需包含以下部分: 数据模型:存储联系人数组 字…

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php实现增删改查

php实现增删改查

以下是在PHP中实现增删改查(CRUD)操作的详细方法,以MySQL数据库为例: 数据库连接配置 创建config.php文件存储数据库连接信息: <?php $host = 'loca…

php 实现登录

php 实现登录

PHP 登录功能实现 使用 PHP 实现登录功能通常需要结合数据库验证和会话管理。以下是一个基本的登录实现流程: 数据库准备 创建用户表存储用户名和密码(建议使用哈希加密): CREATE TAB…

php验证码的实现

php验证码的实现

PHP 验证码实现方法 使用 GD 库生成基础验证码 创建画布并生成随机字符串作为验证码内容: session_start(); $width = 120; $height = 40; $image…

php实现推送

php实现推送

PHP 实现推送功能的方法 PHP 实现推送功能可以通过多种方式完成,包括 WebSocket、Server-Sent Events (SSE)、长轮询或第三方推送服务。以下是几种常见的方法: 使…