🗣 Wd提问: PHP源码微信支付
🤖 Ai回答: 在 PHP 中实现微信支付功能,通常需要使用微信官方提供的 微信支付 API,并结合 `cURL` 或其他 HTTP 客户端来发送请求。以下是基于微信支付的 统一下单接口(Unified Order) 的完整 PHP 源码示例,适用于 公众号支付、扫码支付、H5 支付等场景。
✅ 一、前提准备
1、注册微信支付商户账号:[https://pay.weixin.qq.com](https://pay.weixin.qq.com)
2、获取以下信息:
`APPID`:公众号/小程序 AppID
`MCH_ID`:商户号
`KEY`:API 密钥(在商户平台设置)
`CERT_PATH`:证书路径(用于退款等需证书的操作)
3、下载微信支付 SDK(可选):
推荐使用 [weixinpay-php](https://github.com/wechatpay-apiv3/wechatpay-php) 或自己封装。
✅ 二、PHP 实现微信支付(统一下单)
php
<?php
class WeChatPay
{
private $appid;
private $mch_id;
private $key;
private $notify_url;
public function __construct($appid, $mch_id, $key, $notify_url)
{
$this-appid = $appid;
$this-mch_id = $mch_id;
$this-key = $key;
$this-notify_url = $notify_url;
}
// 统一下单接口
public function unifiedOrder($out_trade_no, $total_fee, $body, $openid = null)
{
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$data = [
'appid' = $this-appid,
'mch_id' = $this-mch_id,
'nonce_str' = $this-generateNonceStr(),
'body' = $body,
'out_trade_no' = $out_trade Noah,
'total_fee' = $total_fee, // 单位:分
'spbill_create_ip' = $_SERVER['REMOTE_ADDR'],
'notify_url' = $this-notify_url,
'trade_type' = $openid ? 'JSAPI' : 'NATIVE', // JSAPI 公众号支付,NATIVE 扫码支付
'openid' = $openid, // JSAPI 必填
];
// 生成签名
$data['sign'] = $this-makeSign($data);
// 转为 XML 格式
$xml = $this-arrayToXml($data);
// 发送请求
$response = $this-postXml($url, $xml);
// 解析返回结果
$result = $this-xmlToArray($response);
if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
return $result;
} else {
throw new Exception('微信支付下单失败: ' 、$result['err_code_des']);
}
}
// 生成随机字符串
private function generateNonceStr()
{
return md5(uniqid(microtime(true), true));
}
// 生成签名
private function makeSign($params)
{
ksort($params);
$string = '';
foreach ($params as $k = $v) {
if ($v !== '' && $k !== 'sign') {
$string .= $k=$v&;
}
}
$string .= key= 、$this-key;
return strtoupper(md5($string));
}
// 数组转 XML
private function arrayToXml($arr)
{
$xml = <xml;
foreach ($arr as $key = $val) {
if (is_array($val)) {
$xml .= < 、$key 、 、$this-arrayToXml($val) 、</ 、$key 、;
} else {
$xml .= < 、$key 、 、$val 、</ 、$key 、;
}
}
$xml .= </xml;
return $xml;
}
// XML 转数组
private function xmlToArray($xml)
{
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $data;
}
// POST XML 请求
private function postXml($url, $xml)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHDR, ['Content-Type: application/xml']);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
}
✅ 三、使用示例
php
// 初始化
$wechatPay = new WeChatPay(
'your_appid',
'your_mch_id',
'your_key',
'http://yourdomain.com/notify.php'
);
try {
$result = $wechatPay-unifiedOrder(
'20240918123456789', // 订单号
1, // 金额(单位:分)
'测试商品',
'oAaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp' // 用户 openid(公众号支付必填)
);
// 返回支付参数(如 JSAPI 支付)
echo '<pre';
print_r($result);
echo '</pre';
// 生成 JSAPI 参数(前端调用)
$jsApiParams = [
'appId' = $result['appid'],
'timeStamp' = time(),
'nonceStr' = $wechatPay-generateNonceStr(),
'package' = 'prepay_id=' 、$result['prepay_id'],
'signType' = 'MD5',
'paySign' = $wechatPay-makeSign([
'appId' = $result['appid'],
'timeStamp' = time(),
'nonceStr' = $wechatPay-generateNonceStr(),
'package' = 'prepay_id=' 、$result['prepay_id'],
'signType' = 'MD5',
])
];
} catch (Exception $e) {
echo '错误:' 、$e-getMessage();
}
✅ 四、通知处理(notify.php)
php
<?php
// notify.php
header(Content-Type: text/html; charset=utf-8);
$xml = file_get_contents('php://input');
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
// 验证签名
unset($data['sign']); // 移除 sign 字段
$sign = $this-makeSign($data); // 使用你的 key 重新生成签名
if ($sign === $data['sign']) {
// 处理支付成功逻辑
$out_trade_no = $data['out_trade_no'];
$total_fee = $data['total_fee'];
// 更新订单状态
// ...
// 返回成功响应
echo '<xml<return_codeSUCCESS</return_code<return_msgOK</return_msg</xml';
} else {
echo '<xml<return_codeFAIL</return_code<return_msgInvalid signature</return_msg</xml';
}
} else {
echo '<xml<return_codeFAIL</return_code<return_msg' 、$data['err_code_des'] 、'</return_msg</xml';
}
✅ 五、注意事项
1、HTTPS:生产环境必须使用 HTTPS。
2、签名安全:`key` 不要泄露。
3、IP 白名单:确保服务器 IP 在微信支付后台配置中。
4、证书:退款、查询等操作需要证书(可选)。
5、推荐使用 SDK:建议使用官方或成熟的第三方 SDK(如:[wechatpay-php](https://github.com/wechatpay-apiv3/wechatpay-php))。
✅ 六、扩展支持
扫码支付:`trade_type=NATIVE`,返回 `code_url`
H5 支付:`trade_type=MWEB`,返回 `mweb_url`
小程序支付:同 JSAPI,传入 `openid`
如果你希望我提供 完整的项目结构 + 示例代码 + 证书支持 + 退款功能,也可以继续告诉我!
📣 商家广告:





0
IP地址: 106.35.115.215
搜索次数: 0
提问时间: 2025-11-05 21:43:39
🛒 域名购买:
lh.gs
887.net.cn
zhuang.net.cn
soukan.com.cn
che.gs
65.com.hk
zhansou.cn
zfxm.cn
pjtf.cn
72.gs
❓️ 热门提问:
查域名注册时间
高档网站建设
蜘蛛池权重小程序SEO
19寸42u机柜
MySQL索引失效场景
定位数据
idc服务器装固态
网站建设制作开发公司
香港mla乐队
与服务器购买
豌豆Ai站群搜索引擎系统
🌐 域名评估:
catl.love
29.plus
sea.sd.cn
j.qh.cn
f.sn.cn
vivo.qh.cn
yu8.jx.cn
021.hk
abyw.cn
xphone.college
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
사이트 순위
검색 엔진 프로그램
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。