PHP code example of elim051 / yii2-wechat

1. Go to this page and download the library: Download elim051/yii2-wechat 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/ */

    

elim051 / yii2-wechat example snippets



'components' => [
    // ...
    'wechat' => [
        'class' => 'elim051\easywechat\Wechat',
        'config' => [  // easywechat configurations
            'app_id' => 'wx3cf0f39249eb0exx',
            'secret' => 'f1c242f4f28f735d4687abb469072axx',
            
            // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ]
        // 'sessionParam' => '' # wechat user info will be stored in session under this key
        // 'returnUrlParam' => '' # returnUrl param stored in session
    ],
    // ...
]


// here are two representative examples that will help you:

// 微信网页授权:
if(Yii::$app->wechat->isWechat && !Yii::$app->wechat->isAuthorized()) {
    return Yii::$app->wechat->authorizeRequired()->send();
}

// 自定义scopes
if(Yii::$app->wechat->isWechat && !Yii::$app->wechat->isAuthorized()) {
    Yii::$app->wechat->scopes = ['snsapi_userinfo'];
    return Yii::$app->wechat->authorizeRequired()->send();
}

// 微信支付(JsApi):
$orderData = [ 
    'openid' => '.. '
    // ... etc. 
];
$order = new WechatOrder($orderData);
$payment = Yii::$app->wechat->payment;
$prepayRequest = $payment->prepare($order);
if($prepayRequest->return_code = 'SUCCESS' && $prepayRequest->result_code == 'SUCCESS') {
	$prepayId = $prepayRequest->prepay_id;
}else{
	throw new yii\base\ErrorException('微信支付异常, 请稍后再试');
}

$jsApiConfig = $payment->configForPayment($prepayId);

return $this->render('wxpay', [
	'jsApiConfig' => $jsApiConfig,
	'orderData'   => $orderData
]);