PHP code example of fengz / kuaishou-miniapp-sdk

1. Go to this page and download the library: Download fengz/kuaishou-miniapp-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/ */

    

fengz / kuaishou-miniapp-sdk example snippets


use Fengz\KuaishouMiniapp\Facades\KuaishouMiniapp;

// code2Session 登录(前端调用 ks.login() → 把 js_code 发到你的服务器)
$session = KuaishouMiniapp::auth()->session($jsCode);
// ['result' => 1, 'session_key' => ..., 'open_id' => ...]

// 生成小程序二维码(base64 字符串)
$base64 = KuaishouMiniapp::qrcode()->generateBase64(['path' => 'pages/index/index', 'width' => 430]);
// 或解码后的二进制字节
$binary = KuaishouMiniapp::qrcode()->generateBinary(['path' => 'pages/index/index']);
// 或两者一起返回
$result = KuaishouMiniapp::qrcode()->generate();
// ['base64' => ..., 'binary' => ...]

// 订阅消息
KuaishouMiniapp::subscribe()->send(
    templateId: 'tpl-xxx',
    toUser: 'openid-xxx',
    page: 'pages/index/index',
    data: ['thing' => ['value' => '苹果']],
);

// Webhook 回调:验签 → 去重 → 应答
if (! KuaishouMiniapp::callback()->verifyRequest($request)) {
    abort(403); // kwaisign 签名不合法(rawBody . app_secret 的 md5)
}

$messageId = KuaishouMiniapp::callback()->messageIdFromRequest($request);

// 平台会用同一个 message_id 重推(最多 16 次),直到收到 {"result": 1}
// —— 只有首次送达才处理。
if ($messageId === null || KuaishouMiniapp::callback()->dedupe($messageId)) {
    $payload = json_decode((string) $request->getContent(), true);
    // 按 $payload['biz_type'] 处理 $payload['data']
}

return response()->json(['result' => 1, 'message_id' => $messageId]);

$session = kuaishou_miniapp()->auth()->session($jsCode);

try {
    KuaishouMiniapp::auth()->session($jsCode);
} catch (\Fengz\KuaishouMiniapp\Exceptions\KuaishouMiniappAuthorizationException $e) {
    // app_id / app_secret 错误或缺失 —— 检查配置
} catch (\Fengz\KuaishouMiniapp\Exceptions\KuaishouMiniappRequestException $e) {
    // 网络 / 传输层失败
} catch (\Fengz\KuaishouMiniapp\Exceptions\KuaishouMiniappApiException $e) {
    // 平台返回了非成功的 result
    // $e->errorCode()、$e->description()、$e->endpoint()、$e->rawResponse()
}
bash
php artisan vendor:publish --tag=kuaishou-miniapp-config