使用 PHP 包管理工具 Composer 安装 SDK:
composer require wechatpay/wechatpay
获取微信商户证书
获取微信支付平台证书
在服务器上进入PHP项目,进入vendor/bin/目录
-k:apiv3秘钥-m:商户号-f:微信商户API私钥文件目录-s:证书序列号-o:生成后的证书保存地址php CertificateDownloader.php -k ${apiV3key} -m ${mchId} -f ${mchPrivateKeyFilePath} -s ${mchSerialNo} -o ${outputFilePath}例如:php CertificateDownloader.php -k 241054wsd5we14586esfwqsfjke25344 -m 1600789654 -f /app/file/wxCert/apiclient_key.pem -s WB0E676A11B907E25875FCCBB15151637E4 -o /app/file/wxCert/
构造一个APIV3客户端实例
$merchantId, 'serial' => $merchantCertificateSerial, 'privateKey' => $merchantPrivateKeyInstance, 'certs' => [ $platformCertificateSerial => $platformPublicKeyInstance, ],]);// 发送请求$resp = $instance->chain('v3/certificates')->get( ['debug' => true] // 调试模式,https://docs.guzzlephp.org/en/stable/request-options.html#debug);echo $resp->getBody(), PHP_EOL;
APP支付下单为例
try { $resp = $instance ->chain('v3/pay/transactions/app') ->post(['json' => [ 'mchid' => '1900006XXX', 'out_trade_no' => 'native12177525012014070332333', 'appid' => 'wxdace645e0bc2cXXX', 'description' => 'Image形象店-深圳腾大-QQ公仔', 'notify_url' => 'https://weixin.qq.com/', 'amount' => [ 'total' => 1, 'currency' => 'CNY' ], ]]); echo $resp->getStatusCode(), PHP_EOL; echo $resp->getBody(), PHP_EOL;} catch (\Exception $e) { // 进行错误处理 echo $e->getMessage(), PHP_EOL; if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) { $r = $e->getResponse(); echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL; echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL; } echo $e->getTraceAsString(), PHP_EOL;}
注意
若运行中出现如下错误:Cannot load privateKey from(string), please take care about the \\$thing input.
需要在文件前面添加 file://
例如:
$merchantPrivateKeyFilePath = 'file://'.私钥文件目录;
若出现签名错误:
先自己查看商户API证书,API序列号,APIV3秘钥,商户号,微信平台证书是否一致,确保一致后还是出现签名错误,则可以验签。
有疑问或不同见解欢迎评论区留言!
来源地址:https://blog.csdn.net/Logical_storm/article/details/123797074