Question

How can you convert from multiple currencies, using the PayPal API (Adaptive Payments) system? The documents only have stuff for Ruby, iOS, PHP, Rails etc... but not Perl!

https://developer.paypal.com/docs/classic/api/adaptive-payments/ConvertCurrency_API_Operation/

Was it helpful?

Solution

This is only meant as a guideline (to run in command line). It will run via the browser, but you need to add in a header (otherwise it'll give a 500 Internal Server Error)

The perl code is as follows:

currency.cgi

#!/usr/bin/perl

use warnings;
use strict;

use HTTP::Request::Common;
use LWP::UserAgent;

my $user           = 'your PayPal API username';
my $password       = 'your PayPal API password';
my $signature      = 'your PayPal API signature';
my $application_id = 'APP-80W284485P519543T'; # this is the sandbox app ID... so you would just change this to your own app-id when going live

my @currencies = qw/GBP EUR CHF USD AUD/; # Enter all the currency codes you want to convert here

my $url     = 'https://svcs.sandbox.paypal.com/AdaptivePayments/ConvertCurrency';  # remove the "sandbox." part of this URL, when its ready to go live...
my $ua      = LWP::UserAgent->new();
my $headers = HTTP::Headers->new(
        'X-PAYPAL-SECURITY-USERID'    => $user,
        'X-PAYPAL-SECURITY-PASSWORD'  => $password,
        'X-PAYPAL-SECURITY-SIGNATURE' => $signature,
        'X-PAYPAL-APPLICATION-ID'     => $application_id,
        'X-PAYPAL-DEVICE-IPADDRESS'   => $ENV{REMOTE_ADDR},
        'X-PAYPAL-REQUEST-DATA-FORMAT'   => 'JSON',
        'X-PAYPAL-RESPONSE-DATA-FORMAT'   => 'JSON'
        );


foreach (@currencies) {
  print qq|\nGetting exchange rates for $_.... \n|;
  my ($status,$vals) = get_converted_amounts($_);
  if ($vals->{error}) {
      print qq|There was an error: $vals->{error}\n|;
      exit;
  } else {
      print qq|Got conversion rates of:\n|;
      foreach (@currencies) {
        if ($vals->{$_}) {
            print qq|\t$_ => $vals->{$_}\n|;
        }
      }
  }
}


sub get_converted_amounts {

    my ($currency_from) = @_;

    my @currencies_to_grab;
    foreach (@currencies) {
      next if $_ eq $currency_from; # We dont wanna bother asking it to convert from this currency, into this currency =)
      push @currencies_to_grab, $_; 
    }

    my $json_var = {
          requestEnvelope => { 
            detailLevel => "ReturnAll",
            errorLanguage =>  "en_US",
          },
          baseAmountList => [{ 'currency' => { 'code' => $currency_from, 'amount' => 1 } }],
          convertToCurrencyList => [{ currencyCode => \@currencies_to_grab }]
    };

    use JSON;
    my $new_json = JSON::to_json($json_var);

    my $request  = HTTP::Request->new( 'POST', $url, $headers, $new_json );
    my $response = $ua->request( $request );

    my $json_returned = decode_json($response->decoded_content);

    if ($json_returned->{error}[0]) {
      return (0, { error => "There was an error: $json_returned->{error}[0]->{message} ($json_returned->{error}[0]->{errorId}) " });
    }

    my $vals;
    foreach (@{$json_returned->{estimatedAmountTable}->{currencyConversionList}[0]->{currencyList}->{currency}}) {
      $vals->{$_->{code}} = $_->{amount};
    }
    return (1,$vals);

}

Running it:

You would simply run it via SSH/Telnet, with:

perl /path/to/script/currency.cgi

You can play around with the currency codes (be sure to only use the currencyCode values found here: https://developer.paypal.com/docs/classic/api/adaptive-payments/ConvertCurrency_API_Operation/, as these are the only ones that are supported)

Although this converts from a given currency into the other related currencies (good if you want to run the script every couple of hours, and store the conversion rates) - it wouldn't be hard to tweak it so you can do:

convert(from_currency,to_currency,amount)

Hopefully this will save someone a bit of time (as I spent almost a day trying to get this going)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top