- wechatpay-apache-httpclient,适用于使用Apache HttpClient处理HTTP的Java开发者。
- wechatpay-guzzle-middleware,适用于PHP开发者。
这里用的是PHP,所以使用 wechatpay-guzzle-middleware。
<?php
namespace App\Http\Controllers\WxPay;
use App\Http\Controllers\Controller;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use WechatPay\GuzzleMiddleware\Util\PemUtil;
use WechatPay\GuzzleMiddleware\WechatPayMiddleware;
class WxPayClient extends Controller
{
// 设置请求头签名
public function setAuthorization(string $methods, string $url, array $params)
{
// 商户相关配置,
$merchantId = config('globaldatas.mchid'); // 商户号
$merchantSerialNumber = config('globaldatas.serial_no'); // 商户API证书序列号
$merchantPrivateKey = PemUtil::loadPrivateKey("apiclient_key.pem");// 商户私钥文件路径
// 微信支付平台配置
$wechat_no = '微信支付平台证书.pem';
$wechatpayCertificate = PemUtil::loadCertificate($wechat_no); // 微信支付平台证书文件路径
// 构造一个WechatPayMiddleware 正常使用
$wechatpayMiddleware = WechatPayMiddleware::builder()
->withMerchant($merchantId, $merchantSerialNumber, $merchantPrivateKey) // 传入商户相关配置
->withWechatPay([$wechatpayCertificate]) // 可传入多个微信支付平台证书,参数类型为array
->build();
// 将WechatPayMiddleware添加到Guzzle的HandlerStack中
$stack = HandlerStack::create();
$stack->push($wechatpayMiddleware, 'wechatpay');
// 创建Guzzle HTTP Client时,将HandlerStack传入,接下来,正常使用Guzzle发起API请求,WechatPayMiddleware 会自动地处理签名和验签
$client = new Client(['handler' => $stack]);
// 接下来,正常使用Guzzle发起API请求,WechatPayMiddleware会自动地处理签名和验签
return $client;
// 接下来,正常使用Guzzle发起API请求,WechatPayMiddleware会自动地处理签名和验签
// $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
// $params = [
// 'appid' => $appid,
// 'mchid' => $mchid,
// 'description' => $productName,
// 'out_trade_no' => $out_trade_no,
// 'notify_url' => "微信支付结果通知URL",
// 'amount' => ["total" => $shipping],
// 'payer' => ["openid" => $userId]
// ];
// $client = new WxPayClient();
// $clients = $client->setAuthorization("POST", $url, $params);
// $resp = $clients->request("POST", $url, [
// 'headers' => ['Accept' => 'application/json','Content-Type'=>'application/json'],
// 'json' => $params
// ]);
// $prepay = json_decode($resp->getBody(), true);
// $prepay_id = $prepay['prepay_id'];
}
}