前置条件
已有商户号、商户私钥(APIv2也叫证书密钥,文件名:apiclient_key.pem)、商户证书(文件名:apiclient_cert.pem),已开通企业微信产品功能,并关联了企业微信号,详细开通并关联说明点这里。
安装软件
composer require wechatpay/wechatpay
工厂方法创建一个APIv2
的实例
从工厂方法创建一个实例,APIv3
的参数随便填,保证mchid
,secret
,merchant[cert]
及merchant[key]
正确即可,例如:
use WeChatPay\Builder;
use WeChatPay\Formatter;
use WeChatPay\Transformer;
use WeChatPay\Crypto\Hash;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
$instance = Builder::factory([
'mchid' => '1234567',
'serial' => 'noop',
'privateKey' => 'noop',
'certs' => ['any' => null],
'secret' => 'abcdefg',
'merchant' => [
'cert' => $merchantCertFile,
'key' => $merchantPrivateKeyFile,
],
]);
加入企业微信专属签名函数中间件
$agentId = 1001;
$agentSecret = 'abcdefgshad';
/** @var \GuzzleHttp\HandlerStack $handler */
$handler = $instance->getDriver()->select('v2')->getConfig('handler');
$handler->before('transform_request', static function($handler) use ($agentSecret, $agentId): callable {
return static function(RequestInterface $request, array $options = []) use($handler, $agentSecret, $agentId): PromiseInterface {
$actName = $options['xml']['act_name'] ?? null;
$mchBillno = $options['xml']['mch_billno'] ?? null;
$mchId = $options['xml']['mch_id'] ?? null;
$nonceStr = $options['xml']['nonce_str'] ?? Formatter::nonce();
$reOpenid = $options['xml']['re_openid'] ?? null;
$totalAmount = $options['xml']['total_amount'] ?? null;
$wxappid = $options['xml']['wxappid'] ?? null;
if ($actName && $mchBillno && $mchId && $nonceStr && $reOpenid && $totalAmount && $wxappid) {
$options['xml']['workwx_sign'] = strtoupper(Hash::md5(
Formatter::queryStringLike(Formatter::ksort([
'act_name' => $actName,
'mch_billno' => $mchBillno,
'mch_id' => $mchId,
'nonce_str' => $nonceStr,
're_openid' => $reOpenid,
'total_amount' => $totalAmount,
'wxappid' => $wxappid,
]))
, $agentSecret
, $agentId
));
}
return $handler($request, $options);
};
}, 'workwxredpack');
发放企业红包
$res = $instance->v2->mmpaymkttransfers->sendworkwxredpack->postAsync([
'security' => true,
'xml' => [
'mch_id' => '1234567',
'act_name' => 'test',
'mch_billno' => 'test1',
're_openid' => '111',
'total_amount' => '1',
'wxappid' => '111',
],
// 'debug' => true,
])
->then(static function($res) { return Transformer::toArray($res->getBody()->getContents()); })
->otherwise(static function($res) { return Transformer::toArray($res->getBody()->getContents()); })
->wait();
print_r($res);
注: wechatpay/wechatpay:~1.0.5
对类型做了强校验,这里的xml:total_amount金额,要用字符串分。
最后
企业微信发企业红包文档见这里,看着文档,填对参数,对接及代码写起来就是这么简单。。。
Repo: https://github.com/TheNorthMemory/wechatpay-php 欢迎 Star .
赞👍