当前位置:首页 > 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
分享给朋友:

相关文章

淘宝css代码制作

淘宝css代码制作

在淘宝店铺装修中,CSS代码用于自定义页面样式,提升视觉效果和用户体验。以下是常见的CSS代码制作方法和应用场景: 自定义店铺背景 通过CSS可以修改店铺背景颜色或图片,代码示例如下: body…

php实现栈

php实现栈

栈的基本概念 栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构。核心操作包括: push:元素入栈。 pop:元素出栈(返回并移除栈顶元素)。 peek:查看栈顶元素(不移除…

php长连接实现

php长连接实现

PHP 长连接实现方法 长连接(Keep-Alive)允许客户端与服务器在一次TCP连接中发送和接收多个HTTP请求/响应,减少重复建立连接的开销。以下是PHP中实现长连接的几种方式: 配置HTTP…

php 实现队列

php 实现队列

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

php实现mvc

php实现mvc

PHP 实现 MVC 架构 MVC(Model-View-Controller)是一种常用的软件设计模式,将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller…

php 实现无限分类

php 实现无限分类

无限分类的实现方法 无限分类通常用于构建多层级结构的数据,如商品分类、菜单管理等。以下是几种常见的实现方式: 邻接列表模型(Adjacency List) 这是最简单的实现方式,每个分类记录存储其父…