Index.php 1.9 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    function getAccessToken() {
        $appId = "wx58ceff4e93cfc523";
        $appSecret = "baf744d21875280a5e98611f66adaf91";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
        $result = json_decode(file_get_contents($url), true);
        return $result["access_token"] ?? null;
    }

    function createMiniProgramQRCode($accessToken, $path, $width = 430) {
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$accessToken}";

        $data = json_encode([
            'path' => $path,
            'width' => $width
        ]);
        $options = [
            'http' => [
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                'content' => $data,
            ],
        ];
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        print_r($result);return;

        if ($result === false) {
            return false;
        }
        return $result;
    }
    public function test(){
        $accessToken = $this->getAccessToken();
        if ($accessToken) {
            $path = 'pages/index/index'; // 小程序内的页面路径
            $qrCodeData = $this->createMiniProgramQRCode($accessToken, $path);

            if ($qrCodeData) {
                header('Content-Type: image/png');
                echo $qrCodeData;
            } else {
                echo "Failed to generate QR code.";
            }
        } else {
            echo "Failed to get access token.";
        }
    }
}