支付寶簡單支付

首先導入架包java

而後自定義express

Base64類安全

private static final int BASELENGTH = 128;app

private static final int LOOKUPLENGTH = 64;dom

private static final int TWENTYFOURBITGROUP = 24;異步

private static final int EIGHTBIT = 8;ide

private static final int SIXTEENBIT = 16;測試

private static final int FOURBYTE = 4;ui

private static final int SIGN = -128;this

private static char PAD = '=';

private static byte[] base64Alphabet = new byte[BASELENGTH];

private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];

 

static {

for (int i = 0; i < BASELENGTH; ++i) {

base64Alphabet[i] = -1;

}

for (int i = 'Z'; i >= 'A'; i--) {

base64Alphabet[i] = (byte) (i - 'A');

}

for (int i = 'z'; i >= 'a'; i--) {

base64Alphabet[i] = (byte) (i - 'a' + 26);

}

 

for (int i = '9'; i >= '0'; i--) {

base64Alphabet[i] = (byte) (i - '0' + 52);

}

 

base64Alphabet['+'] = 62;

base64Alphabet['/'] = 63;

 

for (int i = 0; i <= 25; i++) {

lookUpBase64Alphabet[i] = (char) ('A' + i);

}

 

for (int i = 26, j = 0; i <= 51; i++, j++) {

lookUpBase64Alphabet[i] = (char) ('a' + j);

}

 

for (int i = 52, j = 0; i <= 61; i++, j++) {

lookUpBase64Alphabet[i] = (char) ('0' + j);

}

lookUpBase64Alphabet[62] = (char) '+';

lookUpBase64Alphabet[63] = (char) '/';

 

}

 

private static boolean isWhiteSpace(char octect) {

return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);

}

 

private static boolean isPad(char octect) {

return (octect == PAD);

}

 

private static boolean isData(char octect) {

return (octect < BASELENGTH && base64Alphabet[octect] != -1);

}

 

/**

 * Encodes hex octects into Base64

 *

 * @param binaryData

 *            Array containing binaryData

 * @return Encoded Base64 array

 */

public static String encode(byte[] binaryData) {

 

if (binaryData == null) {

return null;

}

 

int lengthDataBits = binaryData.length * EIGHTBIT;

if (lengthDataBits == 0) {

return "";

}

 

int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;

int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;

int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1

: numberTriplets;

char encodedData[] = null;

 

encodedData = new char[numberQuartet * 4];

 

byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

 

int encodedIndex = 0;

int dataIndex = 0;

 

for (int i = 0; i < numberTriplets; i++) {

b1 = binaryData[dataIndex++];

b2 = binaryData[dataIndex++];

b3 = binaryData[dataIndex++];

 

l = (byte) (b2 & 0x0f);

k = (byte) (b1 & 0x03);

 

byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)

: (byte) ((b1) >> 2 ^ 0xc0);

byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)

: (byte) ((b2) >> 4 ^ 0xf0);

byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)

: (byte) ((b3) >> 6 ^ 0xfc);

 

encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];

encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];

encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];

encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];

}

 

// form integral number of 6-bit groups

if (fewerThan24bits == EIGHTBIT) {

b1 = binaryData[dataIndex];

k = (byte) (b1 & 0x03);

 

byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)

: (byte) ((b1) >> 2 ^ 0xc0);

encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];

encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];

encodedData[encodedIndex++] = PAD;

encodedData[encodedIndex++] = PAD;

} else if (fewerThan24bits == SIXTEENBIT) {

b1 = binaryData[dataIndex];

b2 = binaryData[dataIndex + 1];

l = (byte) (b2 & 0x0f);

k = (byte) (b1 & 0x03);

 

byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)

: (byte) ((b1) >> 2 ^ 0xc0);

byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)

: (byte) ((b2) >> 4 ^ 0xf0);

 

encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];

encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];

encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];

encodedData[encodedIndex++] = PAD;

}

 

return new String(encodedData);

}

 

/**

 * Decodes Base64 data into octects

 *

 * @param encoded

 *            string containing Base64 data

 * @return Array containind decoded data.

 */

public static byte[] decode(String encoded) {

 

if (encoded == null) {

return null;

}

 

char[] base64Data = encoded.toCharArray();

// remove white spaces

int len = removeWhiteSpace(base64Data);

 

if (len % FOURBYTE != 0) {

return null;// should be divisible by four

}

 

int numberQuadruple = (len / FOURBYTE);

 

if (numberQuadruple == 0) {

return new byte[0];

}

 

byte decodedData[] = null;

byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;

char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

 

int i = 0;

int encodedIndex = 0;

int dataIndex = 0;

decodedData = new byte[(numberQuadruple) * 3];

 

for (; i < numberQuadruple - 1; i++) {

 

if (!isData((d1 = base64Data[dataIndex++]))

|| !isData((d2 = base64Data[dataIndex++]))

|| !isData((d3 = base64Data[dataIndex++]))

|| !isData((d4 = base64Data[dataIndex++]))) {

return null;

}// if found "no data" just return null

 

b1 = base64Alphabet[d1];

b2 = base64Alphabet[d2];

b3 = base64Alphabet[d3];

b4 = base64Alphabet[d4];

 

decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);

decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));

decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

}

 

if (!isData((d1 = base64Data[dataIndex++]))

|| !isData((d2 = base64Data[dataIndex++]))) {

return null;// if found "no data" just return null

}

 

b1 = base64Alphabet[d1];

b2 = base64Alphabet[d2];

 

d3 = base64Data[dataIndex++];

d4 = base64Data[dataIndex++];

if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters

if (isPad(d3) && isPad(d4)) {

if ((b2 & 0xf) != 0)// last 4 bits should be zero

{

return null;

}

byte[] tmp = new byte[i * 3 + 1];

System.arraycopy(decodedData, 0, tmp, 0, i * 3);

tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);

return tmp;

} else if (!isPad(d3) && isPad(d4)) {

b3 = base64Alphabet[d3];

if ((b3 & 0x3) != 0)// last 2 bits should be zero

{

return null;

}

byte[] tmp = new byte[i * 3 + 2];

System.arraycopy(decodedData, 0, tmp, 0, i * 3);

tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);

tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));

return tmp;

} else {

return null;

}

} else { // No PAD e.g 3cQl

b3 = base64Alphabet[d3];

b4 = base64Alphabet[d4];

decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);

decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));

decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

 

}

 

return decodedData;

}

 

/**

 * remove WhiteSpace from MIME containing encoded Base64 data.

 *

 * @param data

 *            the byte array of base64 data (with WS)

 * @return the new length

 */

private static int removeWhiteSpace(char[] data) {

if (data == null) {

return 0;

}

 

// count characters that's not whitespace

int newSize = 0;

int len = data.length;

for (int i = 0; i < len; i++) {

if (!isWhiteSpace(data[i])) {

data[newSize++] = data[i];

}

}

return newSize;

}

}

 

寫OrderUtils類

 public static final String APPID = "2016102802383554";

    /**

     * 商戶私鑰,pkcs8格式

     */

    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALbUGZlfrFiw1h35" +

            "2TF1tBgw9OuNPCK3172WS3kYTFb0CKqiYf6NVrZWHBWZM4IzvYsXqmKqqVyX5Qsd" +

            "nSejGh/rJLoDjXyuo5gQNPkj+mmfb4F1/A/hWrFNjsjHTfFDqkU3Z/ajO2YSpVRQ" +

            "lPqYCUccnerZqOedVOwNd9gzXqbFAgMBAAECgYEAiI5HSI1zNxNt+hnBpfWaPG9k" +

            "oANvpSbXlx2I5bvGWTQQvRJoSy7aU3pho6g4Fsn6isd0VhnOQgCZ7QGDfjWOrn+n" +

            "rXo2730axUZMRkzSBOkWB0iX1yfveKNN04s2GUCDkU5YIBpYMFfTDphZmgJeJ8zd" +

            "5yOey1hBZCjch1iM8YkCQQDvX5ywzwUndslAaBSuNbVNsZmmuAy74v+KSTvbW2c6" +

            "c+sCnz8G+1BrfGOhdGBUsrJGo9jbEXJh6ezwiwFOrPi/AkEAw4cKgcILsFUYsXA3" +

            "flVKIIuPrw31Ryz9EXcysPehcQUkATXh3WmVuzmEOyZSd9hFDgLAdBsuh6IzTipk" +

            "tcqdewJBAMtEweZSpenRMS0ENSuKaB9FxViRyh5ysNVZQv8PKyWz8ckUOY1QNAZS" +

            "Zrhf/r1t0X2y/R9qPVtwLchGAiIxODkCQAC1A0+20O4BUMaLflfhnRQDDTD33vQz" +

            "8HJYuQE01AuhliC+/iMb16PGsHi6ScAPMyi6z9Fbq85nwsG8m4KgyfMCQHv5kjsW" +

            "CL/Cd30MGr5BMbZOPJwG+SD9tT04STQt9cjz9Y2ltGyGMMiK87sLze7Ha65aUwDr" +

            "MRCqT2VCBalK0yo=";

 

    /**

     * 構造支付訂單參數列表

     *

     * @param app_id

     * @return

     */

    public static Map<String, String> buildOrderParamMap(String app_id) {

        Map<String, String> keyValues = new HashMap<String, String>();

 

        keyValues.put("app_id", app_id);

 

        keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"我是測試數據\",\"out_trade_no\":\"" + getOutTradeNo() + "\"}");

 

        keyValues.put("charset", "utf-8");

 

        keyValues.put("method", "alipay.trade.app.pay");

 

        keyValues.put("sign_type", "RSA");

 

//        keyValues.put("sign_type","RSA2");

 

        keyValues.put("timestamp", "2016-07-29 16:55:53");

 

        keyValues.put("version", "1.0");

 

        return keyValues;

    }

 

    /**

     * 要求外部訂單號必須惟一。

     *

     * @return

     */

    private static String getOutTradeNo() {

        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());

        Date date = new Date();

        String key = format.format(date);

 

        Random r = new Random();

        key = key + r.nextInt();

        key = key.substring(0, 15);

        return key;

    }

 

    /**

     * 構造支付訂單參數信息

     *

     * @param map 支付訂單參數

     * @return

     */

    public static String buildOrderParam(Map<String, String> map) {

        List<String> keys = new ArrayList<String>(map.keySet());

 

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < keys.size() - 1; i++) {

            String key = keys.get(i);

            String value = map.get(key);

            sb.append(buildKeyValue(key, value, true));

            sb.append("&");

        }

 

        String tailKey = keys.get(keys.size() - 1);

        String tailValue = map.get(tailKey);

        sb.append(buildKeyValue(tailKey, tailValue, true));

 

        return sb.toString();

    }

 

    /**

     * 拼接鍵值對

     *

     * @param key

     * @param value

     * @param isEncode

     * @return

     */

    private static String buildKeyValue(String key, String value, boolean isEncode) {

        StringBuilder sb = new StringBuilder();

        sb.append(key);

        sb.append("=");

        if (isEncode) {

            try {

                sb.append(URLEncoder.encode(value, "UTF-8"));

            } catch (UnsupportedEncodingException e) {

                sb.append(value);

            }

        } else {

            sb.append(value);

        }

        return sb.toString();

    }

 

    /**

     * 對支付參數信息進行簽名

     *

     * @param map 待簽名受權信息

     * @return

     */

    public static String getSign(Map<String, String> map, String rsaKey, boolean rsa2) {

        List<String> keys = new ArrayList<String>(map.keySet());

        // key排序

        Collections.sort(keys);

 

        StringBuilder authInfo = new StringBuilder();

        for (int i = 0; i < keys.size() - 1; i++) {

            String key = keys.get(i);

            String value = map.get(key);

            authInfo.append(buildKeyValue(key, value, false));

            authInfo.append("&");

        }

 

        String tailKey = keys.get(keys.size() - 1);

        String tailValue = map.get(tailKey);

        authInfo.append(buildKeyValue(tailKey, tailValue, false));

 

        String oriSign = SignUtils.sign(authInfo.toString(), rsaKey, rsa2);

        String encodedSign = "";

 

        try {

            encodedSign = URLEncoder.encode(oriSign, "UTF-8");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return "sign=" + encodedSign;

    }

}

 

PayResult類

private String resultStatus;

private String result;

private String memo;

 

public PayResult(Map<String, String> rawResult) {

if (rawResult == null) {

return;

}

 

for (String key : rawResult.keySet()) {

if (TextUtils.equals(key, "resultStatus")) {

resultStatus = rawResult.get(key);

} else if (TextUtils.equals(key, "result")) {

result = rawResult.get(key);

} else if (TextUtils.equals(key, "memo")) {

memo = rawResult.get(key);

}

}

}

 

@Override

public String toString() {

return "resultStatus={" + resultStatus + "};memo={" + memo

+ "};result={" + result + "}";

}

 

/**

 * @return the resultStatus

 */

public String getResultStatus() {

return resultStatus;

}

 

/**

 * @return the memo

 */

public String getMemo() {

return memo;

}

 

/**

 * @return the result

 */

public String getResult() {

return result;

}

}

 

SignUtils類

private static final String ALGORITHM = "RSA";

 

private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

 

private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";

 

private static final String DEFAULT_CHARSET = "UTF-8";

 

private static String getAlgorithms(boolean rsa2) {

return rsa2 ? SIGN_SHA256RSA_ALGORITHMS : SIGN_ALGORITHMS;

}

 

public static String sign(String content, String privateKey, boolean rsa2) {

try {

PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(

Base64.decode(privateKey));

KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);

PrivateKey priKey = keyf.generatePrivate(priPKCS8);

 

java.security.Signature signature = java.security.Signature

.getInstance(getAlgorithms(rsa2));

 

signature.initSign(priKey);

signature.update(content.getBytes(DEFAULT_CHARSET));

 

byte[] signed = signature.sign();

 

return Base64.encode(signed);

} catch (Exception e) {

e.printStackTrace();

}

 

return null;

}

 

}

 

 MainActivity類

 

public class MainActivity extends AppCompatActivity {

 

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        final String orderInfo = getorderInfo();   // 訂單信息

        final Runnable payRunnable = new Runnable() {

 

            @Override

            public void run() {

                PayTask alipay = new PayTask(MainActivity.this);

                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();

                msg.obj = result;

                handler.sendMessage(msg);

            }

        };

 

 

        TextView pay=findViewById(R.id.pay);

        pay.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Thread thread=new Thread(payRunnable);

                thread.start();

            }

        });

 

 

    }

 

    public Handler handler = new Handler() {

        @Override

        public void handleMessage(Message msg) {

            super.handleMessage(msg);

            PayResult payResult = new PayResult((Map<String, String>) msg.obj);

 

            /**

             對於支付結果,請商戶依賴服務端的異步通知結果。同步通知結果,僅做爲支付結束的通知。

             */

            String resultInfo = payResult.getResult();// 同步返回須要驗證的信息

            String resultStatus = payResult.getResultStatus();

            // 判斷resultStatus 爲9000則表明支付成功

            if (TextUtils.equals(resultStatus, "9000")) {

                // TODO 該筆訂單是否真實支付成功,須要依賴服務端的異步通知。

                Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

            } else {

                //TODO  該筆訂單真實的支付結果,須要依賴服務端的異步通知。

                Toast.makeText(MainActivity.this, "支付失敗", Toast.LENGTH_SHORT).show();

            }

        }

    };

 

 

    /**

     * 記得要看

     * 這裏只是爲了方便直接向商戶展現支付寶的整個支付流程;因此Demo中加簽過程直接放在客戶端完成;

     * 真實App裏,privateKey等數據嚴禁放在客戶端,加簽過程務必要放在服務端完成;

     * 防止商戶私密數據泄露,形成沒必要要的資金損失,及面臨各類安全風險;

     * <p>

     * orderInfo的獲取必須來自服務端;

     */

    public String getorderInfo() {

        Map<String, String> params = OrderUtils.buildOrderParamMap(OrderUtils.APPID);

        String orderParam = OrderUtils.buildOrderParam(params);

        String sign = OrderUtils.getSign(params, OrderUtils.RSA_PRIVATE, false);

        final String orderInfo = orderParam + "&" + sign;

        return orderInfo;

    }

 

 

 

}

相關文章
相關標籤/搜索