수색…


비고

이 예제는 노드 서버를 사용하여 안드로이드 기기에서 PayPal의 향후 지불 을 생성하는 실용적인 예를 보여줍니다.

Android 1 단계 : 레이아웃, 초기화 및 서버 응답 처리

이 애플리케이션 (Android + 노드 서버)의 전체 샘플 코드는 PayPal Developer Github 저장소 에서 사용할 수 있습니다.

애플리케이션의 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 에서 버튼에 대한 정의를 연관된 액션과 함께 추가합니다.이 버튼을 클릭하면 beginFuturePayment(...) 호출 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);
}

향후 지불을 요청하는 전화가 시작되면 Google 서버로 전송해야하는 정보가 제공됩니다. 향후 유효한 지불 요청 ( authCodemetadataId )에서이 정보를 추출한 다음 서버에 비동기 요청을 실행하여 향후 지불을 완료합니다 (2 단계에서 자세히 설명).

@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 단계 : 비동기 서버 요청

이 애플리케이션 (Android + 노드 서버)의 전체 샘플 코드는 PayPal Developer Github 저장소 에서 사용할 수 있습니다.

이 시점에서 PayPal의 미래 지급 버튼이 클릭되었고, 우리는 PayPal SDK의 인증 코드와 메타 데이터 ID를 가지고 있으며, 향후 지불 프로세스를 완료하기 위해이를 서버에 전달해야합니다.

아래 백그라운드 프로세스에서 우리는 몇 가지 작업을 수행하고 있습니다.

  • 서버가 http://10.0.2.2:3000/fpstore 인 URI를 설정합니다.이 호스트는 localhost에서 실행되는 서버의 /fpstore 엔드 포인트를 지정합니다.
  • 그런 다음 전송 될 JSON 객체가 설정되며 여기에는 인증 코드와 메타 데이터 ID가 포함됩니다.
  • 그러면 연결됩니다. 요청이 성공한 경우 (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);
    }
}

Android 3 단계 : 노드 토큰으로 액세스 토큰 및 프로세스 지불

이 애플리케이션 (Android + 노드 서버)의 전체 샘플 코드는 PayPal Developer Github 저장소 에서 사용할 수 있습니다.

2 단계에서 /fpstore 엔드 포인트의 서버에 인증 코드 및 메타 데이터 ID를 전달하는 비동기 요청이 이루어졌습니다. 요청을 완료하고 향후 지불을 처리하려면 토큰을 교환해야합니다.

먼저 구성 변수와 객체를 설정합니다.

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());

이제 Android 코드에서 /fpstore 엔드 포인트로 전송 된 POST 요청을 수신하는 Express 경로를 설정합니다.

우리는이 길에서 여러 가지 일을하고 있습니다.

  • POST 본문에서 인증 코드 및 메타 데이터 ID를 캡처합니다.
  • 그런 다음 generateToken() 요청하여 코드 객체를 전달합니다. 성공하면 결제를 생성하는 데 사용할 수있는 토큰을 얻습니다.
  • 다음으로 config 객체가 만들어 질 미래 지불을 위해 생성되고, payment.create(...) 대한 요청이 만들어지며, 미래의 지불 및 지불 설정 객체를 전달합니다. 이것은 미래의 지불을 만듭니다.
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