欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android接入支付宝实现支付功能实例

程序员文章站 2022-06-11 09:33:27
我本来是想直接讲android支付这一块的,包括支付宝,微信,其他第三方整合支付等,但是微信开放平台他对我的账号做了限制,所有我今天就先把重心放在支付宝的支付上,也算是写得...

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

一.准备步骤

1.登录官网

他的官网就是蚂蚁金服的开放平台了,我们可以访问 ,并且注册账号进行登录

Android接入支付宝实现支付功能实例

创建应用

如果你是现有的应用直接接入支付功能的话,可以不看这里,我这里是因为需要讲博客所有重新创建了一个项目并且在android studio里也重新创建了一个项目,android studio里创建的项目我把他叫做simplemall,简单商城的意思,那在开放平台我们又是如何去创建应用呢,点击-进入我的开放平台-应用,就可以看到应用管理了。我们点击创建应用

Android接入支付宝实现支付功能实例

创建成果之后有很多的选项包括需要你上传

Android接入支付宝实现支付功能实例

这些先不管,我们这个时候可以看到已经拿到了appid: 2017062807585767,这样我们就可以继续下一步的准备了

3.签约

大部分的功能需要签约才能使用,很遗憾,我这个个体户就不行了

Android接入支付宝实现支付功能实例

4.配置密钥

配置秘钥是支付这一环节很重要的因素,也是分了两个步骤,生成秘钥和配置秘钥,这里使用的ras非对称加密

我们按照文档上来,首先是下载工具了,这里有win和mac两个地址,我是win,下载下来是这个样子的

Android接入支付宝实现支付功能实例

我们按照图中的配置拿到了公钥和私钥

Android接入支付宝实现支付功能实例

那我们可以配置了,我们找到项目详情

Android接入支付宝实现支付功能实例

然后这里是两种方式,我们选择的是rsa方式么其实哪种方式都是可以的

Android接入支付宝实现支付功能实例

到这里,这个也配置好了

5.sdk 下载

到这里,我们就可以直接去下载他的sdk了sdk下载地址

这个压缩包下载下来什么都有,要找到android的部分

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+086w3bpjyo5rq6b8mxu66wg3crkjhwpaq5a6cxb1u757y2j2qpcckdy3zxed7z0bekgxwpzwkainxm30kvho9qxvfx3oildca2qok7h5vrrrch9ghdzkygf7f0wrfwnwkbgqc2zkyovpe881ek0sfhurutn99m+msciylzjnerpopxcbvvirv3rmvyzcrscijeqqmznqm7vdkqh3mtutednpv2qux3qlhk756q8pdms9hpl9wk8ngssa6aqfgqrv16ngjyrm1h+fm6c6k9yfaojxw/5qyf48x0hxre39++txszwqkbgbnji/fovb2jch1pkcbp9ouz3+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;
    }
  }
}

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

Android接入支付宝实现支付功能实例

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

复制代码 代码如下:

{"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的键值对,都有哪些内容呢

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

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

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

Android接入支付宝实现支付功能实例

其次就是签名方式了,有两种,rsa和rsa2

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

 //获取版本
  private string getplayversion(paytask paytask){
    return paytask.getversion();
  }

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

Android接入支付宝实现支付功能实例

当我们拿到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();
  }

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

Android接入支付宝实现支付功能实例

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

  /**
   * 对支付参数信息进行签名
   * 
   * @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值,具体参数可以参考

Android接入支付宝实现支付功能实例

好的,当我们拿到结果后通过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接入支付宝实现支付功能实例

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

源码simplemall下载

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