PHP code example of skoerfgen / acmecert

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

    

skoerfgen / acmecert example snippets


$handler=function($opts){
  // Write code to setup the challenge token here.

  // Return a function that gets called when the challenge token should be removed again:
  return function($opts){
    // Write code to remove previously setup challenge token.
  };
};

$ac->getCertificateChain(..., ..., $handler);



use skoerfgen\ACMECert\ACMECert;



use skoerfgen\ACMECert\ACMECert;



use skoerfgen\ACMECert\ACMECert;

$ac=new ACMECert('https://acme-v02.api.letsencrypt.org/directory');

$ac=new ACMECert('https://acme-staging-v02.api.letsencrypt.org/directory');

$ac=new ACMECert('https://api.buypass.com/acme/directory');

$ac=new ACMECert('https://api.test4.buypass.no/acme/directory');

$ac=new ACMECert('https://dv.acme-v02.api.pki.goog/directory');

$ac=new ACMECert('https://dv.acme-v02.test-api.pki.goog/directory');

$ac=new ACMECert('https://acme.ssl.com/sslcom-dv-rsa');

$ac=new ACMECert('https://acme.zerossl.com/v2/DV90');

$ac=new ACMECert('INSERT_URL_TO_AMCE_CA_DIRECTORY_HERE');

$key=$ac->generateRSAKey(2048);
file_put_contents('account_key.pem',$key);

$key=$ac->generateECKey('P-384');
file_put_contents('account_key.pem',$key);

$ac->loadAccountKey('file://'.'account_key.pem');
$ret=$ac->register(true,'[email protected]');
print_r($ret);

$ac->loadAccountKey('file://'.'account_key.pem');
$ret=$ac->registerEAB(true,'INSERT_EAB_KEY_ID_HERE','INSERT_EAB_HMAC_HERE','[email protected]');
print_r($ret);

$ac->loadAccountKey('file://'.'account_key.pem');

$domain_config=array(
  'test1.example.com'=>array('challenge'=>'http-01','docroot'=>'/var/www/vhosts/test1.example.com'),
  'test2.example.com'=>array('challenge'=>'http-01','docroot'=>'/var/www/vhosts/test2.example.com')
);

$handler=function($opts){
  $fn=$opts['config']['docroot'].$opts['key'];
  @mkdir(dirname($fn),0777,true);
  file_put_contents($fn,$opts['value']);
  return function($opts){
    unlink($opts['config']['docroot'].$opts['key']);
  };
};

// Generate new certificate key
$private_key=$ac->generateRSAKey(2048);

$fullchain=$ac->getCertificateChain($private_key,$domain_config,$handler);
file_put_contents('fullchain.pem',$fullchain);
file_put_contents('private_key.pem',$private_key);

$ac->loadAccountKey('file://'.'account_key.pem');

$domain_config=array(
  'example.com'=>array('challenge'=>'http-01','docroot'=>'/var/www/vhosts/example.com'),
  '*.example.com'=>array('challenge'=>'dns-01'),
  'test.example.org'=>array('challenge'=>'tls-alpn-01')
);

$handler=function($opts) use ($ac){
  switch($opts['config']['challenge']){
    case 'http-01': // automatic example: challenge directory/file is created..
      $fn=$opts['config']['docroot'].$opts['key'];
      @mkdir(dirname($fn),0777,true);
      file_put_contents($fn,$opts['value']);
      return function($opts) use ($fn){ // ..and removed after validation completed
        unlink($fn);
      };
    break;
    case 'dns-01': // manual example:
      echo 'Create DNS-TXT-Record '.$opts['key'].' with value '.$opts['value']."\n";
      readline('Ready?');
      return function($opts){
        echo 'Remove DNS-TXT-Record '.$opts['key'].' with value '.$opts['value']."\n";
      };
    break;
    case 'tls-alpn-01':
      $cert=$ac->generateALPNCertificate('file://'.'some_private_key.pem',$opts['domain'],$opts['value']);
      // Use $cert and some_private_key.pem(<- does not have to be a specific key,
      // just make sure you generated one) to serve the certificate for $opts['domain']


      // This example uses an included ALPN Responder - a standalone https-server
      // written in a few lines of node.js - which is able to complete this challenge.

      // store the generated verification certificate to be used by the ALPN Responder.
      file_put_contents('alpn_cert.pem',$cert);

      // To keep this example simple, the included Example ALPN Responder listens on port 443,
      // so - for the sake of this example - you have to stop the webserver here, like:
      shell_exec('/etc/init.d/apache2 stop');

      // Start ALPN Responder (

$chains=$ac->getCertificateChains('file://'.'cert_private_key.pem',$domain_config,$handler);
if (isset($chains['ISRG Root X1'])){ // use alternate chain 'ISRG Root X1'
  $fullchain=$chains['ISRG Root X1'];
}else{ // use default chain if 'ISRG Root X1' is not present
  $fullchain=reset($chains);
}
file_put_contents('fullchain.pem',$fullchain);

$ac->loadAccountKey('file://'.'account_key.pem');
$ac->revoke('file://'.'fullchain.pem');

$ac->loadAccountKey('file://'.'account_key.pem');
$ret=$ac->getAccount();
print_r($ret);

$ac->loadAccountKey('file://'.'account_key.pem');
$ret=$ac->keyChange('file://'.'new_account_key.pem');
print_r($ret);

$ac->loadAccountKey('file://'.'account_key.pem');
$ret=$ac->deactivateAccount();
print_r($ret);

$ret=$ac->getARI('file://'.'fullchain.pem',$ari_cert_id);
if ($ret['suggestedWindow']['start']-time()>0) {
  die('Certificate still good, exiting..');
}

$settings=array(
  'replaces'=>$ari_cert_id
);
$ac->getCertificateChain(..., ..., ..., $settings);

$percent=$ac->getRemainingPercent('file://'.'fullchain.pem'); // certificate or certificate-chain
if ($precent>33.333) { // certificate has still more than 1/3 (33.333%) of its lifetime left
  die('Certificate still good, exiting..');
}
// get new certificate here..

$days=$ac->getRemainingDays('file://'.'fullchain.pem'); // certificate or certificate-chain
if ($days>30) { // renew 30 days before expiry
  die('Certificate still good, exiting..');
}
// get new certificate here..

error_reporting(E_ALL);
ini_set('log_errors',1);
ini_set('error_log',dirname(__FILE__).'/ACMECert.log');

$ac->setLogger(false);

$ac->setLogger(function($txt){
	echo 'Log Message: '.$txt."\n";
});

use skoerfgen\ACMECert\ACME_Exception;

try {
  echo $ac->getAccountID().PHP_EOL;
}catch(ACME_Exception $e){
  if ($e->getType()=='urn:ietf:params:acme:error:accountDoesNotExist'){
    echo 'Account does not exist'.PHP_EOL;
  }else{
    throw $e; // another error occured
  }
}

try {
  $cert=$ac->getCertificateChain('file://'.'cert_private_key.pem',$domain_config,$handler);
} catch (\skoerfgen\ACMECert\ACME_Exception $e){
  $ac->log($e->getMessage()); // log original error
  foreach($e->getSubproblems() as $subproblem){
    $ac->log($subproblem->getMessage()); // log sub errors
  }
}

public ACMECert::__construct ( string $ca_url = 'https://acme-v02.api.letsencrypt.org/directory' )

public string ACMECert::generateRSAKey ( int $bits = 2048 )

public string ACMECert::generateECKey ( string $curve_name = 'P-384' )

public void ACMECert::loadAccountKey ( mixed $account_key_pem )

public array ACMECert::register ( bool $termsOfServiceAgreed = FALSE [, mixed $contacts = array() ] )

public array ACMECert::registerEAB ( bool $termsOfServiceAgreed, string $eab_kid, string $eab_hmac [, mixed $contacts = array() ] )

public array ACMECert::update ( mixed $contacts = array() )

public array ACMECert::getAccount()

public string ACMECert::getAccountID()

public array ACMECert::keyChange ( mixed $new_account_key_pem )

public array ACMECert::deactivateAccount()

public string ACMECert::getCertificateChain ( mixed $pem, array $domain_config, callable $callback, array $settings = array() )

> $domain_config=array(
>   '*.example.com'=>array('challenge'=>'dns-01'),
>   'test.example.org'=>array('challenge'=>'tls-alpn-01')
>   'test.example.net'=>array('challenge'=>'http-01','docroot'=>'/var/www/vhosts/test1.example.com'),
> );
> 

> callable callback ( array $opts )
> 

> > $handler=function($opts) use ($variable_from_parent_scope){};
> >                          ^^^
> > 

>> array( 'notAfter' => time() + (60*60*24) * 3 )
>> 

>> array( 'notAfter' => '1970-01-01T01:22:17+01:00' )
>> 

public string ACMECert::getCertificateChains ( mixed $pem, array $domain_config, callable $callback, array $settings = array() )

public void ACMECert::revoke ( mixed $pem )

public string ACMECert::generateCSR ( mixed $private_key, array $domains )

public string ACMECert::generateALPNCertificate ( mixed $private_key, string $domain, string $token )

public array ACMECert::parseCertificate ( mixed $pem )

public float ACMECert::getRemainingPercent( mixed $pem )

public float ACMECert::getRemainingDays ( mixed $pem )

public array ACMECert::splitChain ( string $pem )

public array ACMECert::getCAAIdentities()

public array ACMECert::getSAN( mixed $pem )

public array ACMECert::getTermsURL()

public void ACMECert::setLogger( bool|callable $value = TRUE )

> void callback( string $txt )
> 

public array ACMECert::getARI( mixed $pem, string &$ari_cert_id = null )