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

Android app第三方支付宝支付接入教程

程序员文章站 2024-03-31 17:10:52
支付宝的接入相对比较简单,看看支付宝官网的文档基本都能搞定,但是切记一点让你们的后台也要搞清楚支付宝的流程,重中之重。 1、注意事项 开发前一定要阅读支付宝官方文档...

支付宝的接入相对比较简单,看看支付宝官网的文档基本都能搞定,但是切记一点让你们的后台也要搞清楚支付宝的流程,重中之重。

1、注意事项
开发前一定要阅读支付宝官方文档
强烈建议签名等处理在后台处理,我这个是测试是在自己本地写的,不要吐槽
想获取支付宝合作商户id,及支付宝公钥请点击支付宝链接,生成密钥及pkcs8转码工具在文档中
添加android.permission.internet权限和android.permission.access_network_state权限
要导入支付宝的包
2、特别注意事项(坑点)
下载支付宝的官网之后生成你所需要的密钥及pkcs8转码一定要小心

代码:
mainactivity中调起支付:pay pay = new pay(affirmorderactivity.this, paymoney);

pay 类

public class pay {

                 /**以下四项这些数值机密填入自己申请的就好**/
  // 商户pid
  public static final string partner = "";
  // 商户收款账号
  public static final string seller = "";
  // 商户私钥,pkcs8格式
  public static final string rsa_private = "";
  // 支付宝公钥
  public static final string rsa_public = "";

  private activity context;
  private string mgoods,mprice,micon;
  private int mtype;
  private string mouttradeno;
  public pay(activity activity, string goods,string goodsmore,string price,string icon,int type, string outtradeno) {
    context = activity;
    mprice = price;
    pay(price);
  }


  private handler mhandler = new handler() {

    public void handlemessage(message msg) {
      switch (msg.what) {
        case sdk_pay_flag: {
          payresult payresult = new payresult((string) msg.obj);
          /**
           * 同步返回的结果必须放置到服务端进行验证(验证的规则请看https://doc.open.alipay.com/doc2/
           * detail.htm?spm=0.0.0.0.xdvau6&treeid=59&articleid=103665&
           * doctype=1) 建议商户依赖异步通知
           */
          string resultinfo = payresult.getresult();// 同步返回需要验证的信息

          string resultstatus = payresult.getresultstatus();
          // 判断resultstatus 为“9000”则代表支付成功,具体状态码代表含义可参考接口文档
          if (textutils.equals(resultstatus, "9000")) {
            toast.maketext(context, "支付成功", toast.length_short).show();

          } else {
            // 判断resultstatus 为非"9000"则代表可能支付失败
            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
            if (textutils.equals(resultstatus, "8000")) {
              toast.maketext(context, "支付结果确认中", toast.length_short).show();

            } else {
              // 其他值就可以判断为支付失败,包括用户主动取消支付,或者系统返回的错误
              toast.maketext(context, "支付失败", toast.length_short).show();

            }
          }
          break;
        }
        default:
          break;
      }
    };
  };


  /**
   * call alipay sdk pay. 调用sdk支付
   *
   */
  public void pay(string goods,string goodsmore,string price) {
    if (textutils.isempty(partner) || textutils.isempty(rsa_private) || textutils.isempty(seller)) {
      new alertdialog.builder(context).settitle("警告").setmessage("需要配置partner | rsa_private| seller")
          .setpositivebutton("确定", new dialoginterface.onclicklistener() {
            public void onclick(dialoginterface dialoginterface, int i) {
              //
//              finish();
            }
          }).show();
      return;
    }
    string orderinfo = getorderinfo(goods, goodsmore, price);

    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();
    log.i("lff", "orderinfo == " +orderinfo);
    log.i("lff", "sign == " +sign);    runnable payrunnable = new runnable() {

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

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

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

  /**
   * get the sdk version. 获取sdk版本号
   *
   */
  public void getsdkversion() {
    paytask paytask = new paytask(context);
    string version = paytask.getversion();
    toast.maketext(context, version, toast.length_short).show();
  }




  /**
   * create the order info. 创建订单信息
   *
   */
  private string getorderinfo(string subject, string body, string price) {

    // 签约合作者身份id
    string orderinfo = "partner=" + "\"" + partner + "\"";

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

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

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

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

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

    // 服务器异步通知页面路径
//    orderinfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm" + "\"";
    orderinfo += "&notify_url=" + "\"" + "http://112.74.129.252/new/zfbcallback" + "\"";
    // 服务接口名称, 固定值
    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;
  }

  /**
   * get the out_trade_no for an order. 生成商户订单号,该值在商户端应保持唯一(可自定义格式规范)
   *
   */
  private 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;
    return mouttradeno;
  }

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

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

}

其它的工具类,原封不动拷贝过去就好

base64 类

package com.easyhomework.teacher.ui;

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

总结一下支付宝支付步骤:1、生成秘钥私钥等(一般是后台处理的) ;2、支付宝包复制带项目中 ;3、调用支付(上述mainactivity和pay类) 4、添加工具类

以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。