PHP code example of zoujingli / wechat-developer
1. Go to this page and download the library: Download zoujingli/wechat-developer 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/ */
zoujingli / wechat-developer example snippets
// 1. 引入SDK
config = [
'appid' => 'your_wechat_appid',
'appsecret' => 'your_wechat_appsecret',
'mch_id' => 'your_merchant_id', // 微信支付需要
'mch_key' => 'your_merchant_key', // 微信支付需要
'cache_path' => '/path/to/cache' // 可选,缓存目录
];
// 3. 创建实例并调用
try {
// 微信用户管理
$user = \We::WeChatUser($config);
$userList = $user->getUserList();
// 微信支付
$pay = \We::WePayOrder($config);
$order = $pay->create($orderData);
// 支付宝支付
$alipay = \We::AliPayWeb($config);
$html = $alipay->apply($payData);
// 使用通用接口(万能接口)
// 所有接口类都提供 callApi() 方法,支持多种 HTTP 方法
$result = $user->callApi('https://api.weixin.qq.com/cgi-bin/user/get?ACCESS_TOKEN', [], 'GET');
$result = $pay->callApi('https://api.mch.weixin.qq.com/pay/unifiedorder', $data, 'POST');
$result = $alipay->callApi('alipay.trade.query', $params, 'GET'); // 支付宝:apiMethod 作为第一参数
} catch (Exception $e) {
echo "错误:" . $e->getMessage();
}
// 获取用户列表
$user = \We::WeChatUser($config);
$result = $user->getUserList();
// 批量获取用户信息
foreach (array_chunk($result['data']['openid'], 100) as $openids) {
$userList = $user->getBatchUserInfo($openids);
foreach ($userList['user_info_list'] as $userInfo) {
echo "用户:" . $userInfo['nickname'] . "\n";
}
}
// 设置用户备注
$user->updateMark('openid', 'VIP用户');
// 创建临时二维码
$qrcode = \We::WeChatQrcode($config);
$result = $qrcode->create('场景内容');
// 获取二维码链接
$url = $qrcode->url($result['ticket']);
echo "二维码链接:" . $url;
// 获取当前菜单
$menu = \We::WeChatMenu($config);
$result = $menu->get();
// 创建自定义菜单
$menuData = [
'button' => [
[
'type' => 'click',
'name' => '今日歌曲',
'key' => 'V1001_TODAY_MUSIC'
],
[
'name' => '菜单',
'sub_button' => [
[
'type' => 'view',
'name' => '搜索',
'url' => 'http://www.soso.com/'
]
]
]
]
];
$menu->create($menuData);
// 创建支付订单
$pay = \We::WePayOrder($config);
$options = [
'body' => '测试商品',
'out_trade_no' => time(),
'total_fee' => '1',
'openid' => 'o38gpszoJoC9oJYz3UHHf6bEp0Lo',
'trade_type' => 'JSAPI', // JSAPI/NATIVE/APP/MWEB
'notify_url' => 'https://your-domain.com/notify.php',
'spbill_create_ip' => '127.0.0.1',
];
$result = $pay->create($options);
// 生成JSAPI支付参数
$jsApiParams = $pay->createParamsForJsApi($result['prepay_id']);
// 将 $jsApiParams 传给前端发起支付
// 创建V3支付订单
$payment = \WePayV3\Order::instance($config);
$order = (string)time();
// JSAPI支付
$result = $payment->create('jsapi', [
'appid' => $config['appid'],
'mchid' => $config['mch_id'],
'description' => '商品描述',
'out_trade_no' => $order,
'notify_url' => 'https://your-domain.com/notify.php',
'payer' => ['openid' => 'o38gps3vNdCqaggFfrBRCRikwlWY'],
'amount' => ['total' => 2, 'currency' => 'CNY'],
]);
// H5支付
$result = $payment->create('h5', [
'appid' => $config['appid'],
'mchid' => $config['mch_id'],
'description' => '商品描述',
'out_trade_no' => $order,
'notify_url' => 'https://your-domain.com/notify.php',
'amount' => ['total' => 2, 'currency' => 'CNY'],
'scene_info' => [
'h5_info' => ['type' => 'Wap'],
'payer_client_ip' => '14.23.150.211',
],
]);
// 查询订单
$result = $payment->query($order);
// 创建退款
$refundResult = $payment->createRefund([
'out_trade_no' => $order,
'out_refund_no' => strval(time()),
'amount' => [
'refund' => 2,
'total' => 2,
'currency' => 'CNY'
]
]);
// 发送微信红包
$redpack = \We::WePayRedpack($config);
$options = [
'mch_billno' => time(),
're_openid' => 'o38gps3vNdCqaggFfrBRCRikwlWY',
'send_name' => '商户名称',
'act_name' => '活动名称',
'total_amount' => '100',
'total_num' => '1',
'wishing' => '感谢您参加活动!',
'remark' => '快来抢红包!',
'client_ip' => '127.0.0.1',
];
$result = $redpack->create($options);
// 查询红包记录
$result = $redpack->query($options['mch_billno']);
// 支付宝网站支付
$alipay = \We::AliPayWeb($config);
$result = $alipay->apply([
'out_trade_no' => time(),
'total_amount' => '1',
'subject' => '支付订单描述',
]);
// 直接输出HTML表单,用户点击即可跳转支付
echo $result;
// 支付宝App支付
$alipay = \We::AliPayApp($config);
$result = $alipay->apply([
'out_trade_no' => strval(time()),
'total_amount' => '1',
'subject' => '支付宝订单标题',
]);
// 返回支付参数字符串,传给App端
echo $result;
// 支付宝转账
$transfer = \We::AliPayTransfer($config);
$result = $transfer->create([
'out_biz_no' => time(),
'trans_amount' => '10',
'product_code' => 'TRANS_ACCOUNT_NO_PWD',
'biz_scene' => 'DIRECT_TRANSFER',
'payee_info' => [
'identity' => '[email protected] ',
'identity_type' => 'ALIPAY_LOGON_ID',
'name' => '收款人姓名',
],
]);
// 小程序用户登录
$mini = \We::WeMiniCrypt($config);
// 获取session_key
$session = $mini->session($code);
// 解密用户数据
$userInfo = $mini->userInfo($code, $iv, $encryptedData);
// 直接解密数据
$decoded = $mini->decode($iv, $sessionKey, $encryptedData);
// 生成小程序码
$qrcode = \We::WeMiniQrcode($config);
$result = $qrcode->create([
'scene' => 'id=123',
'page' => 'pages/index/index',
'width' => 430
]);
// 微信公众号
callApi(string $url, array|string $data = [], string $method = 'GET')
// 微信支付V2
callApi(string $url, array|string $data = [], string $method = 'POST', bool $isCert = false, string $signType = 'HMAC-SHA256')
// 微信支付V3
callApi(string $url, array|string $data = '', string $method = 'POST', bool $verify = false)
// 支付宝
callApi(string $apiMethod, array|string $data = [], string $method = 'GET', bool $verify = false)
$user = \We::WeChatUser($config);
// GET请求 - 自动处理ACCESS_TOKEN
$result = $user->callApi(
'https://api.weixin.qq.com/cgi-bin/user/info?openid=OPENID&lang=zh_CN&ACCESS_TOKEN',
[], // GET参数(如果URL中已包含参数,这里可以为空)
'GET'
);
// POST请求 - 批量获取用户信息(自动JSON编码)
$result = $user->callApi(
'https://api.weixin.qq.com/cgi-bin/user/info/batchget?ACCESS_TOKEN',
['user_list' => [['openid' => 'xxx'], ['openid' => 'yyy']]],
'POST'
);
// PUT请求 - 更新资源
$result = $user->callApi($url, $data, 'PUT');
// DELETE请求 - 删除资源
$result = $user->callApi($url, $data, 'DELETE');
// PATCH请求 - 部分更新
$result = $user->callApi($url, $data, 'PATCH');
$pay = \We::WePayOrder($config);
// POST请求 - 统一下单(自动签名,默认HMAC-SHA256)
$result = $pay->callApi(
'https://api.mch.weixin.qq.com/pay/unifiedorder',
[
'body' => '测试商品',
'out_trade_no' => time(),
'total_fee' => '1',
'openid' => 'o38gpszoJoC9oJYz3UHHf6bEp0Lo',
'trade_type' => 'JSAPI',
'notify_url' => 'https://your-domain.com/notify.php',
'spbill_create_ip' => '127.0.0.1',
],
'POST'
);
// POST请求 - 使用MD5签名
$result = $pay->callApi(
'https://api.mch.weixin.qq.com/pay/unifiedorder',
$data,
'POST',
false, // 不需要证书
'MD5' // 签名类型:MD5
);
// POST请求 - 需要证书(如退款)
$result = $pay->callApi(
'https://api.mch.weixin.qq.com/secapi/pay/refund',
$data,
'POST',
true, // 需要证书
'MD5' // 签名类型
);
// GET请求 - 查询订单
$result = $pay->callApi(
'https://api.mch.weixin.qq.com/pay/orderquery',
['out_trade_no' => '123456'],
'GET'
);
// PUT/DELETE请求
$result = $pay->callApi($url, $data, 'PUT', false, 'MD5');
$result = $pay->callApi($url, $data, 'DELETE', false, 'MD5');
$payment = \WePayV3\Order::instance($config);
// POST请求 - 创建JSAPI支付订单(相对路径)
$result = $payment->callApi(
'/v3/pay/transactions/jsapi',
[
'appid' => $config['appid'],
'mchid' => $config['mch_id'],
'description' => '商品描述',
'out_trade_no' => (string)time(),
'notify_url' => 'https://your-domain.com/notify.php',
'payer' => ['openid' => 'o38gpszoJoC9oJYz3UHHf6bEp0Lo'],
'amount' => ['total' => 2, 'currency' => 'CNY'],
],
'POST'
);
// GET请求 - 查询订单(完整URL或相对路径)
$result = $payment->callApi(
'/v3/pay/transactions/out-trade-no/123456?mchid=' . $config['mch_id'],
'',
'GET',
true // 验证响应签名
);
// PUT请求 - 更新资源
$result = $payment->callApi('/v3/some/resource/xxx', $data, 'PUT');
// DELETE请求 - 删除资源
$result = $payment->callApi('/v3/some/resource/xxx', '', 'DELETE');
$alipay = \We::AliPayWeb($config);
// GET请求 - 查询订单
$result = $alipay->callApi(
'alipay.trade.query', // API方法名(必填,第一参数)
['out_trade_no' => '123456'],
'GET',
false // 验证响应签名,默认false
);
// POST请求 - 订单退款
$result = $alipay->callApi(
'alipay.trade.refund', // API方法名(第一参数)
[
'out_trade_no' => '123456',
'refund_amount' => '10',
],
'POST',
false // 不验证响应签名
);
// PUT/DELETE请求
$result = $alipay->callApi('alipay.some.method', $data, 'PUT', false);
// 配置自定义缓存(适配常驻内存框架)
\WeChat\Contracts\Tools::$cache_callable = [
'set' => function ($name, $value, $expired = 360) {
// 自定义缓存设置逻辑
// $name: 缓存名称
// $value: 缓存值
// $expired: 过期时间(秒)
return Redis::setex($name, $expired, serialize($value));
},
'get' => function ($name) {
// 自定义缓存获取逻辑
// $name: 缓存名称
// 返回: 缓存值或 null
$data = Redis::get($name);
return $data ? unserialize($data) : null;
},
'del' => function ($name) {
// 自定义缓存删除逻辑
// $name: 缓存名称
// 返回: boolean
return Redis::del($name);
},
'put' => function ($name, $content) {
// 自定义文件缓存逻辑(用于证书等文件)
// $name: 文件名称
// $content: 文件内容
// 返回: 文件路径(必须是可读的文件路径)
$file = '/path/to/cache/' . $name;
file_put_contents($file, $content);
return $file;
},
];
// 注意:
// 1. 未配置自定义缓存时,默认使用文件缓存
// 2. 文件缓存路径可通过配置中的 'cache_path' 参数设置
// 3. SDK 会自动清理 CURL 临时缓存文件,无需手动处理
// 4. 在常驻内存框架中,建议使用 Redis 等外部缓存替代文件缓存
try {
$user = \We::WeChatUser($config);
$result = $user->getUserList();
} catch (\WeChat\Exceptions\InvalidResponseException $e) {
// 接口调用异常
echo "接口错误:" . $e->getMessage();
} catch (\WeChat\Exceptions\LocalCacheException $e) {
// 缓存异常
echo "缓存错误:" . $e->getMessage();
} catch (Exception $e) {
// 其他异常
echo "系统错误:" . $e->getMessage();
}
$mini = \We::WeMiniNewtmpl($config);
$mini->send([
'touser' => '用户openid',
'template_id' => '模板ID',
'page' => 'pages/index?foo=bar',
'data' => [
'thing1' => ['value' => '订单已支付'],
'time2' => ['value' => '2024-01-01 12:00'],
],
]);
$security = \We::WeMiniSecurity($config);
// 文本校验
$security->msgSecCheck('留言内容示例');
// 图片校验(文件流)
$imgContent = file_get_contents('/path/to/demo.jpg');
$security->imgSecCheck($imgContent);
$wechatConfig = [
'appid' => 'wx60a43dd8161666d4',
'appsecret' => 'b4e28746f1bd73b5c6684f5e01883c36',
'token' => 'your_wechat_token',
'encodingaeskey' => 'your_encodingaeskey',
'cache_path' => '/path/to/cache',
];
// 微信支付V2配置
$payConfig = [
'appid' => 'wx60a43dd8161666d4',
'mch_id' => '15293xxxxxx',
'mch_key' => 'your_merchant_key',
'cache_path' => '/path/to/cache',
];
// 微信支付V3配置(推荐)
$payV3Config = [
'appid' => 'wx60a43dd8161666d4',
'mch_id' => '15293xxxxxx',
'mch_v3_key' => '98b7fxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cert_serial' => '49055D67B2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'cert_public' => '-----BEGIN CERTIFICATE-----...',
'cert_private' => '-----BEGIN PRIVATE KEY-----...',
'cache_path' => '/path/to/cache',
'cert_package' => [
'PUB_KEY_ID_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' => '-----BEGIN CERTIFICATE-----...'
],
];
// 支付宝公钥模式配置
$alipayConfig = [
'appid' => '2021000122667306',
'private_key' => 'MIIEowIBAAKCAQEAn...',
'public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...',
'sign_type' => 'RSA2',
'notify_url' => 'https://your-domain.com/alipay/notify',
'return_url' => 'https://your-domain.com/alipay/return',
'charset' => 'utf-8',
'debug' => false, // 生产环境设为false
];
// 支付宝证书模式配置
$alipayCertConfig = [
'appid' => '2021000122667306',
'private_key' => 'MIIEowIBAAKCAQEAn...',
'app_cert_path' => '/path/to/appPublicCert.crt',
'alipay_root_path' => '/path/to/alipayRootCert.crt',
'alipay_cert_path' => '/path/to/alipayPublicCert.crt',
'sign_type' => 'RSA2',
'notify_url' => 'https://your-domain.com/alipay/notify',
'return_url' => 'https://your-domain.com/alipay/return',
];