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

Android支付宝支付封装代码

程序员文章站 2023-12-15 23:13:22
在做android支付的时候肯定会用到支付宝支付, 根据官方给出的demo做起来非常费劲,所以我们需要一次简单的封装。 封装的代码也很简单,就是将官网给的demo提取出...

在做android支付的时候肯定会用到支付宝支付, 根据官方给出的demo做起来非常费劲,所以我们需要一次简单的封装。
封装的代码也很简单,就是将官网给的demo提取出一个类来方便使用。

public class alipay {
  // 商户pid
  public static final string partner = "123456789";
  // 商户收款账号
  public static final string seller = "qibin0506@gmail.com";
  // 商户私钥,pkcs8格式
  public static final string rsa_private = "rsa_private";
  // 支付宝公钥
  public static final string rsa_public = "rsa_public";

  private static final int sdk_pay_flag = 1;

  private weakreference<activity> mactivity;

  private onalipaylistener mlistener;

  public alipay(activity activity) {
    mactivity = new weakreference<activity>(activity);
  }

  @suppresslint("handlerleak") 
  private handler mhandler = new handler() {
    public void handlemessage(message msg) {
      if (msg.what == sdk_pay_flag) {
        payresult payresult = new payresult((string) msg.obj);
        // 支付宝返回此次支付结果及加签,建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
        string resultinfo = payresult.getresult();
        string resultstatus = payresult.getresultstatus();
        // 判断resultstatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档
        if (textutils.equals(resultstatus, "9000")) {
          if (mlistener != null) mlistener.onsuccess();
        } else {
          // 判断resultstatus 为非“9000”则代表可能支付失败
          // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,
          // 最终交易是否成功以服务端异步通知为准(小概率状态)
          if (textutils.equals(resultstatus, "8000")) {
            if (mlistener != null) mlistener.onwait();
          } else {
            // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
            if (mlistener != null) mlistener.oncancel();
          }
        }
      }
    }
  };

  /**
   * 支付
   * 
   * @param title  标题 不能为空或者“”
   * @param desc 描述 不能为空或者“”
   * @param price 价格 不能为空或者“”
   * @param sn 商品唯一货号 不能为空或者“”
   * @param url 服务器回调url 不能为空或者“”
   */
  public void pay(string title, string desc, string price, string sn, string url) {
    // 订单
    string orderinfo = getorderinfo(title, desc, price, sn, url);

    // 对订单做rsa 签名
    string sign = sign(orderinfo);
    try {
      // 仅需对sign 做url编码
      sign = urlencoder.encode(sign, "utf-8");
    } catch (unsupportedencodingexception e) {
      e.printstacktrace();
    }

    // 完整的符合支付宝参数规范的订单信息
    final string payinfo = orderinfo + "&sign=\"" + sign + "\"&"
        + getsigntype();

    runnable payrunnable = new runnable() {

      @override
      public void run() {
        activity activity = mactivity.get();
        if(activity == null) return;
        // 构造paytask 对象
        paytask alipay = new paytask(activity);
        // 调用支付接口,获取支付结果
        string result = alipay.pay(payinfo);

        message msg = new message();
        msg.what = sdk_pay_flag;
        msg.obj = result;
        mhandler.sendmessage(msg);
      }
    };

    // 必须异步调用
    thread paythread = new thread(payrunnable);
    paythread.start();
  }

  /**
   * create the order info. 创建订单信息
   * 
   */
  public string getorderinfo(string subject, string body, string price,
      string sn, string url) {
    // 签约合作者身份id
    string orderinfo = "partner=" + "\"" + partner + "\"";

    // 签约卖家支付宝账号
    orderinfo += "&seller_id=" + "\"" + seller + "\"";

    // 商户网站唯一订单号
    orderinfo += "&out_trade_no=" + "\"" + sn + "\"";

    // 商品名称
    orderinfo += "&subject=" + "\"" + subject + "\"";

    // 商品详情
    orderinfo += "&body=" + "\"" + body + "\"";

    // 商品金额
    orderinfo += "&total_fee=" + "\"" + price + "\"";

    // 服务器异步通知页面路径
    orderinfo += "&notify_url=" + "\"" + url + "\"";

    // 服务接口名称, 固定值
    orderinfo += "&service=\"mobile.securitypay.pay\"";

    // 支付类型, 固定值
    orderinfo += "&payment_type=\"1\"";

    // 参数编码, 固定值
    orderinfo += "&_input_charset=\"utf-8\"";

    // 设置未付款交易的超时时间
    // 默认30分钟,一旦超时,该笔交易就会自动被关闭。
    // 取值范围:1m~15d。
    // m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。
    // 该参数数值不接受小数点,如1.5h,可转换为90m。
    orderinfo += "&it_b_pay=\"30m\"";

    // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
    // orderinfo += "&extern_token=" + "\"" + extern_token + "\"";

    // 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空
    orderinfo += "&return_url=\"m.alipay.com\"";

    // 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)
    // orderinfo += "&paymethod=\"expressgateway\"";

    return orderinfo;
  }

  /**
   * sign the order info. 对订单信息进行签名
   * 
   * @param content
   *      待签名订单信息
   */
  public string sign(string content) {
    return signutils.sign(content, rsa_private);
  }

  /**
   * get the sign type we use. 获取签名方式
   * 
   */
  public string getsigntype() {
    return "sign_type=\"rsa\"";
  }

  public void setlistener(onalipaylistener l) {
    mlistener = l;
  }

  /**
   * 支付回调接口
   * 
   * @author lenovo
   * 
   */
  public static class onalipaylistener {
    /**
     * 支付成功
     */
    public void onsuccess() {}

    /**
     * 支付取消
     */
    public void oncancel() {}

    /**
     * 等待确认
     */
    public void onwait() {}
  }
}

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;
  }
}

class payresult {
  private string resultstatus;
  private string result;
  private string memo;

  public payresult(string rawresult) {

    if (textutils.isempty(rawresult))
      return;

    string[] resultparams = rawresult.split(";");
    for (string resultparam : resultparams) {
      if (resultparam.startswith("resultstatus")) {
        resultstatus = gatvalue(resultparam, "resultstatus");
      }
      if (resultparam.startswith("result")) {
        result = gatvalue(resultparam, "result");
      }
      if (resultparam.startswith("memo")) {
        memo = gatvalue(resultparam, "memo");
      }
    }
  }

  @override
  public string tostring() {
    return "resultstatus={" + resultstatus + "};memo={" + memo
        + "};result={" + result + "}";
  }

  private string gatvalue(string content, string key) {
    string prefix = key + "={";
    return content.substring(content.indexof(prefix) + prefix.length(),
        content.lastindexof("}"));
  }

  /**
   * @return the resultstatus
   */
  public string getresultstatus() {
    return resultstatus;
  }

  /**
   * @return the memo
   */
  public string getmemo() {
    return memo;
  }

  /**
   * @return the result
   */
  public string getresult() {
    return result;
  }
}

class signutils {

  private static final string algorithm = "rsa";

  private static final string sign_algorithms = "sha1withrsa";

  private static final string default_charset = "utf-8";

  public static string sign(string content, string privatekey) {
    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(sign_algorithms);

      signature.initsign(prikey);
      signature.update(content.getbytes(default_charset));

      byte[] signed = signature.sign();

      return base64.encode(signed);
    } catch (exception e) {
      e.printstacktrace();
    }

    return null;
  }
}

前面的几个常量是需要去支付宝官网获取的,获取后直接替换就ok,
其他的代码基本都是从demo中copy出来的, 现在我们就将支付功能封装到了一个类中,那么如何使用呢?

alipay alipay = new alipay(orderconfirmactivity.this);
alipay.setlistener(malipaylistener);
alipay.pay(desc, morder.getshopname(), string.valueof(orderamount), ordersn, url); /**
 * 支付宝支付回调
 */ private alipay.onalipaylistener malipaylistener = new alipay.onalipaylistener() { @override public void onsuccess() {
    onordersubmitsuccess();
  } @override public void oncancel() {
    onuserordercanceled();
      toast.maketext(orderconfirmactivity.this, r.string.pay_failed, 
          toast.length_short).show();
  } @override public void onwait() {

  }
};

new出对象来,只需要调用pay方法就ok啦, 不过支付的回调我们还是必须的,当然这个也不麻烦。这里说一下pay方法的几个参数,

  • title 支付的标题
  • desc 支付的描述
  • price 支付的金额
  • sn 商品的唯一货号
  • url 服务器的回调url

这几个参数在做支付的时候服务器都会给到,但是要注意一下,这几个参数都不能为空或者空字符串,否则会支付失败。

以上就是封装android支付宝支付的代码,希望对大家的学习有所启发。

上一篇:

下一篇: