当前位置:首页 > 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实现。配置好商户信息后,使用以下代码发起支付:

php实现付款代码

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集成需要安装官方库。使用以下代码处理支付:

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实现上传

php实现上传

PHP 文件上传实现 HTML 表单设置 创建一个包含文件上传字段的 HTML 表单,确保表单的 enctype 属性设置为 multipart/form-data,这是文件上传必需的设置。 <…

php 实现验证码

php 实现验证码

使用 PHP 生成验证码 验证码(CAPTCHA)用于防止自动化脚本提交表单,以下是几种常见的 PHP 实现方法。 使用 GD 库生成图片验证码 GD 库是 PHP 的图像处理扩展,可用于生成验证码…

基于php的设计与实现

基于php的设计与实现

PHP 设计与实现的关键要素 环境搭建与框架选择 PHP开发需配置服务器环境(如Apache/Nginx)、PHP版本(建议7.4+)及数据库(MySQL/MariaDB)。主流框架包括Laravel…

php实现统计

php实现统计

PHP 实现统计功能 在 PHP 中实现统计功能通常涉及数据的收集、处理和展示。以下是一些常见的统计实现方法: 数据库数据统计 通过 SQL 查询可以直接从数据库中获取统计结果: $conn =…

php 实现队列

php 实现队列

PHP 实现队列的方法 PHP 可以通过多种方式实现队列功能,以下是几种常见的实现方法: 使用数组实现队列 PHP 数组可以通过 array_push 和 array_shift 函数模拟队列的先进…

php实现获取验证码

php实现获取验证码

使用GD库生成验证码 在PHP中,可以通过GD库来生成验证码图片。以下是一个简单的实现示例: <?php session_start(); $width = 120; $height = 40…