您好,登錄后才能下訂單哦!
本篇文章為大家展示了Android中怎么接入支付寶實現支付功能,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
1.登錄官網
他的官網就是螞蟻金服的開放平臺了,我們可以訪問 螞蟻金服開放平臺 ,并且注冊賬號進行登錄
創建應用
如果你是現有的應用直接接入支付功能的話,可以不看這里,我這里是因為需要講博客所有重新創建了一個項目并且在Android Studio里也重新創建了一個項目,Android Studio里創建的項目我把他叫做SimpleMall,簡單商城的意思,那在開放平臺我們又是如何去創建應用呢,點擊-進入我的開放平臺-應用,就可以看到應用管理了。我們點擊創建應用
創建成果之后有很多的選項包括需要你上傳
這些先不管,我們這個時候可以看到已經拿到了APPID: 2017062807585767,這樣我們就可以繼續下一步的準備了
3.簽約
大部分的功能需要簽約才能使用,很遺憾,我這個個體戶就不行了
4.配置密鑰
配置秘鑰是支付這一環節很重要的因素,也是分了兩個步驟,生成秘鑰和配置秘鑰,這里使用的RAS非對稱加密
https://docs.open.alipay.com/291/105971
我們按照文檔上來,首先是下載工具了,這里有win和mac兩個地址,我是win,下載下來是這個樣子的
我們按照圖中的配置拿到了公鑰和私鑰
那我們可以配置了,我們找到項目詳情
然后這里是兩種方式,我們選擇的是RSA方式么其實哪種方式都是可以的
到這里,這個也配置好了
5.SDK 下載
到這里,我們就可以直接去下載他的SDK了SDK下載地址
這個壓縮包下載下來什么都有,要找到Android的部分
二.SDK集成
我們現在就開始來把jar集成進去,支付寶給我們提供的就是一個jar,我們放進我們的工程里面去
并且在我們的app/build.gradle里配置一下
compile files('libs/alipaySdk-20170623-proguard.jar')
這樣Jar就集成好了,然后配置一下清單文件
<activity android:name="com.alipay.sdk.app.H5PayActivity" android:configChanges="orientation|keyboardHidden|navigation" android:exported="false" android:screenOrientation="behind"/> <activity android:name="com.alipay.sdk.auth.AuthActivity" android:configChanges="orientation|keyboardHidden|navigation" android:exported="false" android:screenOrientation="behind"/>
并且添加權限
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如大于等于Android6.0,還需要動態申請下權限
如果你的項目需要混淆,需要添加混淆規則
-libraryjars libs/alipaySDK-20150602.jar -keep class com.alipay.android.app.IAlixPay{*;} -keep class com.alipay.android.app.IAlixPay$Stub{*;} -keep class com.alipay.android.app.IRemoteServiceCallback{*;} -keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;} -keep class com.alipay.sdk.app.PayTask{ public *;} -keep class com.alipay.sdk.app.AuthTask{ public *;}
嗯,可以說得上是比較簡單的,我們繼續
三.支付接口調用
其實支付寶的調用還是比較簡單的,我們來看一下我的調用方式
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btnPay; private static final int SDK_PAY_FLAG = 1001; private String RSA_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCNYm+oveZOECAjwrH1E+RHznGxVqdAKI/teijarKYIV7RjpNyfMaEaI0ms8vd9aXtN6gEeSPvBQmWVunY1FWfLpAOkSYGJLJ8GJEgiNTAstCgkHw21DaojrD9LxoUZbvfBwWXiDLDAPUGiU6pnG7AkClJuzSETMCTWsrcB35Y9MMprnPaXgNG8+MJ6P2Z1xmN51uNQw4Z99iDrR27lrQH/OXNzLnRDzlj0rwoYFHDSPds58qmjVRTcBXCVpZoLmuf4OfSc8gplNGz/qs/rjOfKEOrcZQeKw1SCkG5U4ZHsMM5XmwbCGg20G9+BokYdHJNKFKu/+kwu69No1Mcy8RTfAgMBAAECggEAIXBCkFo5egT+VPbbN+d4ejMtWI/yBo6RW80klHN44Ug89cQsGcqXG6N07V6ZgiPMceUCVrNUN6UIeZ0cD/n8DoHACr8Hz/Wptr4mAVErD6ecRs7BYyzULJO0dKuDFzzThBPFkO0HcLAMMeQvzSsTQbLfRC1nwS4FyHGELwE+e0IQy3wug7jAid/X2crGC438pwxS7iCjZxsO44WCteCLTjIG/y2AR42wJXSRlPpsGQP6CVgUKa1ATEsoGBDoImDAitnPAyADyOvRMf3jqOcadWq8MtXKPM1KyfM1Sq+NgPawwXxdBHPXB4aDPHmoZm3qb8Nat1VkbTfnmnFNVNiGAQKBgQDGcR0xEI/oP/HRdhKQJCNguUN2dcXIfbfLj4ff9yMtQ+086W3BpJYO5rq6B8mXU66wg3crKJHwpaQ5a6CXb1U757y2J2qPccKdy3ZXed7z0bEkGxwPzwkAiNXM30KvHO9QxVFX3oILDca2qOk7h6vRrRCH9GHdZkYgf7F0WRFwnwKBgQC2ZKYOVPE881ek0SFHURuTN99M+MsciyLzJNeRpopXCBvViRV3rMvyzCRsciJEqQmZnQM7VDkqh4MtutEDnPv2Qux3Qlhk756Q8PdmS9hPl9WK8NGSSA6AQFGqrV16ngjYRm1h+fm6c6K9YFaoJXw/5qYF48X0hXRE39++TXSzwQKBgBnji/Fovb2JCh2PkCBp9ouZ3+lGeCUt8ZqHAS0A6v/uyraVpZILzN/ozheTCIPLkRDKNfPVeSSyF3i+R9c52R7VntMM1WQdbUx0zN2gsquQgdG6D7EoS35cW7g8sFB0L+yTsYcLKmASzgfqhXMUwAlc0LlL8rCVtTRsNFR/gjz1AoGAUiANmSRsHvqe+wpjRp5hoS8mL51Srz6C9SIgomdvoPJ4vfRkoyc+Ccwblmzpuyq1tOI640rwFpM4rF2S4WKdHOxTVvubm489QZwOeZQrCOOf9liqtIgXZ24Ol6BKF/zylJdZhyUsaeTJYSXwvvNp98fd94bwykIQ8TYwo5pyssECgYAZC+l1Ok0VJyisBLgOHoAuwYmWbFRC0RJAwQQoTs4/ozHiR+kFOgiHY6W7sjfgdMej+0U0gNifm2nn0lj1KRuOXiAzkzRBTkiwDChP0PAa2ns9GSbxApRVPJJzeM2NlRX4ptscjKUqWB3tgqPNWDTjW0d7iCYeFWkx0GfRgSwHaQ=="; public static final String APPID = "2017062807585767"; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SDK_PAY_FLAG: PayResult payResult = new PayResult((Map<String, String>) msg.obj); //同步獲取結果 String resultInfo = payResult.getResult(); Log.i("Pay", "Pay:" + resultInfo); String resultStatus = payResult.getResultStatus(); // 判斷resultStatus 為9000則代表支付成功 if (TextUtils.equals(resultStatus, "9000")) { Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "支付失敗", Toast.LENGTH_SHORT).show(); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { btnPay = (Button) findViewById(R.id.btnPay); btnPay.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnPay: //秘鑰驗證的類型 true:RSA2 false:RSA boolean rsa = false; //構造支付訂單參數列表 Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa); //構造支付訂單參數信息 String orderParam = OrderInfoUtil2_0.buildOrderParam(params); //對支付參數信息進行簽名 String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE, rsa); //訂單信息 final String orderInfo = orderParam + "&" + sign; //異步處理 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.what = SDK_PAY_FLAG; msg.obj = result; mHandler.sendMessage(msg); } }; // 必須異步調用 Thread payThread = new Thread(payRunnable); payThread.start(); break; } } }
可以看到我們并沒有多少代碼,調用起來
但是還是提示有錯誤,我們來看一下他的返回值
復制代碼 代碼如下:
{"alipay_trade_app_pay_response":{"code":"40006","msg":"Insufficient Permissions","sub_code":"isv.insufficient-isv-permissions","sub_msg":"ISV權限不足"}}
這是因為我們這個應用并沒有去簽約功能,所有并沒有這個權限,好的,但是起碼可以看出我們已經可以調用支持包的支付了,那我們繼續來了解他的功能吧
四.Api
首先我們看下他提供的OrderInfoUtil2_0這個工具類
public class OrderInfoUtil2_0 { /** * 構造授權參數列表 * * @param pid * @param app_id * @param target_id * @return */ public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id, boolean rsa2) { Map<String, String> keyValues = new HashMap<String, String>(); // 商戶簽約拿到的app_id,如:2013081700024223 keyValues.put("app_id", app_id); // 商戶簽約拿到的pid,如:2088102123816631 keyValues.put("pid", pid); // 服務接口名稱, 固定值 keyValues.put("apiname", "com.alipay.account.auth"); // 商戶類型標識, 固定值 keyValues.put("app_name", "mc"); // 業務類型, 固定值 keyValues.put("biz_type", "openservice"); // 產品碼, 固定值 keyValues.put("product_id", "APP_FAST_LOGIN"); // 授權范圍, 固定值 keyValues.put("scope", "kuaijie"); // 商戶唯一標識,如:kkkkk091125 keyValues.put("target_id", target_id); // 授權類型, 固定值 keyValues.put("auth_type", "AUTHACCOUNT"); // 簽名類型 keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA"); return keyValues; } /** * 構造支付訂單參數列表 * @param app_id * @return */ public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2) { 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", rsa2 ? "RSA2" : "RSA"); keyValues.put("timestamp", "2016-07-29 16:55:53"); keyValues.put("version", "1.0"); return keyValues; } /** * 構造支付訂單參數信息 * * @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; } /** * 要求外部訂單號必須唯一。 * @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 app_id * @return */ public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2) { 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", rsa2 ? "RSA2" : "RSA"); keyValues.put("timestamp", "2016-07-29 16:55:53"); keyValues.put("version", "1.0"); return keyValues; }
這個方法我們來解讀一下吧,他其實就是構建一個Map的鍵值對,都有哪些內容呢
app_id(key)
biz_content(內容)
charset(編碼)
method(方法)
sign_type(簽名類型)
timestamp(時間戳)
version(版本)
這個demo里面可能都是寫死了,但是如果我們真的要在實際應用中開發支付的話,這里要填寫正確,我們主要關心的有方法和簽名類型還有版本這三個
方法有幾個類型,要注意一下
其次就是簽名方式了,有兩種,RSA和RSA2
最后就是版本,版本可以通過PayTask去獲取
//獲取版本 private String getPlayVersion(PayTask payTask){ return payTask.getVersion(); }
而關于biz_content,就需要你們自己去定義了,我們來看下全部的參數說明
當我們拿到map之后就可以轉換成一個string作為請求信息了,可以看到我們使用的是這個方法
/** * 構造支付訂單參數信息 * * @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 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; }
這里的加密主要還是用到了SignUtils
public class 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; } }
而SignUtils則啟動了Base64
public final class Base64 { private static final int BASELENGTH = 128; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; private static final int FOURBYTE = 4; private static final int SIGN = -128; 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; } }
這些你都可以在我寫的demo里獲取到的,我們繼續分析就是了,當加密成功之后他會返回一個sign的字符串給我,這就是加密信息,然后通過 訂單信息 & 加密訂單這種公式就拼接出商品信息
//訂單信息 String orderInfo = orderParam + "&" + sign;
好的,我們的下單需要在異步中操作,也就是我們所見到的Runnable
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.what = SDK_PAY_FLAG; msg.obj = result; mHandler.sendMessage(msg); } };
在這里他同樣的是構建一個PayTask 區調用payV2,里面的參數就是訂單信息和一個boolean值,具體參數可以參考
好的,當我們拿到結果后通過Handler回到UI線程
PayResult payResult = new PayResult((Map<String, String>) msg.obj); //同步獲取結果 String resultInfo = payResult.getResult(); Log.i("Pay", "Pay:" + resultInfo); String resultStatus = payResult.getResultStatus(); // 判斷resultStatus 為9000則代表支付成功 if (TextUtils.equals(resultStatus, "9000")) { Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "支付失敗", Toast.LENGTH_SHORT).show(); }
這里其實PayResult只是把結果幾個關鍵信息提取出來了
public class 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; } }
我們如果想看詳細的結果,可以打印resultInfo,好的,關于返回參數,可以參考App支付同步通知參數說明
上述內容就是Android中怎么接入支付寶實現支付功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。