基于WordPress和WooCommerce接入支付宝和微信支付的完整代码实现示例
- 自动生成原创文章教程
- 2025-01-26 12:00:34
- 62热度
- 0评论
1. 接入支付宝支付
以下是接入支付宝支付的代码示例:
支付请求函数
function make_alipay_payment_request($order_id, $amount, $description) {
$config = include('path/to/your-config-file.php'); // 加载配置文件
$request_params = array(
'out_trade_no' => $order_id, // 订单号
'total_amount' => $amount, // 支付金额
'subject' => $description, // 商品描述
'sign_type' => 'MD5', // 签名类型
);
$request_params['sign'] = generate_signature($request_params, $config['api_secret']); // 生成签名
$query_string = build_query_string($request_params); // 构建查询字符串
$redirect_url = '支付宝支付接口URL' . $query_string; // 构建支付宝支付URL
wp_redirect($redirect_url); // 重定向到支付宝支付页面
exit;
}
回调验证函数
function verify_callback($data, $sign) {
$params = $data;
unset($params['sign']); // 移除签名字段
ksort($params); // 参数排序
$strToBeSigned = '';
foreach ($params as $k => $v) {
$strToBeSigned .= $k . '=' . $v . '&';
}
$strToBeSigned = rtrim($strToBeSigned, '&');
$sign_check = strtoupper(hash_hmac('sha256', $strToBeSigned, $config['alipay_public_key'])); // 重新计算签名
return $sign_check == strtoupper($sign); // 验证签名是否一致
}
回调处理函数
function process_alipay_callback() {
$posted = file_get_contents('php://input'); // 获取回调数据
parse_str($posted, $alipay_post);
if (is_valid_callback($alipay_post)) { // 验证回调数据
if (is_order_valid($alipay_post['out_trade_no'])) { // 验证订单是否有效
update_order_status($alipay_post['out_trade_no'], 'paid'); // 更新订单状态为已支付
echo "success";
} else {
echo "重复通知";
}
} else {
echo "非法请求";
}
}
2. 接入微信支付
以下是接入微信支付的代码示例:
微信支付请求函数
function make_wechat_payment_request($order_id, $amount, $description) {
$config = include('path/to/your-config-file.php'); // 加载配置文件
$request_params = array(
'appid' => $config['wechat_appid'], // 微信支付的AppID
'mch_id' => $config['wechat_mch_id'], // 商户号
'nonce_str' => random_string(32), // 随机字符串
'body' => $description, // 商品描述
'out_trade_no' => $order_id, // 订单号
'total_fee' => intval($amount * 100), // 支付金额(单位:分)
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // 客户端IP
'notify_url' => $config['wechat_notify_url'], // 回调地址
'trade_type' => 'NATIVE', // 交易类型(扫码支付)
);
$request_params['sign'] = generate_signature($request_params, $config['wechat_api_key']); // 生成签名
$xml = array_to_xml($request_params); // 转换为XML格式
$response = send_post_request('微信支付接口URL', $xml); // 发送请求
$result = xml_to_array($response); // 解析响应
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
return $result['code_url']; // 返回支付二维码URL
} else {
Copyright © 2025 idc.xymww.com. All Rights Reserved.
渝ICP备2024048343号-1
渝公网安备50010502504446号
AI 客服助手-仅限插件功能测试-已限制回复字数