Android Alipay Payment Package code _android

Source: Internet
Author: User
Tags 0xc0 base64 static class

The

will definitely use Alipay to pay for the Android payment, and it's very hard to do it according to the official demo, so we need a simple package. The
encapsulated code is also very simple, that is, the demo of the Generals network to extract a class to facilitate the use.

public class Alipay {//merchant PID public static final String PARTNER = "123456789";
  Merchant Receivables Account public static final String SELLER = "qibin0506@gmail.com";
  Merchant private key, PKCS8 format public static final String rsa_private = "Rsa_private";

  The Alipay public key, the final String rsa_public = "Rsa_public";

  private static final int sdk_pay_flag = 1;

  Private weakreference<activity> mactivity;

  Private Onalipaylistener Mlistener;
  Public Alipay {mactivity = new weakreference<activity> (activity);  @SuppressLint ("Handlerleak") private Handler Mhandler = new Handler () {public void Handlemessage (msg)
        {if (Msg.what = = Sdk_pay_flag) {Payresult Payresult = new Payresult ((String) msg.obj);
        Alipay return this payment results and endorsement, the proposal to pay treasure signature information to take the signing of Alipay provided by the public key to do the verification of a String Resultinfo = Payresult.getresult ();
        String resultstatus = Payresult.getresultstatus (); The Judge Resultstatus is "9000" to represent the successful payment, the specific status code represents the meaning of the Reference interface document if (TeXtutils.equals (Resultstatus, "9000")) {if (Mlistener!= null) mlistener.onsuccess (); else {//Judge Resultstatus is not "9000" represents a possible payment failure//"8000" representative payment results due to payment channel reasons or system reasons are still waiting for payment results confirmation,//FINAL delivery Easy to succeed with server-side asynchronous notification (small probability state) if (Textutils.equals (Resultstatus, "8000")) {if (Mlistener!= null) mlistene
          R.onwait ();
          else {//other value can be judged as payment failure, including user active cancellation payment, or system return error if (Mlistener!= null) mlistener.oncancel ();

  }
        }
      }
    }
  };  /** * Payment * * @param title cannot be empty or "" * @param desc description cannot be empty or "* @param price cannot be null or" "* @param sn  Product unique item number cannot be empty or "" * @param URL Server callback URL cannot be empty or "" */public void Pay (string title, String desc, string price, string

    sn, string URL) {//order string orderInfo = GetOrderInfo (title, desc, price, sn, url);
    Make an RSA signature String sign = sign (orderInfo) on an order; try {//Only need to sign URL encoding sign = Urlencoder.encode (sign, "UTF-8");
    catch (Unsupportedencodingexception e) {e.printstacktrace (); //Complete order information conforming to Alipay parameter specification final String payinfo = orderInfo + "&sign=\" "+ Sign +" & "+ Getsigntype

    (); Runnable payrunnable = new Runnable () {@Override public void run () {Activity activity = MACTIVITY.G
        ET ();
        if (activity = null) return;
        Construct Paytask Object Paytask Alipay = new Paytask (activity);

        Call the payment interface to get the payment results String result = Alipay.pay (payinfo);
        msg = new Message ();
        Msg.what = Sdk_pay_flag;
        Msg.obj = result;
      Mhandler.sendmessage (msg);

    }
    };
    Thread paythread = new Thread (payrunnable) must be invoked asynchronously;
  Paythread.start (); }/** * Create the order info.
    Create order Information */public string GetOrderInfo (string subject, string body, string price, String sn, string url) {

    Contract Partner ID String orderInfo = "partner=" + "\" "+ partner +" \ ""; AgencySeller Alipay Account OrderInfo = "&seller_id=" + "" "+ Seller +" "";

    Merchant website Unique Order number OrderInfo + + "&out_trade_no=" + "" + sn + "" ";

    Product Name OrderInfo + + "&subject=" + "" "+ Subject +" "";

    Product Details OrderInfo + + "&body=" + "" "+ Body +" "";

    The amount of the goods OrderInfo + + "&total_fee=" + "" "+ Price +" \ ";

    The Server Asynchronous notification page path OrderInfo + + "&notify_url=" + "\" + URL + "\";

    Service interface name, fixed value orderInfo + = "&service=\" mobile.securitypay.pay\ "";

    Payment type, fixed value orderInfo + = "&payment_type=\" 1\ "";

    parameter coding, fixed value orderInfo + = "&_input_charset=\" utf-8\ "";
    Set the timeout for an unpaid transaction/default of 30 minutes, and the transaction is automatically closed once the timeout is exceeded.
    Value range: 1m~15d.
    M-Minute, H-hour, D-Day, 1c-day (regardless of when the transaction was created, closed at 0 points).
    This parameter value does not accept decimal points, such as 1.5h, and can be converted to 90m.

    OrderInfo = "&it_b_pay=\" 30m\ ""; Extern_token for the alipay_open_id obtained by the express authorization, take this parameter the user will use the authorized account to pay//OrderInfo + + + "&extern_token=" + "" + Extern_toke

    n + "\"; After Alipay has finished processing the request, the current page jumps to the merchant specified pagePath, can be empty orderInfo + + "&return_url=\" m.alipay.com\ "";

    Call the bank card payment, need to configure this parameter, participate in the signature, fixed value (need to sign "wireless bank card fast Payment" to use)//OrderInfo + + "&paymethod=\" expressgateway\ ";
  return orderInfo; }/** * Sign the order info. Sign the Order information * * @param content * Pending signed order information/public string sign (String content) {return signutils.si
  GN (content, rsa_private); /** * Get the ' sign type we use.
  Get signature Mode */public String Getsigntype () {return "sign_type=\" Rsa\ "";
  public void Setlistener (Onalipaylistener l) {mlistener = l;
     /** * Payment Callback interface * * @author Lenovo * */public static class Onalipaylistener {/** * paid successfully
     * * public void onsuccess () {}/** * payment cancellation/public void OnCancel () {}/** * waiting for confirmation
  */public void onwait () {}}} final class Base64 {private static final int baselength = 128;
  private static final int lookuplength = 64; private static Final intTwentyfourbitgroup = 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 <= i++) {Lookupbase64alphabet[i] = (char) (' A ' + i);
 for (int i =, j = 0; I <= i++, J + +) {Lookupbase64alphabet[i] = (char) (' a ' + j);   for (int i =, j = 0; I <= 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 | | oc
  Tect = = 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 * @ret URN encoded BASE64 array */public static String encode (byte[] binarydata) {if (BinaryData = null) {RET
    Urn 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 to New String (Encodeddata); /** * Decodes Base64 data into octects * * @param encoded * String containing Base64 data * @ret
   Urn 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 is divisible by four} int numberquadruple = (Len/fourby

    TE);
    if (numberquadruple = = 0) {return new byte[0];
    } byte decodeddata[] = null; ByteB1 = 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 = ba se64data[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 (d3) | |!isdata ((d4)) {/Check if they are PAD characters if (Ispad (D3) && Ispad (D4)) {!isdata
        if ((B2 & 0xf)!= 0)//Last 4 bits should is 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 is 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 I
    NT 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 = Gatva
      Lue (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 Pkcs8enc
      Odedkeyspec (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;
 }
}

The previous several constants are needed to pay the official website to obtain, after obtaining the direct replacement on OK,
The rest of the code is basically copy from the demo, now we have to encapsulate the payment function in a class, then how to use it?

Alipay Alipay = new Alipay (orderconfirmactivity.this);
Alipay.setlistener (Malipaylistener);
Alipay.pay (DESC, Morder.getshopname (), string.valueof (OrderAmount), ORDERSN, URL); /**
 * Alipay Payment callback
 /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 out object, only need to call the pay method is OK, but we still need to pay the callback, of course, this is not troublesome. Here's a few arguments for the pay method,

    • Title to pay
    • Description of DESC Payment
    • Amount paid by Price
    • Unique item number of SN product
    • Callback URL for URL server

These parameters will be given to the server at the time of payment, but be aware that none of these parameters can be empty or empty, or you may fail to pay.

The above is the package of Android Alipay payment Code, I hope to learn from everyone.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.