Android-based on micro-letter open Platform V3SDK Development (micro-credit payment landfills) _android

Source: Internet
Author: User
Tags stringbuffer

Contact with micro-letter payment before I heard it was a pit, and the heart had been ready ... I thought I could not jump out of the pit, did not think I filled in, after the success of the call I feel that all of the company's colleagues are beautiful, through the heavy fog of Beijing I like to see the Sun ~ ~ ~ Good, loaded force to end ... Get to the point.

Development preparation:

1. Application for account in micro-credit open platform

2. After the success of the creation of applications, is to fill in some seemingly official very serious information ... (said audit 7 days or so, no accident in the case of your app the next day to audit success is not very happy, with the AppID, is it possible to call the micro-letter payment???? -------think too much, really.)

3. Micro-credit payment is required for additional applications: the need for data audit, account verification, agreement signing and other steps, (I remember, the data audit to fill in a lot of things,,, a lot of,,,, the account verification is your audit success after the micro-letter will send mail to your registration of registered mailbox account, which contains a random amount for account verification, Agreement signed, slightly, too simple) Be sure to read any information about your email, because some of the details are wrong, you may be landfills for a long time ...

Formal development phase:

Question 1:

Call the official SDK Discovery can only successfully tune a micro-letter, again pay the time how can not be called up

Solve:

Does not seem to be a serious method: in the mobile phone settings to manage the application, clear the micro-data, caching, and then again, absolutely can be adjusted (of course, just once ...). )

Go on:

I think it's going to be paid for by micro-mail, and just look at the documents that call the payment interface:
Later found that the required parameters Prepayid is how can not find Ah, and later found that this prepayid is first called "Unified under the single" interface when the warm turn of things, but the official SDK does not unify the order of the Code. Pit???

So first look at the unified document.

1. Use your own app call when the official website down the SDK wxpayentryactivity copy to their own projects, the name of the package must be the last. Wxapi (i handcuffed the bag ...) )

2. Fill in the project manifest file:

The Appregister in 3.SDK is copied down,, and replaced with your own AppID, and then registered in the list of items.
4. The point is, it's your app that's going to be paying for micro-letters, and I'm payactivity.

To tune up the micro-credit Payment page, in this activity, register your app to the micro-mail
Next, first call unified to get Prepayid, parameters, micro-trust people to XML format! We'll have to send the XML format!
When the call to the return of this method is worth the parameter pass, waiting for the micro-letter back to Success Bar!

Error I met: Signature error

My reason is careless. Configutil.notify_url This parameter writes an empty string

And because the debug version is running, there's no packaging running

After successful return, you can call the payment interface.

Don't forget this step to jump the interface,,,,,

No jump to micro-credit payment may be made by running the debug version,,,, and not packaged ....

Here's my payactivity complete code:

Package com.example.taijiapp.ui;
Import Java.io.StringReader;
Import java.net.InetAddress;
Import Java.net.NetworkInterface;
Import java.net.SocketException;
Import java.util.Enumeration;
Import Java.util.HashMap;
Import java.util.LinkedList;
Import java.util.List;
Import Java.util.Map;
 
Import Java.util.Random;
Import Org.apache.http.NameValuePair;
Import Org.apache.http.message.BasicNameValuePair;
 
Import Org.xmlpull.v1.XmlPullParser;
Import COM.EXAMPLE.TAIJIAPP.R;
Import com.example.taijiapp.util.Constants;
Import com.example.taijiapp.util.MD5;
Import com.example.taijiapp.util.t;
Import Com.example.taijiapp.util.Util;
Import Com.example.taijiapp.utils.ConfigUtil;
Import Com.tencent.mm.sdk.modelpay.PayReq;
Import Com.tencent.mm.sdk.openapi.IWXAPI;
 
Import Com.tencent.mm.sdk.openapi.WXAPIFactory;
Import android.app.Activity;
Import Android.app.ProgressDialog;
Import Android.content.Context;
Import Android.net.wifi.WifiInfo;
Import Android.net.wifi.WifiManager; Import Android.os.Asynctask;
Import Android.os.Bundle;
Import Android.util.Log;
Import android.util.Xml;
Import Android.view.View;
 
Import Android.widget.Button;
  public class Payactivity extends activity {payreq req;
  Private Iwxapi Msgapi;
  Map<string, string= "" > Resultunifiedorder;
  StringBuffer SB;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.pay);
    req = new Payreq ();
    SB = new StringBuffer ();
    Msgapi = Wxapifactory.createwxapi (this, constants.app_id);
    /** * To register APP to micro-letter/Boolean Registerapp = Msgapi.registerapp (constants.app_id);
    T.show (This, "Registered ========" +registerapp+ ");
    Button appaybtn = (button) Findviewbyid (R.ID.APPAY_BTN);
    Button check_pay_btn = (button) Findviewbyid (R.ID.CHECK_PAY_BTN); Appaybtn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {get Prepayidtask Getprepayid = new GETPREPAYIDTASK ();
      Getprepayid.execute ();
    }
    }); /** * will register the app to the micro-letter/Check_pay_btn.setonclicklistener (new View.onclicklistener () {@Override PU
        Blic void OnClick (View v) {genpayreq ();
         
      Sendpayreq ();
}
    });
Generate signature parameter//button APPAY_PRE_BTN = (Button) Findviewbyid (R.ID.APPAY_PRE_BTN); Appay_pre_btn.setonclicklistener (New View.onclicklistener () {////@Override//public void OnClick (View v)
  {//Genpayreq ();//}//}; /** * Generate signature */private String genpackagesign (list<namevaluepair> params) {StringBuilder sb = new S
 
    Tringbuilder ();
      for (int i = 0; i < params.size (); i++) {Sb.append (Params.get (i) getName ());
      Sb.append (' = ');
      Sb.append (Params.get (i). GetValue ());
    Sb.append (' & ');
    } sb.append ("key=");
    Sb.append (Constants.key);
    LOG.E ("Splicing =====", sb.tostring ()); String packagesign = md5.getmessagedigest (sb.tostrING (). GetBytes ()). toUpperCase ();
    LOG.E ("orion generation signature = = =", packagesign);
  return packagesign; /** * Signature tool does not include merchant key-Temporarily not = * Encoding format UTF-8 = * @return/public static String Createsignnokey (List<namevalue
 
    pair> params) {StringBuilder sb = new StringBuilder ();
      for (int i = 0; i < params.size (); i++) {Sb.append (Params.get (i) getName ());
      Sb.append (' = ');
      Sb.append (Params.get (i). GetValue ());
    Sb.append (' & ');
    String signstr = sb.tostring ();
    String subStr = signstr.substring (0, Signstr.length ()-1);
  Note that sign is converted to uppercase return Md5.getmessagedigest (Substr.getbytes ()). toUpperCase ();
 
    Private String genappsign (list<namevaluepair> params) {StringBuilder sb = new StringBuilder ();
      for (int i = 0; i < params.size (); i++) {Sb.append (Params.get (i) getName ());
      Sb.append (' = ');
      Sb.append (Params.get (i). GetValue ());
    Sb.append (' & ');
    } sb.append ("key="); Sb.append (COnstants.
 
    KEY);
    This.sb.append ("sign str\n" + sb.tostring () + "\ n");
    String appsign = Md5.getmessagedigest (Sb.tostring (). GetBytes ());
    LOG.E ("Orion", Appsign);
  return appsign;
    Private String toXml (list<namevaluepair> params) {StringBuilder sb = new StringBuilder ();
    Sb.append ("<xml>");
 
      for (int i = 0; i < params.size (); i++) {Sb.append ("<" + Params.get (i) getName () + ">");
      Sb.append (Params.get (i). GetValue ());
    Sb.append ("<!--" + params.get (i) getName () + "-->");
 
    } sb.append ("</xml>");
    LOG.E ("Orion", Sb.tostring ());
  return sb.tostring (); Private class Getprepayidtask extends Asynctask<void, void,= "map<string,=" "string=" ">> {privat
 
    e ProgressDialog Dialog; @Override protected void OnPreExecute () {dialog = Progressdialog.show (Payactivity.this, getString (r.string.app_
    TIP), getString (R.string.getting_prepayid)); } @OveRride protected void OnPostExecute (map<string, string= "" > Result) {if (dialog!= null) {DIALOG.D
      Ismiss ();
 
      } sb.append ("prepay_id\n" + result.get ("prepay_id") + "\ n \");
 
    Resultunifiedorder = result;
    } @Override protected void oncancelled () {super.oncancelled (); @Override protected Map<string, string= "" > Doinbackground (Void ... params) {string url = string.
      Format ("Https://api.mch.weixin.qq.com/pay/unifiedorder");
      String entity = Genproductargs ();
      LOG.E ("orion=== sent Past", entity);
 
      byte[] buf = util.httppost (URL, entity);
      String content = new string (BUF);
      LOG.E ("Orion", content);
 
      Map<string, string= "" > XML = decodexml (content);
    return XML; } public map<string, string= "" > Decodexml (String content) {try {map<string, string= "" > x
      ml = new hashmap<string, string= "" > (); Xmlpullparser parser = XML.NEWPUllparser ();
      Parser.setinput (content) (new StringReader);
      int event = Parser.geteventtype ();
        while (event!= xmlpullparser.end_document) {String nodename = Parser.getname ();
        Switch (event) {case XmlPullParser.START_DOCUMENT:break; Case XmlPullParser.START_TAG:if ("xml". Equals (nodename) = = False) {//Instantiate student object X
          Ml.put (NodeName, Parser.nexttext ());
        } break;
        Case XmlPullParser.END_TAG:break;
      event = Parser.next ();
    } return XML;
    catch (Exception e) {log.e ("Orion", E.tostring ());
 
  return null;
    /** * Generate random number * @return/private String gennoncestr () {Random Random = new Random ();
  Return Md5.getmessagedigest (string.valueof (Random.nextint (10000)). GetBytes ()); /** * Timestamp * @return/private Long Gentimestamp () {return system.currenttimemillis ()/1000;
    /** * Random number * @return/private String Genouttradno () {Random Random = new Random ();
  Return Md5.getmessagedigest (string.valueof (Random.nextint (10000)). GetBytes ()); /** * Get the IP address of the device * @return/Public String getlocalipaddress () {try {for Enumeration<networ Kinterface> en = networkinterface.getnetworkinterfaces (); En.hasmoreelements ();)
        {NetworkInterface intf = en.nextelement (); for (enumeration<inetaddress> enumipaddr = intf.getinetaddresses (); enumipaddr.hasmoreelements ();)
          {InetAddress inetaddress = enumipaddr.nextelement ();
          if (!inetaddress.isloopbackaddress ()) {return inetaddress.gethostaddress (). toString ();
  The catch (SocketException ex) {} return null; Private String Getwifiip () {//Get WiFi service Wifimanager Wifimanager = (wifimanager) getsystemservice (context.wi
    Fi_service); Determine if WiFi is open if (!wifimanageR.iswifienabled ()) {wifimanager.setwifienabled (true);
    } wifiinfo Wifiinfo = Wifimanager.getconnectioninfo ();
    int ipaddress = wifiinfo.getipaddress ();
    String IP = Inttoip (ipaddress);
  return IP; /** * Convert to IP address format * @param i * @return/private String Inttoip (int i) {return (I & 0xFF) + "
  . "+ ((I >> 8) & 0xFF) +". "+ ((I >>) & 0xFF) +". "+ (I >> & 0xFF);
    Private String Genproductargs () {stringbuffer xml = new StringBuffer ();
    String IP = GETWIFIIP ();
    if (IP = = "" && IP = = "") {IP = getlocalipaddress ();
      try {String noncestr = Gennoncestr ();
      Xml.append ("");
      list<namevaluepair> packageparams = new linkedlist<namevaluepair> ();
      Packageparams.add (New Basicnamevaluepair ("AppID", constants.app_id));
      Packageparams.add (New Basicnamevaluepair ("Body", "apptest")); Packageparams.add (New Basicnamevaluepair ("mch_id"), constants.mch_id));
      Packageparams.add (New Basicnamevaluepair ("Nonce_str", Noncestr));
      Packageparams.add (New Basicnamevaluepair ("Notify_url", Configutil.notify_url));
      Packageparams.add (New Basicnamevaluepair ("Out_trade_no", Genouttradno ());
      Packageparams.add (New Basicnamevaluepair ("Spbill_create_ip", IP));
      Packageparams.add (New Basicnamevaluepair ("Total_fee", "100"));
      Packageparams.add (New Basicnamevaluepair ("Trade_type", "APP"));
      String sign = genpackagesign (packageparams);
      Packageparams.add (New Basicnamevaluepair ("sign", sign));
      String xmlstring = toXml (packageparams);
    return xmlstring;
      catch (Exception e) {log.e ("TAG", "fail, ex =" + E.getmessage ());
    return null;
    }} private void Genpayreq () {req.appid = constants.app_id;
    Req.partnerid = constants.mch_id;
    Req.prepayid = Resultunifiedorder.get ("prepay_id");
Req.packagevalue = "prepay_id=" + resultunifiedorder.get ("prepay_id");    Req.noncestr = Gennoncestr ();
    Req.timestamp = string.valueof (Gentimestamp ());
    list<namevaluepair> signparams = new linkedlist<namevaluepair> ();
    Signparams.add (New Basicnamevaluepair ("AppID", Req.appid));
    Signparams.add (New Basicnamevaluepair ("Noncestr", Req.noncestr));
    Signparams.add (New Basicnamevaluepair ("package", Req.packagevalue));
    Signparams.add (New Basicnamevaluepair ("Partnerid", Req.partnerid));
    Signparams.add (New Basicnamevaluepair ("Prepayid", Req.prepayid));
    Signparams.add (New Basicnamevaluepair ("timestamp", Req.timestamp));
    Req.sign = Genappsign (signparams);
    Sb.append ("sign\n" + req.sign + "\ n");
 
  LOG.E ("orion==genpayreq===============", signparams.tostring ());
    private void Sendpayreq () {Boolean sendreq = Msgapi.sendreq (req);
  T.show (This, "micro-letter Jump =====" "+sendreq+"); }} </namevaluepair></namevaluepair></namevaluepair></namevaluepair></inetaddress> </networkinterface></string,></string,></string,></string,></string,></string,></ Void,></namevaluepair></namevaluepair></namevaluepair></namevaluepair></string,
 >

There is no class,,,, na: source download. Download your own copy ...

Reference article: http://www.jb51.net/article/97712.htm

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.