Android App Third party Alipay payment Access Tutorial _android

Source: Internet
Author: User
Tags 0xc0 base64

Alipay's access is relatively simple to see the payment of the official website of the basic documents can be done, but remember that your backstage also want to make clear the process of Alipay, the most important.

1. Attention Matters
must read Alipay official document before developing
It is strongly recommended that signatures such as processing in the background processing, I this is the test is written in their own local, do not spit groove
Want to get Alipay partner ID, and Alipay public key please click on Alipay link, generate key and PKCS8 transcoding tool in document
Add Android.permission.INTERNET permissions and Android.permission.ACCESS_NETWORK_STATE permissions
To import Alipay's package
2. Special precautions (Pit point)
Download Alipay's official website and generate the key and PKCS8 you need to be careful.

Code:
Mainactivity Payment: Pay Pay = new Pay (affirmorderactivity.this, Paymoney);

Pay class

The public class Pay {/** The following four items of these numeric secrets into their own application is good **///merchant PID public static final String PARTNER = "";
  Merchant Receivables Account public static final String SELLER = "";
  Merchant private key, PKCS8 format public static final String rsa_private = "";

  Alipay public Key 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) {Co
    ntext = activity;
    Mprice = Price;
  Pay (price);
        Private Handler Mhandler = new Handler () {public void Handlemessage (msg) {switch (msg.what) {
          Case Sdk_pay_flag: {payresult payresult = new Payresult ((String) msg.obj); /** * The results returned by synchronization must be placed on the server side for validation (validation rules See https://doc.open.alipay.com/doc2/* DETAIL.HTM?SPM=0.0.0.0.XDVAU6&A mp;treeid=59&articleid=103665& * doctype=1) recommends that the Merchant rely on asynchronous notification/String resultinfo = Payresult.getresult ();//sync returns the information that needs to be validated string Resultstat
          US = Payresult.getresultstatus (); The Judge Resultstatus is "9000" to represent the successful payment, the specific status code represents the meaning can refer to the interface document if (Textutils.equals (Resultstatus, "9000")) {Toas

          T.maketext (Context, "pay success", Toast.length_short). Show (); else {//Judge Resultstatus is not "9000" represents a possible payment failure//"8000" representative payment results due to the payment channel reasons or system reasons are still waiting for payment results confirmed that the final transaction was successful with service-side differences Step notification is quasi (small probability state) if (Textutils.equals (Resultstatus, "8000")) {Toast.maketext (context, "Payment result confirmation", to Ast.

            Length_short). Show (); else {//other value can be judged as payment failure, including user active cancellation payment, or system return error Toast.maketext (context, "Payment failure", Toast.length_sh

            ORT). Show ();
        }} break;
      } Default:break;
  }
    };


  }; /** * Call Alipay SDK pay.
  Call SDK Payment * */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 ("Warning"). Setmessage ("Need to configure partner | rsa_private| SELLER "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {public void OnClick (Dialog
            Interface dialoginterface, int i) {////Finish ();
      ). Show ();
    Return

    String OrderInfo = getorderinfo (Goods, goodsmore, price);

    String sign = sign (orderInfo);

    try {/** * only need to sign URL encoding */sign = Urlencoder.encode (sign, "UTF-8");
    catch (Unsupportedencodingexception e) {e.printstacktrace (); /** * Complete order information in accordance with Alipay parameter specification * * Final String Payinfo = orderInfo + "&sign=\" "+ sign +" \ & "+ Get
    Signtype ();
    LOG.I ("Lff", "orderInfo = =" +orderinfo);    LOG.I ("Lff", "sign = =" +sign); Runnable payrunnable = new Runnable () {@OverriDe public void Run () {//Construct Paytask object Paytask Alipay = new Paytask (context);

        Call the payment interface to get the payment results String result = Alipay.pay (Payinfo, true);
        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 (); }/** * Get the SDK version.
    Get SDK Version Number * */public void getsdkversion () {Paytask paytask = new Paytask (context);
    String Version = Paytask.getversion ();
  Toast.maketext (context, version, Toast.length_short). Show (); }/** * Create the order info. Create order Information */private string GetOrderInfo (string subject, string body, string price) {//Contract partner ID String

    OrderInfo = "partner=" + "\" "+ Partner +" "";

    Signed sellers pay Treasure Account OrderInfo + + + &seller_id= + "" + Seller + "" "; Merchant website Unique Order number OrderInfo + + "&out_trade_no=" + "\""+ Getouttradeno () +" "";

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

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

    The amount of merchandise OrderInfo + + "&total_fee=" + "" "+" 0.01 "+" ";
    Server Asynchronous Notification page path//OrderInfo + + "&notify_url=" + "\" + "http://notify.msp.hk/notify.htm" + "" ";
    OrderInfo + + "&notify_url=" + "" "+" Http://112.74.129.252/new/zfbCallback "+" "";

    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 pageJump to the merchant specify the path of the page, 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; /** * Get the "out_trade_no for" order. Generate merchant order number, which should remain unique on the merchant side (customizable format specification) */private String Getouttradeno () {//SimpleDateFormat format = new Simpledate
Format ("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. Sign the Order information * * @param content * Pending signed order information/private string sign (string content) {return signutils.si
  GN (content, rsa_private); /** * Get the ' sign type we use.
  Get Signature method */Private String Getsigntype () {return "sign_type=\" "rsa\";

 }

}

Other tool classes, copy the past intact.

Base64 class

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 (inti = 0; I <= 25;
    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/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 = 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;

 }
}

Sum up Alipay Payment steps: 1, generate secret key, etc. (usually in the background processing); 2, pay the treasure bag to copy belt project; 3, call payment (above mainactivity and pay Class) 4, Add tool class

This is the entire content of this article, I hope to learn more about Android software programming help.

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.