生成带post参数的微信小程序二维码

	/**
     * 生成微信小程序二维码
     * @param $params  需要携带的参数
     * @return string
     */
    public function createWxQrcode($params)
    {
        //配置APPID、APPSECRET
        $wxapp = \config();
        //获取access_token
        $access_token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wxapp['AppId'] . '&secret=' . $wxapp['AppSecret'];
        //缓存access_token
        session_start();
        $_SESSION['access_token'] = "";
        $_SESSION['expires_in'] = 0;

        if (!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in'])) {
            // 通过get请求获取access_token
            $json = curl_get($access_token);
            $_SESSION['access_token'] = $json['access_token'];
            $_SESSION['expires_in'] = time() + 7200;  // 过期时间 秒
            $ACCESS_TOKEN = $json["access_token"];
        } else {
            $ACCESS_TOKEN = $_SESSION["access_token"];
        }
        
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        //path是扫描二维码跳转的小程序路径,可以带get参数?id=xxx
        //width是二维码宽度
        $param = json_encode(array("path" => "", "width" => 73));
        //构建请求二维码参数   POST参数
        $result = $this->httpRequest($qcode, $param,"POST");
        $filename = CACHE_PATH . 'posters' . DS . 'qrocde'.$params['member_id'].'.jpg';
        //生成二维码
        file_put_contents($filename, $result);
        $image = CACHE_PATH . 'posters' . DS . 'qrocde'.$params['member_id'].'.jpg';  // 路径

        return $image;
    }

    //把请求发送到微信服务器换取二维码
    public function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

然后二维码就生成成功了

你可能感兴趣的:(微信)