PHP code example of ethenoscar2011 / pt-wechatpay-php

1. Go to this page and download the library: Download ethenoscar2011/pt-wechatpay-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ethenoscar2011 / pt-wechatpay-php example snippets




tWeChatPay\Builder;
use PtWeChatPay\Crypto\Rsa;

// 设置参数

// 商户号
$merchantId = '190000****';

// 从本地文件中加载「商户API私钥」,「商户API私钥」会用来生成请求的签名
$merchantPrivateKeyFilePath = 'file:///path/to/merchant/apiclient_key.pem';
$merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);

// 「商户API证书」的「证书序列号」
$merchantCertificateSerial = '3775B6A45ACD588826D15E583A95F5DD********';

// 从本地文件中加载「微信支付平台证书」,可由内置CLI工具下载到,用来验证微信支付应答的签名
$platformCertificateFilePath  = 'file:///path/to/wechatpay/certificate.pem';
$onePlatformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);

// 「微信支付平台证书」的「平台证书序列号」
// 可以从「微信支付平台证书」文件解析,也可以在 商户平台 -> 账户中心 -> API安全 查询到
$platformCertificateSerial = '7132D72A03E93CDDF8C03BBD1F37EEDF********';

// 从本地文件中加载「微信支付公钥」,用来验证微信支付应答的签名
$platformPublicKeyFilePath    = 'file:///path/to/wechatpay/publickey.pem';
$twoPlatformPublicKeyInstance = Rsa::from($platformPublicKeyFilePath, Rsa::KEY_TYPE_PUBLIC);

// 「微信支付公钥」的「微信支付公钥ID」
// 需要在 商户平台 -> 账户中心 -> API安全 查询
$platformPublicKeyId = 'PUB_KEY_ID_01142321349124100000000000********';

// 构造一个 APIv3 客户端实例
$instance = Builder::factory(array(
    'mchid'      => $merchantId,
    'serial'     => $merchantCertificateSerial,
    'privateKey' => $merchantPrivateKeyInstance,
    'certs'      => array(
        $platformCertificateSerial => $onePlatformPublicKeyInstance,
        $platformPublicKeyId       => $twoPlatformPublicKeyInstance,
    ),
));

// 发送请求
try {
    $resp = $instance->chain('v3/certificates')->get(
        // array('debug' => true) // 调试模式
    );
    echo (string) $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 (string) $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
    }
    echo $e->getTraceAsString(), PHP_EOL;
}

AesGcm::decrypt($cert->ciphertext, $apiv3Key, $cert->nonce, $cert->associated_data);