How To Use the PayPal API with Certificate Authentication
I have struggled to find good documentation for authenticating with paypal via a certificate. I have found a few blog posts, but none of these had definitive answers on how to implement it. I’m going to be explaining how to get things setup on Windows with .NET code. However, most of the content in here will be useful for any platform, with some minor tweaks.
Convert cert_key_pem.txt to p12
Using OpenSSL, convert to the key you received from PayPal to pkcs12 format. Keep track of the password that you choose for later reference.
openssl pkcs12 -export -in cert_key_pem.txt -out cert_key.p12
Note: I’m going to install it via command line and give permissions to “NETWORK SERVICE” so that IIS can access the certificate. This will probably be different for OSX and Linux and also may vary depending on your programming language of choice for communicating with paypal.
First, change directories to where you saved your .p12 file.
Then you can either, try installing the cert from the directory you saved the .p12 in. Note: if you don’t have WinHttpCertCfg installed, you can get it here. It comes preinstalled on Windows Server, but if you’re testing on your developer machine, you’ll need to download it.
Make sure you are running your command prompt/powershell as an administrator during this step:
“C:\Program Files (x86)\Windows Resource Kits\Tools\WinHttpCertCfg” -i cert_key.p12 -p P@ssw0rd -c LOCAL_MACHINE\my -a “NETWORK SERVICE”
Or, if that gives you issues, you can change directories to “C:\Program Files (x86)\Windows Resource Kits\Tools\” so that you can run WinHttpCertCfg.exe in its folder.
.\winhttpcertcfg -i C:/path/to/key/cert_key.p12 -p P@ssw0rd -c LOCAL_MACHINE\my -a “NETWORK SERVICE”
At this point, you should get a message indicating that you’re certificate was imported.
If you’re not programming in C# for .NET, you can ignore the rest of this section. At this point, you’re certificate is installed and ready for use.
Where you are creating your
HttpWebRequest, you can add your certificate information onto the request like:
var request = (HttpWebRequest) WebRequest.Create(WebConfigurationManager.AppSettings[“PayPalDataUrl”]);
var certPath = GetCertificatePath();
var certPassword = GetCertificatePassword();
var cert = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.MachineKeySet);
This will add the certificate to be used as authentication and you would add the rest of the request like you would with signature authentication.
At this point, you should be ready to use this certificate to authenticate your paypal express checkout order with paypal.
I plan to improve this document as I remember snags that I went through to get this working for my site. If you have any questions, or feedback, I will gladly like to hear it.