खोज…


टिप्पणियों

यह उदाहरण एक नोड डिवाइस का उपयोग करके एंड्रॉइड डिवाइस से पेपल भविष्य के भुगतान का उदाहरण देने के लिए एक व्यावहारिक अंत दिखाता है।

Android चरण 1: लेआउट, इनिशियलाइज़ेशन और हैंडलिंग सर्वर रिस्पांस

इस एप्लिकेशन (Android + नोड सर्वर) के लिए पूरा नमूना कोड पेपल डेवलपर जीथब रिपॉजिटरी में उपलब्ध है

हमारे एप्लिकेशन का एंड्रॉइड भाग बनाने का पहला चरण एक बुनियादी लेआउट सेट करना है और उन प्रतिक्रियाओं को संभालना है जो उस सर्वर से वापस आते हैं जिसे हम नोड में सेट करेंगे।

अपनी एप्लिकेशन जानकारी को घर पर एक नया PayPalConfiguration ऑब्जेक्ट बनाकर प्रारंभ करें।

private static PayPalConfiguration config = new PayPalConfiguration()
        .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
        .clientId("YOUR APPLICATION CLIENT ID")
        .merchantName("My Store")
        .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
        .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));

इसके बाद, हम अपने भुगतान दीक्षा के रूप में कार्य करने के लिए onCreate(...) एक साधारण बटन जोड़ते हैं। यह केवल कार्रवाई को ट्रिगर करने के लिए है, और एक उपयोगकर्ता के लिए भविष्य के भुगतान के लिए दीक्षा प्रक्रिया के रूप में रखा जाना चाहिए (जैसे जब वे किसी सदस्यता पर सहमत होते हैं)।

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button button = (Button) findViewById(R.id.paypal_button);
}

res > layout > activity_main.xml तहत res > layout > activity_main.xml हम इसकी संबंधित कार्रवाई के साथ बटन के लिए परिभाषा जोड़ते हैं, जब इसे क्लिक किया जाता है तो beginFuturePayment(...) कहता है, जिसे हम एक मिनट में परिभाषित करेंगे।

<Button android:id="@+id/paypal_button"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/paypal_button"
    android:onClick="beginFuturePayment" />

res > values > strings.xml तहत हम फिर बटन के लिए एक स्ट्रिंग संदर्भ जोड़ते हैं।

<string name="paypal_button">Process Future Payment</string>

अब हम बटन हैंडलर को जोड़ते हैं, जब उपयोगकर्ता बटन पर क्लिक करता है तो भविष्य की भुगतान प्रक्रिया शुरू करने के लिए कॉल आरंभ करने के लिए। हम यहां क्या कर रहे हैं, इस उदाहरण के शीर्ष पर स्थापित कॉन्फ़िगरेशन ऑब्जेक्ट के साथ भुगतान सेवा शुरू कर रहा है।

public void beginFuturePayment(View view){
    Intent serviceConfig = new Intent(this, PayPalService.class);
    serviceConfig.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
    startService(serviceConfig);

    Intent intent = new Intent(this, PayPalFuturePaymentActivity.class);
    intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
    startActivityForResult(intent, 0);
}

जब भविष्य में भुगतान करने के लिए कॉल किया जाता है, तो हमें कुछ जानकारी दी जाएगी, जिसे हमारे सर्वर पर भेजना होगा। हम इस जानकारी को मान्य भविष्य भुगतान अनुरोध ( authCode और metadataId ) से authCode , फिर भविष्य में भुगतान (चरण 2 में विस्तृत) के लिए सर्वर पर authCode अनुरोध को निष्पादित करें।

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data){
    if (resultCode == Activity.RESULT_OK){
        PayPalAuthorization auth = data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
        if (auth != null){
            try{
                //prepare params to be sent to server
                String authCode = auth.getAuthorizationCode();
                String metadataId = PayPalConfiguration.getClientMetadataId(this);
                String [] params = {authCode, metadataId};

                //process async server request for token + payment
                ServerRequest req = new ServerRequest();
                req.execute(params);

            } catch (JSONException e) {
                Log.e("FPSample", "JSON Exception: ", e);
            }
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        Log.i("FPSample", "User canceled.");
    } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
        Log.i("FPSample", "Invalid configuration");
    }
}

अंत में, हम अपने onDestroy() को परिभाषित करते हैं।

@Override
public void onDestroy(){
    stopService(new Intent(this, PayPalService.class));
    super.onDestroy();
}

Android चरण 2: Async सर्वर अनुरोध

इस एप्लिकेशन (Android + नोड सर्वर) के लिए पूरा नमूना कोड पेपल डेवलपर जीथब रिपॉजिटरी में उपलब्ध है

इस बिंदु पर पेपल भविष्य के भुगतान बटन पर क्लिक किया गया है, हमारे पास पेपल एसडीके से एक कोड और मेटाडेटा आईडी है, और हमें भविष्य की भुगतान प्रक्रिया को पूरा करने के लिए अपने सर्वर पर पास करना होगा।

नीचे की पृष्ठभूमि प्रक्रिया में, हम कुछ चीजें कर रहे हैं:

  • हम यूआरआई की स्थापना की है कि हमारे सर्वर होने के लिए http://10.0.2.2:3000/fpstore , जो मार रहा है /fpstore हमारे सर्वर स्थानीय होस्ट पर चल रहा है के अंतिम बिंदु।
  • JSON ऑब्जेक्ट को इसके माध्यम से भेजा जाएगा, फिर सेट किया गया है, जिसमें ऑर्टिकल कोड और मेटाडेटा आईडी है।
  • फिर कनेक्शन किया जाता है। एक सफल अनुरोध (200/201 रेंज) के मामले में हम सर्वर से प्रतिक्रिया की उम्मीद कर सकते हैं। हम उस प्रतिक्रिया को पढ़ते हैं और फिर उसे वापस करते हैं।
  • अंत में, हमारे पास एक onPostExecute(...) विधि है जो सर्वर स्ट्रिंग को लौटाने के लिए सेट है। इस उदाहरण के मामले में, यह बस लॉग इन है।
public class ServerRequest extends AsyncTask<String, Void, String> {
    protected String doInBackground(String[] params){
        HttpURLConnection connection = null;
        try{
            //set connection to connect to /fpstore on localhost
            URL u = new URL("http://10.0.2.2:3000/fpstore");
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("POST");

            //set configuration details
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setAllowUserInteraction(false);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            //set server post data needed for obtaining access token
            String json = "{\"code\": \"" + params[0] + "\", \"metadataId\": \"" + params[1] + "\"}";
            Log.i("JSON string", json);

            //set content length and config details
            connection.setRequestProperty("Content-length", json.getBytes().length + "");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            //send json as request body
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(json.getBytes("UTF-8"));
            outputStream.close();

            //connect to server
            connection.connect();

            //look for 200/201 status code for received data from server
            int status = connection.getResponseCode();
            switch (status){
                case 200:
                case 201:
                    //read in results sent from the server
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null){
                        sb.append(line + "\n");
                    }
                    bufferedReader.close();

                    //return received string
                    return sb.toString();
            }

        } catch (MalformedURLException ex) {
            Log.e("HTTP Client Error", ex.toString());
        } catch (IOException ex) {
            Log.e("HTTP Client Error", ex.toString());
        } catch (Exception ex) {
            Log.e("HTTP Client Error", ex.toString());
        } finally {
            if (connection != null) {
                try{
                    connection.disconnect();
                } catch (Exception ex) {
                    Log.e("HTTP Client Error", ex.toString());
                }
            }
        }
        return null;
    }

    protected void onPostExecute(String message){
        //log values sent from the server - processed payment
        Log.i("HTTP Client", "Received Return: " + message);
    }
}

एंड्रॉइड स्टेप 3: एक्सेस टोकन और प्रोसेस भुगतान प्राप्त करने के लिए नोड सर्वर

इस एप्लिकेशन (Android + नोड सर्वर) के लिए पूरा नमूना कोड पेपल डेवलपर जीथब रिपॉजिटरी में उपलब्ध है

चरण 2 से, हमारे सर्वर पर /fpstore एंडपॉइंट पर, /fpstore कोड और मेटाडेटा आईडी के साथ एक async अनुरोध किया गया है। अब हमें अनुरोध को पूरा करने और भविष्य के भुगतान को संसाधित करने के लिए एक टोकन के लिए विनिमय करने की आवश्यकता है।

पहले हम अपने कॉन्फ़िगरेशन चर और ऑब्जेक्ट सेट करते हैं।

var bodyParser = require('body-parser'),
    http = require('http'),
    paypal = require('paypal-rest-sdk'),
    app = require('express')();

var client_id = 'YOUR APPLICATION CLIENT ID';
var secret = 'YOUR APPLICATION SECRET';

paypal.configure({
    'mode': 'sandbox',
    'client_id': client_id,
    'client_secret': secret
});

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());

अब हम एक एक्सप्रेस मार्ग स्थापित करते हैं जो हमारे एंड्रॉइड कोड से /fpstore समापन बिंदु पर भेजे गए POST अनुरोधों को /fpstore

हम इस मार्ग में कई काम कर रहे हैं:

  • हम POST बॉडी से कई कोड और मेटाडेटा आईडी कैप्चर करते हैं।
  • फिर हम कोड ऑब्जेक्ट से गुजरते हुए generateToken() बनाने का अनुरोध करते generateToken() । सफल होने पर, हम एक टोकन प्राप्त करते हैं जिसका उपयोग भुगतान बनाने के लिए किया जा सकता है।
  • इसके बाद, config वस्तुओं भविष्य भुगतान है कि किए जाने के लिए, और के लिए एक अनुरोध के लिए बनाई गई हैं payment.create(...) , किया जाता है भविष्य भुगतान और भुगतान config वस्तुओं के साथ गुजर। इससे भविष्य का भुगतान होता है।
app.post('/fpstore', function(req, res){
    var code = {'authorization_code': req.body.code};
    var metadata_id = req.body.metadataId;
    
    //generate token from provided code
    paypal.generateToken(code, function (error, refresh_token) {
        if (error) {
            console.log(error);
            console.log(error.response);
        } else {
            //create future payments config 
            var fp_config = {'client_metadata_id': metadata_id, 'refresh_token': refresh_token};

            //payment details
            var payment_config = {
                "intent": "sale",
                "payer": {
                    "payment_method": "paypal"
                },
                "transactions": [{
                    "amount": {
                        "currency": "USD",
                        "total": "3.50"
                    },
                    "description": "Mesozoic era monster toy"
                }]
            };

            //process future payment
            paypal.payment.create(payment_config, fp_config, function (error, payment) {
                if (error) {
                    console.log(error.response);
                    throw error;
                } else {
                    console.log("Create Payment Response");
                    console.log(payment);
                    
                    //send payment object back to mobile
                    res.send(JSON.stringify(payment));
                }
            });
        }
    });
});

अंत में, हम पोर्ट 3000 पर सुनने के लिए सर्वर बनाते हैं।

//create server
http.createServer(app).listen(3000, function () {
   console.log('Server started: Listening on port 3000');
});


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow