PHP code example of godrealms / wechat-php-sdk
1. Go to this page and download the library: Download godrealms/wechat-php-sdk 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/ */
godrealms / wechat-php-sdk example snippets
use WeChatSDK\Config;
$config = new Config('your_app_id', 'your_app_secret');
use WeChatSDK\Auth\OAuth;
$oauth = new OAuth($config);
// 生成授权 URL
$redirectUri = 'https://yourdomain.com/callback';
$scope = 'snsapi_userinfo'; // 或 'snsapi_base'
$state = 'custom_state';
$authUrl = $oauth->getAuthorizeUrl($redirectUri, $scope, $state);
echo $authUrl;
// 获取访问令牌
$code = 'authorization_code_from_wechat';
$accessToken = $oauth->getAccessToken($code);
print_r($accessToken);
// 获取用户信息
$userInfo = $oauth->getUserInfo($accessToken['access_token'], $accessToken['openid']);
print_r($userInfo);
use WeChatSDK\Offiaccount\CardManager;
$cardManager = new CardManager($config);
// 创建卡券
$cardData = [
'card_type' => 'GROUPON',
'groupon' => [
'base_info' => [
'logo_url' => 'https://example.com/logo.png',
'brand_name' => 'Brand',
'title' => 'Groupon Title',
'color' => 'Color010',
'notice' => 'Use this card at checkout',
'description' => 'Card description',
// 其他参数...
],
'deal_detail' => 'Groupon details...',
],
];
$response = $cardManager->createCard($cardData);
print_r($response);
use WeChatSDK\Config;
use WeChatSDK\Payment\Payment;
// 初始化支付配置
$config = new Config(
'your_app_id', // AppID
'your_app_secret', // AppSecret
'', // Token (支付用不到)
'', // AES Key (支付用不到)
'your_mch_id', // MchID (商户ID)
'your_api_key' // API密钥
);
// 初始化支付类
$payment = new Payment($config);
// 调用统一下单接口
$unifiedOrderParams = [
'body' => '测试商品', // 商品描述
'out_trade_no' => date('YmdHis') . rand(1000, 9999), // 商户订单号
'total_fee' => 1, // 总金额,单位为分
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], // 终端IP
'notify_url' => 'https://yourdomain.com/notify', // 异步通知地址
'trade_type' => 'JSAPI', // 交易类型
'openid' => 'user_openid', // 用户标识
];
$result = $payment->unifiedOrder($unifiedOrderParams);
if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
// 获取JSAPI支付参数
$prepayId = $result['prepay_id'];
$jsApiParams = $payment->getJsApiParameters($prepayId);
// 将$jsApiParams传递给前端页面,用于调起微信支付
echo json_encode($jsApiParams);
}
bash
composer html
<script>
function onBridgeReady() {
WeixinJSBridge.invoke('getBrandWCPayRequest', {
'appId': '<?= $jsApiParams['appId'] bash
phpunit --bootstrap vendor/autoload.php tests