Passing Stripe tokens to server and handling on server

跟風遠走 提交于 2020-01-16 04:20:25

问题


I am merely trying to get the test working and cannot seem to do it any help would be greatly appreciated. I keep getting a stripe invalid request error. I tried multiple things but can not get it to work.

android code:

private void deposit() throws AuthenticationException {
    //bp.purchase("android.test.purchased");
    //bp.consumePurchase("android.test.purchased");

    Card card = new Card("4242-4242-4242-4242", 12, 2016, "123");

    if ( !card.validateCard() ) {
        // Show errors
        Toast.makeText(getApplicationContext(), "Incorrect card Information", Toast.LENGTH_SHORT).show();
    }
    else {
        Stripe stripe = new Stripe("pk_test_t9ODKMyhv3BwKiEHdQE0bmHi");
        stripe.createToken(
                card,
                new TokenCallback() {
                    public void onSuccess(Token token) {
                        // Send token to your server
                        String url = "/BettingXChange/charge.php";

                        //populate json object with user entered data
                        try {
                            chargeInfo.put("stripeToken", token);
                            Log.e("token", String.valueOf(token));
                            chargeInfo.put("user", savedUserID);

                        } catch (JSONException e) {
                            //Log the exception
                            Log.e("JSON Exception", e.toString());
                        }

                        //Set the response listener
                        Response.Listener responseListener = new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                //Handle the json response
                                try {
                                    //Assign member variables upon Json Response
                                    responseSuccess = response.getInt("success");
                                } catch (JSONException e) {
                                    //Log the exception
                                    Log.e("JSON Exception", e.toString());

                                }

                                //If charge successful, move to main app
                                if (responseSuccess == 1) {
                                    Toast.makeText(getApplicationContext(), "YAYY", Toast.LENGTH_SHORT).show();
                                }
                            }
                        };

                        //Set the error response listener
                        Response.ErrorListener responseErrorListener = new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                //Log the error
                                Log.e("Response Error", error.toString());

                                //Make a toast
                                Toast.makeText(getApplicationContext(),
                                        "sorry",
                                        Toast.LENGTH_SHORT).show();
                            }
                        };

                        //Use the request handler to send the Volley json POST request
                        requestHandler.post(url, chargeInfo, responseListener, responseErrorListener);
                    }

                    public void onError(Exception error) {
                        // Show localized error message
                    /*\
                    Toast.makeText(getContext(),
                            error.getLocalizedString(getContext()),
                            Toast.LENGTH_LONG
                    ).show();*/
                    }
                }
        );
    }
}

php code:

<?php
require_once("stripe-php-1.17.5/lib/Stripe.php");

mysql_connect("localhost","root","password");
mysql_select_db("testapp");


    $body = file_get_contents('php://input');
    $postvars = json_decode($body, true);
    $token = $postvars["stripeToken"];
    $user = $postvars["user"];

// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account
Stripe::setApiKey("sk_test_BrWE3ndM19knCYGAGj27Wix7");

// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = Stripe_Charge::create(array(
  "amount" => 1000, // amount in cents, again
  "currency" => "usd",
  "card" => $token,
  "description" => "payinguser@example.com")

);

  //add money to users account
  //get total money from people involved in bet
$sql = mysql_query("SELECT currency FROM `people` WHERE id = '".$user."'");

while($e=mysql_fetch_assoc($sql)){
        $output1[]=$e;
    }

$userAmount = $output1[0]['currency'];
$remainingUserBalance = (1000/100.0)+$userAmount;

$sql = "UPDATE `people` set currency = '".$remainingUserBalance."' WHERE id = '".$user."'";
if(mysql_query($sql)){

        $response["success"] = $token;
        echo $response;

}

} catch(Stripe_CardError $e) {
  // The card has been declined
    echo "carderror";
}
catch (Stripe_InvalidRequestError $e) {
    // You screwed up in your programming. Shouldn't happen!
    echo "uh oh";
} 
catch(Stripe_Error $e){
    //
    //echo "stripe error";
    //echo $e;
}

mysql_close();
?>

回答1:


Usually to run a network related process and or task on android, you have to perform the task on a separate thread; whether that may be a background thread a new thread all together. Conveniently, performing such a process asynchronously on a background thread in android isn't all that bad. (just extend AsyncTask and perform the operation in said extended class) If what you are trying to perform a task that seems to take longer than a few seconds of time, it is recommended that you look into using the java.util.concurrent package.

Link to android API information for AsyncTask class

Link to android API information for java.util.concurrent



来源:https://stackoverflow.com/questions/28058767/passing-stripe-tokens-to-server-and-handling-on-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!