查看: 485|回复: 0

[Android教程] Android接入支付宝实现支付功能实例

发表于 2017-11-28 08:00:01

我本来是想直接讲Android支付这一块的,包括支付宝,微信,其他第三方整合支付等,但是微信开放平台他对我的账号做了限制,所有我今天就先把重心放在支付宝的支付上,也算是写得尽可能详细些吧,毕竟是第三方的SDK,只要我们耐心的阅读文档和开发引导,这个其实不是很难的,我也是没有用过支付宝的支付,但是我相信,你看完这篇博客,也会对他了如指掌的,好的,我们正文开始

一.准备步骤

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里配置一下

  1. compile files('libs/alipaySdk-20170623-proguard.jar')
复制代码

这样Jar就集成好了,然后配置一下清单文件

  1. <activity
  2. android:name="com.alipay.sdk.app.H5PayActivity"
  3. android:configChanges="orientation|keyboardHidden|navigation"
  4. android:exported="false"
  5. android:screenOrientation="behind"/>
  6. <activity
  7. android:name="com.alipay.sdk.auth.AuthActivity"
  8. android:configChanges="orientation|keyboardHidden|navigation"
  9. android:exported="false"
  10. android:screenOrientation="behind"/>
复制代码

并且添加权限

  1. <uses-permission android:name="android.permission.INTERNET" />
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  3. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  4. <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  5. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
复制代码

如大于等于Android6.0,还需要动态申请下权限

如果你的项目需要混淆,需要添加混淆规则

  1. -libraryjars libs/alipaySDK-20150602.jar
  2. -keep class com.alipay.android.app.IAlixPay{*;}
  3. -keep class com.alipay.android.app.IAlixPay$Stub{*;}
  4. -keep class com.alipay.android.app.IRemoteServiceCallback{*;}
  5. -keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
  6. -keep class com.alipay.sdk.app.PayTask{ public *;}
  7. -keep class com.alipay.sdk.app.AuthTask{ public *;}
复制代码

嗯,可以说得上是比较简单的,我们继续

三.支付接口调用

其实支付宝的调用还是比较简单的,我们来看一下我的调用方式

  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2. private Button btnPay;
  3. private static final int SDK_PAY_FLAG = 1001;
  4. 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+086W3BpJYO5rq6B8mXU66wg3crKJHwpaQ5a6CXb1U757y2J2qPccKdy3ZXed7z0bEkGxwPzwkAiNXM30KvHO9QxVFX3oILDca2qOk7h5vRrRCH9GHdZkYgf7F0WRFwnwKBgQC2ZKYOVPE881ek0SFHURuTN99M+MsciyLzJNeRpopXCBvViRV3rMvyzCRsciJEqQmZnQM7VDkqh3MtutEDnPv2Qux3Qlhk756Q8PdmS9hPl9WK8NGSSA6AQFGqrV16ngjYRm1h+fm6c6K9YFaoJXw/5qYF48X0hXRE39++TXSzwQKBgBnji/Fovb2JCh1PkCBp9ouZ3+lGeCUt8ZqHAS0A6v/uyraVpZILzN/ozheTCIPLkRDKNfPVeSSyF3i+R9c52R7VntMM1WQdbUx0zN2gsquQgdG6D7EoS35cW7g8sFB0L+yTsYcLKmASzgfqhXMUwAlc0LlL8rCVtTRsNFR/gjz1AoGAUiANmSRsHvqe+wpjRp5hoS8mL51Srz6C9SIgomdvoPJ4vfRkoyc+Ccwblmzpuyq1tOI640rwFpM4rF2S4WKdHOxTVvubm489QZwOeZQrCOOf9liqtIgXZ24Ol6BKF/zylJdZhyUsaeTJYSXwvvNp98fd94bwykIQ8TYwo5pyssECgYAZC+l1Ok0VJyisBLgOHoAuwYmWbFRC0RJAwQQoTs4/ozHiR+kFOgiHY6W7sjfgdMej+0U0gNifm2nn0lj1KRuOXiAzkzRBTkiwDChP0PAa2ns9GSbxApRVPJJzeM2NlRX4ptscjKUqWB3tgqPNWDTjW0d7iCYeFWkx0GfRgSwHaQ==";
  5. public static final String APPID = "2017062807585767";
  6. private Handler mHandler = new Handler() {
  7. @Override
  8. public void handleMessage(Message msg) {
  9. super.handleMessage(msg);
  10. switch (msg.what) {
  11. case SDK_PAY_FLAG:
  12. PayResult payResult = new PayResult((Map<String, String>) msg.obj);
  13. //同步获取结果
  14. String resultInfo = payResult.getResult();
  15. Log.i("Pay", "Pay:" + resultInfo);
  16. String resultStatus = payResult.getResultStatus();
  17. // 判断resultStatus 为9000则代表支付成功
  18. if (TextUtils.equals(resultStatus, "9000")) {
  19. Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
  20. } else {
  21. Toast.makeText(MainActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
  22. }
  23. break;
  24. }
  25. }
  26. };
  27. @Override
  28. protected void onCreate(Bundle savedInstanceState) {
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.activity_main);
  31. initView();
  32. }
  33. private void initView() {
  34. btnPay = (Button) findViewById(R.id.btnPay);
  35. btnPay.setOnClickListener(this);
  36. }
  37. @Override
  38. public void onClick(View v) {
  39. switch (v.getId()) {
  40. case R.id.btnPay:
  41. //秘钥验证的类型 true:RSA2 false:RSA
  42. boolean rsa = false;
  43. //构造支付订单参数列表
  44. Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa);
  45. //构造支付订单参数信息
  46. String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
  47. //对支付参数信息进行签名
  48. String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE, rsa);
  49. //订单信息
  50. final String orderInfo = orderParam + "&" + sign;
  51. //异步处理
  52. Runnable payRunnable = new Runnable() {
  53. @Override
  54. public void run() {
  55. //新建任务
  56. PayTask alipay = new PayTask(MainActivity.this);
  57. //获取支付结果
  58. Map<String, String> result = alipay.payV2(orderInfo, true);
  59. Message msg = new Message();
  60. msg.what = SDK_PAY_FLAG;
  61. msg.obj = result;
  62. mHandler.sendMessage(msg);
  63. }
  64. };
  65. // 必须异步调用
  66. Thread payThread = new Thread(payRunnable);
  67. payThread.start();
  68. break;
  69. }
  70. }
  71. }
复制代码

可以看到我们并没有多少代码,调用起来

这里写图片描述

但是还是提示有错误,我们来看一下他的返回值

代码如下:
{"alipay_trade_app_pay_response":{"code":"40006","msg":"Insufficient Permissions","sub_code":"isv.insufficient-isv-permissions","sub_msg":"ISV权限不足"}}

这是因为我们这个应用并没有去签约功能,所有并没有这个权限,好的,但是起码可以看出我们已经可以调用支持包的支付了,那我们继续来了解他的功能吧

四.Api

首先我们看下他提供的OrderInfoUtil2_0这个工具类

  1. public class OrderInfoUtil2_0 {
  2. /**
  3. * 构造授权参数列表
  4. *
  5. * @param pid
  6. * @param app_id
  7. * @param target_id
  8. * @return
  9. */
  10. public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id, boolean rsa2) {
  11. Map<String, String> keyValues = new HashMap<String, String>();
  12. // 商户签约拿到的app_id,如:2013081700024223
  13. keyValues.put("app_id", app_id);
  14. // 商户签约拿到的pid,如:2088102123816631
  15. keyValues.put("pid", pid);
  16. // 服务接口名称, 固定值
  17. keyValues.put("apiname", "com.alipay.account.auth");
  18. // 商户类型标识, 固定值
  19. keyValues.put("app_name", "mc");
  20. // 业务类型, 固定值
  21. keyValues.put("biz_type", "openservice");
  22. // 产品码, 固定值
  23. keyValues.put("product_id", "APP_FAST_LOGIN");
  24. // 授权范围, 固定值
  25. keyValues.put("scope", "kuaijie");
  26. // 商户唯一标识,如:kkkkk091125
  27. keyValues.put("target_id", target_id);
  28. // 授权类型, 固定值
  29. keyValues.put("auth_type", "AUTHACCOUNT");
  30. // 签名类型
  31. keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");
  32. return keyValues;
  33. }
  34. /**
  35. * 构造支付订单参数列表
  36. * @param app_id
  37. * @return
  38. */
  39. public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2) {
  40. Map<String, String> keyValues = new HashMap<String, String>();
  41. keyValues.put("app_id", app_id);
  42. keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"我是测试数据\",\"out_trade_no\":\"" + getOutTradeNo() + "\"}");
  43. keyValues.put("charset", "utf-8");
  44. keyValues.put("method", "alipay.trade.app.pay");
  45. keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");
  46. keyValues.put("timestamp", "2016-07-29 16:55:53");
  47. keyValues.put("version", "1.0");
  48. return keyValues;
  49. }
  50. /**
  51. * 构造支付订单参数信息
  52. *
  53. * @param map
  54. * 支付订单参数
  55. * @return
  56. */
  57. public static String buildOrderParam(Map<String, String> map) {
  58. List<String> keys = new ArrayList<String>(map.keySet());
  59. StringBuilder sb = new StringBuilder();
  60. for (int i = 0; i < keys.size() - 1; i++) {
  61. String key = keys.get(i);
  62. String value = map.get(key);
  63. sb.append(buildKeyValue(key, value, true));
  64. sb.append("&");
  65. }
  66. String tailKey = keys.get(keys.size() - 1);
  67. String tailValue = map.get(tailKey);
  68. sb.append(buildKeyValue(tailKey, tailValue, true));
  69. return sb.toString();
  70. }
  71. /**
  72. * 拼接键值对
  73. *
  74. * @param key
  75. * @param value
  76. * @param isEncode
  77. * @return
  78. */
  79. private static String buildKeyValue(String key, String value, boolean isEncode) {
  80. StringBuilder sb = new StringBuilder();
  81. sb.append(key);
  82. sb.append("=");
  83. if (isEncode) {
  84. try {
  85. sb.append(URLEncoder.encode(value, "UTF-8"));
  86. } catch (UnsupportedEncodingException e) {
  87. sb.append(value);
  88. }
  89. } else {
  90. sb.append(value);
  91. }
  92. return sb.toString();
  93. }
  94. /**
  95. * 对支付参数信息进行签名
  96. *
  97. * @param map
  98. * 待签名授权信息
  99. *
  100. * @return
  101. */
  102. public static String getSign(Map<String, String> map, String rsaKey, boolean rsa2) {
  103. List<String> keys = new ArrayList<String>(map.keySet());
  104. // key排序
  105. Collections.sort(keys);
  106. StringBuilder authInfo = new StringBuilder();
  107. for (int i = 0; i < keys.size() - 1; i++) {
  108. String key = keys.get(i);
  109. String value = map.get(key);
  110. authInfo.append(buildKeyValue(key, value, false));
  111. authInfo.append("&");
  112. }
  113. String tailKey = keys.get(keys.size() - 1);
  114. String tailValue = map.get(tailKey);
  115. authInfo.append(buildKeyValue(tailKey, tailValue, false));
  116. String oriSign = SignUtils.sign(authInfo.toString(), rsaKey, rsa2);
  117. String encodedSign = "";
  118. try {
  119. encodedSign = URLEncoder.encode(oriSign, "UTF-8");
  120. } catch (UnsupportedEncodingException e) {
  121. e.printStackTrace();
  122. }
  123. return "sign=" + encodedSign;
  124. }
  125. /**
  126. * 要求外部订单号必须唯一。
  127. * @return
  128. */
  129. private static String getOutTradeNo() {
  130. SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
  131. Date date = new Date();
  132. String key = format.format(date);
  133. Random r = new Random();
  134. key = key + r.nextInt();
  135. key = key.substring(0, 15);
  136. return key;
  137. }
  138. }
复制代码

而我们一开始就需要构建订单参数列表,就是这个方法

  1. /**
  2. * 构造支付订单参数列表
  3. * @param app_id
  4. * @return
  5. */
  6. public static Map<String, String> buildOrderParamMap(String app_id, boolean rsa2) {
  7. Map<String, String> keyValues = new HashMap<String, String>();
  8. keyValues.put("app_id", app_id);
  9. keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\"0.01\",\"subject\":\"1\",\"body\":\"我是测试数据\",\"out_trade_no\":\"" + getOutTradeNo() + "\"}");
  10. keyValues.put("charset", "utf-8");
  11. keyValues.put("method", "alipay.trade.app.pay");
  12. keyValues.put("sign_type", rsa2 ? "RSA2" : "RSA");
  13. keyValues.put("timestamp", "2016-07-29 16:55:53");
  14. keyValues.put("version", "1.0");
  15. return keyValues;
  16. }
复制代码

这个方法我们来解读一下吧,他其实就是构建一个Map的键值对,都有哪些内容呢

  1. app_id(key)
  2. biz_content(内容)
  3. charset(编码)
  4. method(方法)
  5. sign_type(签名类型)
  6. timestamp(时间戳)
  7. version(版本)

这个demo里面可能都是写死了,但是如果我们真的要在实际应用中开发支付的话,这里要填写正确,我们主要关心的有方法和签名类型还有版本这三个

方法有几个类型,要注意一下

这里写图片描述

其次就是签名方式了,有两种,RSA和RSA2

最后就是版本,版本可以通过PayTask去获取

  1. //获取版本
  2. private String getPlayVersion(PayTask payTask){
  3. return payTask.getVersion();
  4. }
复制代码

而关于biz_content,就需要你们自己去定义了,我们来看下全部的参数说明

这里写图片描述

当我们拿到map之后就可以转换成一个string作为请求信息了,可以看到我们使用的是这个方法

  1. /**
  2. * 构造支付订单参数信息
  3. *
  4. * @param map
  5. * 支付订单参数
  6. * @return
  7. */
  8. public static String buildOrderParam(Map<String, String> map) {
  9. List<String> keys = new ArrayList<String>(map.keySet());
  10. StringBuilder sb = new StringBuilder();
  11. for (int i = 0; i < keys.size() - 1; i++) {
  12. String key = keys.get(i);
  13. String value = map.get(key);
  14. sb.append(buildKeyValue(key, value, true));
  15. sb.append("&");
  16. }
  17. String tailKey = keys.get(keys.size() - 1);
  18. String tailValue = map.get(tailKey);
  19. sb.append(buildKeyValue(tailKey, tailValue, true));
  20. return sb.toString();
  21. }
复制代码

他的本质就是拼接出最后的订单信息,如图

这里写图片描述

好的,现在订单详情已经有了我们就可以把订单加密了

  1. /**
  2. * 对支付参数信息进行签名
  3. *
  4. * @param map
  5. * 待签名授权信息
  6. *
  7. * @return
  8. */
  9. public static String getSign(Map<String, String> map, String rsaKey, boolean rsa2) {
  10. List<String> keys = new ArrayList<String>(map.keySet());
  11. // key排序
  12. Collections.sort(keys);
  13. StringBuilder authInfo = new StringBuilder();
  14. for (int i = 0; i < keys.size() - 1; i++) {
  15. String key = keys.get(i);
  16. String value = map.get(key);
  17. authInfo.append(buildKeyValue(key, value, false));
  18. authInfo.append("&");
  19. }
  20. String tailKey = keys.get(keys.size() - 1);
  21. String tailValue = map.get(tailKey);
  22. authInfo.append(buildKeyValue(tailKey, tailValue, false));
  23. String oriSign = SignUtils.sign(authInfo.toString(), rsaKey, rsa2);
  24. String encodedSign = "";
  25. try {
  26. encodedSign = URLEncoder.encode(oriSign, "UTF-8");
  27. } catch (UnsupportedEncodingException e) {
  28. e.printStackTrace();
  29. }
  30. return "sign=" + encodedSign;
  31. }
复制代码

这里的加密主要还是用到了SignUtils

  1. public class SignUtils {
  2. private static final String ALGORITHM = "RSA";
  3. private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
  4. private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";
  5. private static final String DEFAULT_CHARSET = "UTF-8";
  6. private static String getAlgorithms(boolean rsa2) {
  7. return rsa2 ? SIGN_SHA256RSA_ALGORITHMS : SIGN_ALGORITHMS;
  8. }
  9. public static String sign(String content, String privateKey, boolean rsa2) {
  10. try {
  11. PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
  12. Base64.decode(privateKey));
  13. KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
  14. PrivateKey priKey = keyf.generatePrivate(priPKCS8);
  15. java.security.Signature signature = java.security.Signature
  16. .getInstance(getAlgorithms(rsa2));
  17. signature.initSign(priKey);
  18. signature.update(content.getBytes(DEFAULT_CHARSET));
  19. byte[] signed = signature.sign();
  20. return Base64.encode(signed);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. return null;
  25. }
  26. }
复制代码

而SignUtils则启动了Base64

  1. public final class Base64 {
  2. private static final int BASELENGTH = 128;
  3. private static final int LOOKUPLENGTH = 64;
  4. private static final int TWENTYFOURBITGROUP = 24;
  5. private static final int EIGHTBIT = 8;
  6. private static final int SIXTEENBIT = 16;
  7. private static final int FOURBYTE = 4;
  8. private static final int SIGN = -128;
  9. private static char PAD = '=';
  10. private static byte[] base64Alphabet = new byte[BASELENGTH];
  11. private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
  12. static {
  13. for (int i = 0; i < BASELENGTH; ++i) {
  14. base64Alphabet[i] = -1;
  15. }
  16. for (int i = 'Z'; i >= 'A'; i--) {
  17. base64Alphabet[i] = (byte) (i - 'A');
  18. }
  19. for (int i = 'z'; i >= 'a'; i--) {
  20. base64Alphabet[i] = (byte) (i - 'a' + 26);
  21. }
  22. for (int i = '9'; i >= '0'; i--) {
  23. base64Alphabet[i] = (byte) (i - '0' + 52);
  24. }
  25. base64Alphabet['+'] = 62;
  26. base64Alphabet['/'] = 63;
  27. for (int i = 0; i <= 25; i++) {
  28. lookUpBase64Alphabet[i] = (char) ('A' + i);
  29. }
  30. for (int i = 26, j = 0; i <= 51; i++, j++) {
  31. lookUpBase64Alphabet[i] = (char) ('a' + j);
  32. }
  33. for (int i = 52, j = 0; i <= 61; i++, j++) {
  34. lookUpBase64Alphabet[i] = (char) ('0' + j);
  35. }
  36. lookUpBase64Alphabet[62] = (char) '+';
  37. lookUpBase64Alphabet[63] = (char) '/';
  38. }
  39. private static boolean isWhiteSpace(char octect) {
  40. return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
  41. }
  42. private static boolean isPad(char octect) {
  43. return (octect == PAD);
  44. }
  45. private static boolean isData(char octect) {
  46. return (octect < BASELENGTH && base64Alphabet[octect] != -1);
  47. }
  48. /**
  49. * Encodes hex octects into Base64
  50. *
  51. * @param binaryData
  52. * Array containing binaryData
  53. * @return Encoded Base64 array
  54. */
  55. public static String encode(byte[] binaryData) {
  56. if (binaryData == null) {
  57. return null;
  58. }
  59. int lengthDataBits = binaryData.length * EIGHTBIT;
  60. if (lengthDataBits == 0) {
  61. return "";
  62. }
  63. int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
  64. int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
  65. int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
  66. : numberTriplets;
  67. char encodedData[] = null;
  68. encodedData = new char[numberQuartet * 4];
  69. byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
  70. int encodedIndex = 0;
  71. int dataIndex = 0;
  72. for (int i = 0; i < numberTriplets; i++) {
  73. b1 = binaryData[dataIndex++];
  74. b2 = binaryData[dataIndex++];
  75. b3 = binaryData[dataIndex++];
  76. l = (byte) (b2 & 0x0f);
  77. k = (byte) (b1 & 0x03);
  78. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  79. : (byte) ((b1) >> 2 ^ 0xc0);
  80. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
  81. : (byte) ((b2) >> 4 ^ 0xf0);
  82. byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
  83. : (byte) ((b3) >> 6 ^ 0xfc);
  84. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  85. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
  86. encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
  87. encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
  88. }
  89. // form integral number of 6-bit groups
  90. if (fewerThan24bits == EIGHTBIT) {
  91. b1 = binaryData[dataIndex];
  92. k = (byte) (b1 & 0x03);
  93. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  94. : (byte) ((b1) >> 2 ^ 0xc0);
  95. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  96. encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
  97. encodedData[encodedIndex++] = PAD;
  98. encodedData[encodedIndex++] = PAD;
  99. } else if (fewerThan24bits == SIXTEENBIT) {
  100. b1 = binaryData[dataIndex];
  101. b2 = binaryData[dataIndex + 1];
  102. l = (byte) (b2 & 0x0f);
  103. k = (byte) (b1 & 0x03);
  104. byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
  105. : (byte) ((b1) >> 2 ^ 0xc0);
  106. byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
  107. : (byte) ((b2) >> 4 ^ 0xf0);
  108. encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
  109. encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
  110. encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
  111. encodedData[encodedIndex++] = PAD;
  112. }
  113. return new String(encodedData);
  114. }
  115. /**
  116. * Decodes Base64 data into octects
  117. *
  118. * @param encoded
  119. * string containing Base64 data
  120. * @return Array containind decoded data.
  121. */
  122. public static byte[] decode(String encoded) {
  123. if (encoded == null) {
  124. return null;
  125. }
  126. char[] base64Data = encoded.toCharArray();
  127. // remove white spaces
  128. int len = removeWhiteSpace(base64Data);
  129. if (len % FOURBYTE != 0) {
  130. return null;// should be divisible by four
  131. }
  132. int numberQuadruple = (len / FOURBYTE);
  133. if (numberQuadruple == 0) {
  134. return new byte[0];
  135. }
  136. byte decodedData[] = null;
  137. byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
  138. char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
  139. int i = 0;
  140. int encodedIndex = 0;
  141. int dataIndex = 0;
  142. decodedData = new byte[(numberQuadruple) * 3];
  143. for (; i < numberQuadruple - 1; i++) {
  144. if (!isData((d1 = base64Data[dataIndex++]))
  145. || !isData((d2 = base64Data[dataIndex++]))
  146. || !isData((d3 = base64Data[dataIndex++]))
  147. || !isData((d4 = base64Data[dataIndex++]))) {
  148. return null;
  149. }// if found "no data" just return null
  150. b1 = base64Alphabet[d1];
  151. b2 = base64Alphabet[d2];
  152. b3 = base64Alphabet[d3];
  153. b4 = base64Alphabet[d4];
  154. decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  155. decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  156. decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
  157. }
  158. if (!isData((d1 = base64Data[dataIndex++]))
  159. || !isData((d2 = base64Data[dataIndex++]))) {
  160. return null;// if found "no data" just return null
  161. }
  162. b1 = base64Alphabet[d1];
  163. b2 = base64Alphabet[d2];
  164. d3 = base64Data[dataIndex++];
  165. d4 = base64Data[dataIndex++];
  166. if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
  167. if (isPad(d3) && isPad(d4)) {
  168. if ((b2 & 0xf) != 0)// last 4 bits should be zero
  169. {
  170. return null;
  171. }
  172. byte[] tmp = new byte[i * 3 + 1];
  173. System.arraycopy(decodedData, 0, tmp, 0, i * 3);
  174. tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
  175. return tmp;
  176. } else if (!isPad(d3) && isPad(d4)) {
  177. b3 = base64Alphabet[d3];
  178. if ((b3 & 0x3) != 0)// last 2 bits should be zero
  179. {
  180. return null;
  181. }
  182. byte[] tmp = new byte[i * 3 + 2];
  183. System.arraycopy(decodedData, 0, tmp, 0, i * 3);
  184. tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  185. tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  186. return tmp;
  187. } else {
  188. return null;
  189. }
  190. } else { // No PAD e.g 3cQl
  191. b3 = base64Alphabet[d3];
  192. b4 = base64Alphabet[d4];
  193. decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
  194. decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
  195. decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
  196. }
  197. return decodedData;
  198. }
  199. /**
  200. * remove WhiteSpace from MIME containing encoded Base64 data.
  201. *
  202. * @param data
  203. * the byte array of base64 data (with WS)
  204. * @return the new length
  205. */
  206. private static int removeWhiteSpace(char[] data) {
  207. if (data == null) {
  208. return 0;
  209. }
  210. // count characters that's not whitespace
  211. int newSize = 0;
  212. int len = data.length;
  213. for (int i = 0; i < len; i++) {
  214. if (!isWhiteSpace(data[i])) {
  215. data[newSize++] = data[i];
  216. }
  217. }
  218. return newSize;
  219. }
  220. }
复制代码

这些你都可以在我写的demo里获取到的,我们继续分析就是了,当加密成功之后他会返回一个sign的字符串给我,这就是加密信息,然后通过 订单信息 & 加密订单这种公式就拼接出商品信息

  1. //订单信息
  2. String orderInfo = orderParam + "&" + sign;
复制代码

好的,我们的下单需要在异步中操作,也就是我们所见到的Runnable

  1. Runnable payRunnable = new Runnable() {
  2. @Override
  3. public void run() {
  4. //新建任务
  5. PayTask alipay = new PayTask(MainActivity.this);
  6. //获取支付结果
  7. Map<String, String> result = alipay.payV2(orderInfo, true);
  8. Message msg = new Message();
  9. msg.what = SDK_PAY_FLAG;
  10. msg.obj = result;
  11. mHandler.sendMessage(msg);
  12. }
  13. };
复制代码

在这里他同样的是构建一个PayTask 区调用payV2,里面的参数就是订单信息和一个boolean值,具体参数可以参考

这里写图片描述

好的,当我们拿到结果后通过Handler回到UI线程

  1. PayResult payResult = new PayResult((Map<String, String>) msg.obj);
  2. //同步获取结果
  3. String resultInfo = payResult.getResult();
  4. Log.i("Pay", "Pay:" + resultInfo);
  5. String resultStatus = payResult.getResultStatus();
  6. // 判断resultStatus 为9000则代表支付成功
  7. if (TextUtils.equals(resultStatus, "9000")) {
  8. Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
  9. } else {
  10. Toast.makeText(MainActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
  11. }
复制代码

这里其实PayResult只是把结果几个关键信息提取出来了

  1. public class PayResult {
  2. private String resultStatus;
  3. private String result;
  4. private String memo;
  5. public PayResult(Map<String, String> rawResult) {
  6. if (rawResult == null) {
  7. return;
  8. }
  9. for (String key : rawResult.keySet()) {
  10. if (TextUtils.equals(key, "resultStatus")) {
  11. resultStatus = rawResult.get(key);
  12. } else if (TextUtils.equals(key, "result")) {
  13. result = rawResult.get(key);
  14. } else if (TextUtils.equals(key, "memo")) {
  15. memo = rawResult.get(key);
  16. }
  17. }
  18. }
  19. @Override
  20. public String toString() {
  21. return "resultStatus={" + resultStatus + "};memo={" + memo
  22. + "};result={" + result + "}";
  23. }
  24. /**
  25. * @return the resultStatus
  26. */
  27. public String getResultStatus() {
  28. return resultStatus;
  29. }
  30. /**
  31. * @return the memo
  32. */
  33. public String getMemo() {
  34. return memo;
  35. }
  36. /**
  37. * @return the result
  38. */
  39. public String getResult() {
  40. return result;
  41. }
  42. }
复制代码

我们如果想看详细的结果,可以打印resultInfo,好的,关于返回参数,可以参考App支付同步通知参数说明

这里写图片描述

好的,事实上在实际开发中,要做的准备工作并不只是这么点,毕竟涉及到支付这个敏感话题,我这边也只是个人商户,没办法给大家展示正确的结果了,可能有些疏漏,但是大体就是这样,比微信稍微要简单点,我们下次细聊下微信支付,我们感觉去注册个账号去~~~

源码SimpleMall下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条