There is code in the beanstream and paymentech addon modules that does that sort of thing. Perhaps you can find inspiration from that to suit your needs with your own site.