PayPal APIでHello World!10分で作るnode.js寄付サイト

PayPalは専用のボタンを埋め込む事で簡単にオンライン決済ができますが、専用のRESTAPIを使う事で、より細かい決済をWebサイトで実現する事が出来ます。

ここではnode.js(CoffeeScript)でPayPal決済を動作させる為の最低限のコードを紹介します。

アプリケーションの登録

  1. https://developer.paypal.com のDashboardのMyAppsからテスト用のアプリケーションを作ります。
  2. 作ったアプリの名前を開いてClient IDとSecretを控えておきます。

起動方法

  1. node.jsをインストールします。
  2. 下のほうのソースをapp.coffeeの名前で保存します。
  3. CLIENTIDとCLIENTSECRETの部分を先ほど取得したクライアントIDとシークレットに変更します。
  4. 必要なモジュールをインストールしてアプリケーションを起動します。
>npm install -g coffee-script
>npm install express async paypal-rest-sdk
>./app.coffee

支払い方法

  1. https://developer.paypal.com のdashboardのSandBox、Accountsでテスト用アカウントを作ります。
  2. http://localhost:8080 にアクセスしてOKey!を押すとPayPalに飛ぶので上記アカウントで支払いができます。
#!/usr/bin/env coffee

Http=require 'http'
Express=require 'express'
Async=require 'async'
Paypal=require 'paypal-rest-sdk'

Paypal.configure
    mode:'sandbox'
    client_id:'CLIENTID'
    client_secret:'CLIENTSECRET'

ap=Express()

ap.get '/',(q,s)->
    s.send "<html><body><p>Hello world. Give me a doller.</p> <a href='/pay'>Okey!</a></body></html>"

ap.get '/callback',(q,s)->
    paymentId=q.query['paymentId']
    payerId=q.query['PayerID']
    data=
        payer_id:payerId
    Paypal.payment.execute paymentId,data,(e,payment)->
        if e
            console.error e
            s.redirect '/'
        else
            console.log payment
            s.send 'Thank you '+payment.payer.payer_info.first_name+'!'

ap.get '/pay',(q,s)->
    order=
        intent:'sale'
        payer:
            payment_method:'paypal'
        redirect_urls:
            return_url:'http://localhost:8080/callback'
            cancel_url:'http://localhost:8080/callback'
        transactions:[
            item_list:
                items:[
                    quantity:'1'
                    name:"Donate"
                    price:'1.00'
                    currency:'USD'
                ]
            amount:
                currency:'USD'
                total:'1.00'
            description:
                'Give me a doller!'
        ]
    Paypal.payment.create order,(e,payment)->
        if e
            console.error e
            s.redirect '/'
        else
            console.log payment
            url=payment.links.filter (x)->x.rel=='approval_url'
            console.log url

            s.redirect url[0].href

Http.createServer(ap).listen(8080)

この記事を見た人がよく読んでいる記事

トップページ

節約テクノロジ > PayPal APIでHello World!10分で作るnode.js寄付サイト