php实现付款代码
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."¬ify_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规范和安全要求。







