Sunday, September 8, 2024

How to Signing PDFs Digitally with Laravel and PDF Signify


This guide will walk you through the process of digitally signing PDFs using PHP and the Laravel framework, leveraging the free external service API provided by PDFSignify.

Why Digital Signatures?

Digital signatures are essential for ensuring the authenticity and integrity of your PDFs. They guarantee that the document hasn't been tampered with and confirms the sender's identity.

Prerequisites:

  • A Laravel Project: If you don't have one, create a new Laravel project using Composer:

          composer create-project --prefer-dist laravel/laravel pdf-signing-app
        
    A Digital Certificate: You'll need a digital certificate in .pfx or .p12 format, containing your private key and certificate, along with its associated password.

Part 1: Setting Up the Laravel Environment

  1. Navigate to your project directory:

          cd pdf-signing-app
        

  2. Create your .env file:

          cp .env.example .env
        

  3. Generate the application key:

          php artisan key:generate
        

  4. Configure your database:

    • Open the .env file and set the following database configuration variables. Replace the placeholders with your database credentials.

      DB_CONNECTION=mysql
      DB_HOST=127.0.0.1
      DB_PORT=3306
      DB_DATABASE=your_database_name
      DB_USERNAME=your_database_username
      DB_PASSWORD=your_database_password
          

  5. Migrate your database:

          php artisan migrate
        

Part 2: Setting Up PDF Signify

  1. Create a PDF Signify Account:

    • Visit the PDF Signify website.

    • Sign up for an account using your email address or by linking your Google or Microsoft account.

  2. Verify your email address:

    • Follow the link in the verification email sent to your inbox.

  3. Create a new project:

    • Select the "Free Plan" to get started.

    • Give your project a name and create it.

  4. Access the Admin Dashboard:

    • View your API keys, plan limits, and API usage.

Part 3: Creating API Credentials

  1. Navigate to the "API Credentials" section:

    • Click on the "API Credentials" option in the sidebar of your PDF Signify project dashboard.

  2. Create new API credentials:

    • Click on the "Create Credentials" button.

    • A popup will appear displaying your API Key and Secret Key.

    • Important: Save these keys in a secure location as you'll need them for authentication.

Part 4: Coding the Laravel Application

  1. Save your PDF file:

    • Place the PDF you want to sign in the storage/app directory of your Laravel project.

    • Rename the file to filepdf.pdf.

  2. Create a new route and controller:

    • Open routes/web.php and add the following route:

      use App\Http\Controllers\PDFSignController;
      
      Route::get('/sign-pdf', [PDFSignController::class, 'signPDF'])->name('sign.pdf');
          

    • Create a new controller called PDFSignController in the app/Http/Controllers directory:

      <?php
      
      namespace App\Http\Controllers;
      
      use Illuminate\Support\Facades\Storage;
      use CURLFile;
      
      class PDFSignController extends Controller
      {
          public function signPDF()
          {
              $certPath = Storage::path('certificate.pfx'); // Replace 'certificate.pfx' with your certificate file name
              $pdfPath = Storage::path('filepdf.pdf');
              $password = "YOUR_CERTIFICATE_PASSWORD"; // Replace with your certificate password
      
              $postFields = [
                  'certificate' => new CURLFile($certPath, 'application/x-pkcs12', 'certificate.pfx'),
                  'certificatePassword' => $password,
                  'pdf' => new CURLFile($pdfPath, 'application/pdf', 'filepdf.pdf')
              ];
      
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_URL, 'https://api.pdfsignify.com/api/v1/sign-pdf');
              curl_setopt($ch, CURLOPT_POST, 1);
              curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
              curl_setopt($ch, CURLOPT_HTTPHEADER, [
                  'Content-Type: multipart/form-data',
                  'AccessKey: ' . env('PDFSIGNIFY_ACCESS_KEY'), // Replace 'PDFSIGNIFY_ACCESS_KEY' with your actual key
                  'SecretKey: ' . env('PDFSIGNIFY_SECRET_KEY'),  // Replace 'PDFSIGNIFY_SECRET_KEY' with your actual key
              ]);
      
              $response = curl_exec($ch);
              $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
              curl_close($ch);
      
              if ($statusCode != 200) {
                  return response()->json(['response' => $response], 500);
              }
      
              return response($response, 200)
                  ->header('Content-Type', 'application/pdf')
                  ->header('Content-Disposition', 'attachment; filename="signed_filepdf.pdf"');
          }
      }
          

  3. Set up your digital certificate and password:

    • Place your certificate file (certificate.pfx or certificate.p12) in the storage/app directory.

    • Replace "YOUR_CERTIFICATE_PASSWORD" in the code with your certificate's password.

    • In your .env file, add the following:

      PDFSIGNIFY_ACCESS_KEY="YOUR_ACCESS_KEY"
      PDFSIGNIFY_SECRET_KEY="YOUR_SECRET_KEY"
          

      Replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with the values you generated in the PDF Signify dashboard.

  4. Rerun your Laravel server:

          php artisan serve
        

  5. Test the sign route:

    • Access the route in your browser: http://localhost:8000/sign-pdf

    • Download the signed PDF to view the digital signature.

Part 5: Customizing the Signature

PDF Signify offers many customization options:

  • Background Image: (Requires a paid account)

    • Use the signatureBackgroundImage parameter to set your logo as the background image.

  • Image Near the Signature:

    • Use the signatureImage parameter to display an image near the signature.

  • Signature Parameters:

    • Customize the signature's appearance, position, and content using parameters like:

      • signatureFieldName: Unique name for the signature

      • signatureXPosition: X-coordinate in pixels

      • signatureYPosition: Y-coordinate in pixels

      • signatureWidth: Width in pixels

      • signatureHeight: Height in pixels

      • signatureMessage: Message for the signature

      • signatureDateLabel: Label for the date

      • signatureDateFormat: Format for the date

      • signatureReasonLabel: Label for the reason

      • signatureReason: Reason for the signature

      • signatureLocation: Location of the signature

      • signatureContactInfo: Contact information

      • signatureShowDistinguishedName: Whether to display the Distinguished Name

  • PDF Metadata:

    • Modify the PDF's metadata using parameters like:

      • pdfMetadataTitle: Title of the document

      • pdfMetadataSubject: Subject of the document

      • pdfMetadataAuthor: Author of the document

      • pdfMetadataKeywords: Keywords associated with the document

      • pdfMetadataCreator: Creator application

      • pdfMetadataProducer: Producer application

      • pdfMetadataCreationDate: Creation date

      • pdfMetadataModificationDate: Last modification date

Part 6: Verifying Certificate Validity and Password Match

You can use the /api/v1/check-certificate-password endpoint to verify the validity of a certificate and the correctness of the password.

Part 7: Conclusion

By following this guide, you've learned how to effortlessly integrate digital signatures into your Laravel applications using PDF Signify's easy-to-use API. This process ensures the authenticity and integrity of your PDFs, strengthening the security and reliability of your applications.

Remember, this is just a starting point. Experiment with the various customization options and explore the extensive PDF Signify API documentation to find more advanced features for your specific needs.

0 comments:

Post a Comment