Android calls micro-letter login, share, pay _android

Source: Internet
Author: User
Tags unique id

With the micro-mail SDK all kinds of pain, feel more trouble than QQ SDK call, callback is too troublesome, but also must be in the name of the designated package Actvity callback, so I write a blog here, there is a need for friends can learn from, and later their other projects useful to have a look for information.

A. Micro-letter landing is divided into three steps:

1). Micro-Letter Authorization Login
2. According to the authorization login code to obtain the user token
3). Obtain user information according to token
4. Receive micro-letter request and return value if your program needs to receive a request from a micro-letter or receive a response to a micro-letter request, the following 3 steps are required:

A. Create a new Wxapi directory in the appropriate directory of your package name and add a wxentryactivity class to the Wxapi directory, which inherits from activity (for example, the package name of the application is Net.sourceforge.simcpux,

The newly added class is shown in the following illustration)

and add the exported attribute to the manifest file, set to True, for example:

B. Implement the Iwxapieventhandler interface, the request sent by the micro-mail will be recalled to the Onreq method, and the response sent to the micro-letter request will be recalled to the Onresp method
C. Intent received in wxentryactivity and objects that implement the Iwxapieventhandler interface are passed to the Iwxapi interface Handleintent method, as shown in the following illustration:

Micro-Letter Website Login Tutorial: Https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1 &id=open1419317851&token=&lang=zh_cn

Micro-letter Official website Access Guide: Https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1 &id=1417751808&token=&lang=zh_cn

Two. Micro-letter sharing directly invoke the SDK on the line, callback and login callback class is the same, according to the type of baseresp to distinguish between landing or sharing.

Three. Micro-credit Payment

1). Send a payment request

2. Receive the return value of the micro-letter payment (with the receive micro-letter login.) The return value of the share is similar, I do not write the detailed procedure.

Official website Reference address: https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=8_5

Four. Put the code to explain

I landed, shared, and paid into a class, and you can refer to this class. 6 methods are encapsulated, and I'll introduce you to a few of the methods I need.

1. Construction method: Initializing the object, by the way of initializing the micro-object, the APP_ID register to the micro-letter

2. Login () initiate a login request to get code in the micro-mail login monitor actviity

3). Getaccesstoken (String code) after you have obtained the code from the listening activity, you can obtain the micro-access token by this method.

4). Getweixinuserinfo (final Weixintoken obj) gets the micro-subscriber information to pass in a Weixintoken object, which is the return value of the third step

5). Share (Final Boolean friendscircle,final videob videob) share to friends or friends if you have to share the picture, the picture is too large must be compressed, micro-letter official website description picture can not be big

In 32KB

6). iswxappinstalled () Check whether the micro-letter is installed

7. Wxpay (Final baseactivity activity,string order_id,string paytype) micro-letter payment for our project micro-credit some of the parameters are saved on the server, so I also asked for my own

Server, if you are placed locally, direct copy of the callback function inside the code can. Get payment status code in micro-credit payment listening actviity

Payreq class attribute corresponding meaning please refer to the micro-letter Official document: Https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_12

/** * Micro-letter sharing, landing, payment * @author Ansen * @create Time 2015-08-29/public class Weixinpresenter extends presenter{ public static final int image_size=32768;//micro letter share picture size limit public static final String app_id = "";//apply unique ID, after application approval is submitted on the micro-trust platform 
  Obtains the public static final String secret= "";//Application key Appsecret, after the micro-letter open platform submitted application audit to obtain private IWXAPI wxapi; 
  Private IView IView; 
   
  Private Iusercontroller Usercontroller; 
  @Override public IView Getiview () {return IView; } public Weixinpresenter {if (context!=null && context instanceof IView) IView 
    = (IView) context; 
      if (wxapi==null) {Wxapi = Wxapifactory.createwxapi (context,app_id,true); 
    Wxapi.registerapp (app_id); 
  } if (Null==usercontroller) Usercontroller=controllerfactory.getusercontroller (); 
   /** * Micro-letter Landing (three steps) * 1. Micro-Letter Authorization to login * 2. Obtain the user token * 3 According to the authorized login code. * To obtain user information according to token * @param activity 
    */public void login () {Sendauth.req Req = new Sendauth.req (); 
    Req.scope = "Snsapi_userinfo"; 
    Req.state = string.valueof (System.currenttimemillis ()); 
  Wxapi.sendreq (req); /** * Obtain micro-access token/public void Getaccesstoken (String code) {if (!usercontroller.islogin ()) {//No login 
        Land in the case of a third party landing Usercontroller.getweixinaccesstoken (App_id,secret,code,new requestdatacallback<weixintoken> () { @Override public void Datacallback (Weixintoken obj) {if (obj!=null) {if (Obj.geterrco 
              De () ==0) {if (mlog.debug) Iview.showtoast ("authorized user uniquely identified:" +obj.getopenid ()); 
            Getweixinuserinfo (obj); 
            }else{Iview.showtoast (Obj.geterrmsg ()); 
    }}else{}}); }else{//user has landed}/** * access to micro-credit user information/private void Getweixinuserinfo (final Weixintoken obj ) {Usercontroller.getweixinuserinfo (Obj.getacCess_token (), Obj.getopenid (), new requestdatacallback<registerb> () {@Override public void Datacallba 
        CK (Registerb registerb) {Registerb.setaccess_token (Obj.getaccess_token ()); 
        Registerb.settoken_expire_at (Obj.getexpires_in ()); 
          if (Registerb.geterrcode () ==0) {registerb.setthird_type_name (constants.wei_xin); 
        Thirdlogin (Registerb); 
        }else{Iview.showtoast (Registerb.geterrmsg ()); 
  } 
      } 
    }); /** * Call our own server for login * @param registerb * * private void Thirdlogin (Registerb registerb) {User Controller.thirdauth (registerb,new requestdatacallback<userp> () {@Override public void Datacallback (Us ErP User {if (checkcallbackdata (user, True)) {if (User.geterror ()) ==user. 
            Errornone) {iview.showtoast (r.string.login_success); 
            Getappcontroller (). Sendloginchangeintent (); Usercontroller.saveloginuser (USer,fileutil.getfilepath ()); 
          ((Iloginview) iView). Tomain (); 
          }else{Iview.showtoast (User.geterror_reason ()); 
  } 
        } 
      } 
    }); /** * Micro-letter Sharing * @param friendscircle whether to share the circle of friends/public void Share (final Boolean friendscircle,final Videob videob) {New Loadpicthread (Videob.getcover_url (), new Handler () {@Override public void handlemess 
        Age (MSG) {byte[] bytes= (byte[]) msg.obj; 
          if (bytes.length>image_size) {iview.showtoast (r.string.image_no_big); 
        Return 
        } System.out.println ("Picture length:" +bytes.length); Wxvideoobject videoobject = new Wxvideoobject ()//video Type Videoobject.videourl = Videob.getshare_url () + Constants.W Ei_xin + "&share_from=" +com.kaka.utils.constants.android;//video playback URL wxmediamessage wxmessage = new WXMediaMes 
        Sage (videoobject); 
        Wxmessage.title = Videob.getcontent (); WxmessAge.thumbdata = bytes; 
        Sendmessagetowx.req Req = new Sendmessagetowx.req (); 
        The transaction field is used to uniquely identify a request Req.transaction = String.valueof (Videob.getid () + System.currenttimemillis ()); 
        Req.message = Wxmessage; Req.scene = friendscircle? 
        SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession; 
      Wxapi.sendreq (req); 
  }). Start (); 
    Private class Loadpicthread extends thread{private String URL; 
    Private Handler Handler; 
      Public Loadpicthread (String Url,handler Handler) {this.url=url; 
    This.handler=handler;  
        @Override public void Run () {try {URL picurl = new URL (URL); HttpURLConnection conn = (httpurlconnection) picurl.openconnection ();  
        Get connection Conn.setconnecttimeout (6000);//Set timeout Conn.setdoinput (true); 
        Conn.setusecaches (false);//Do not cache conn.connect (); Bitmap Bmp=bitmapfactory.decodestream (Conn.getInputStream ());          
        Bytearrayoutputstream output = new Bytearrayoutputstream (); 
        Bmp.compress (Bitmap.CompressFormat.JPEG, Output); 
        int options = 100; 
          while (Output.tobytearray (). length > Image_size && options!=) {output.reset ();//Empty BAOs  
        Bmp.compress (Bitmap.CompressFormat.JPEG, options, Output),//Here compressed options%, the compressed data stored in the BAOs options-= 10; 
        } bmp.recycle (); 
        Byte[] result = Output.tobytearray (); 
         
        Output.close (); 
        Message Message=handler.obtainmessage (); 
        Message.obj=result; 
      Message.sendtotarget (); 
      catch (Exception e) {e.printstacktrace (); 
  Check to see if the micro-letter is installed public boolean iswxappinstalled () {return wxapi.iswxappinstalled (); 
    } public void Wxpay (final baseactivity activity,string order_id,string paytype) {activity.showprogress (""); ControllerfactoRy.getwalletscontroller (). GetPayments (order_id, PayType, New requestdatacallback<paymentsp> () {@Override public void Datacallback (paymentsp obj) {if (Checkcallbackdata (obj, True) {if (Obj.geterror () ==obj . 
            Errornone) {Payreq req = new Payreq ();/To be modified Req.appid = Obj.getappid (); 
            Req.noncestr=obj.getnoncestr (); 
            Req.packagevalue=obj.getpackage_value (); 
            Req.sign=obj.getsign (); 
            Req.partnerid=obj.getpartnerid (); 
            Req.prepayid=obj.getprepayid (); 
             
            Req.timestamp=obj.gettimestamp (); 
            Wxapi.registerapp (Obj.getappid ()); 
             
            Wxapi.sendreq (req); 
            MLOG.I ("Ansen", "Start a micro-letter payment ..."); 
          Iview.showtoast ("Start a micro-letter payment ..."); 
        }}else{Iview.showtoast (Obj.geterror_reason ()); 
      } activity.hideprogress (); 
  } 
    });  } 
}

Micro-mail login and share request with return value    I'm landing here. The state of sharing is to send the broadcast out and then end the current activity.

/** * Micro-letter Login Share callback activity * @author Ansen * @create Time 2015-05-25/public class Wxentryactivity extends Activit 
   
  Y implements iwxapieventhandler{private Iwxapi Wxapi; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    if (mlog.debug) System.out.println ("Wxentryactivity onCreate"); 
    Wxapi = Wxapifactory.createwxapi (this,weixinpresenter.app_id,true); 
     
    Wxapi.registerapp (weixinpresenter.app_id); 
  Wxapi.handleintent (Getintent (), this); 
    } @Override protected void Onnewintent (Intent Intent) {super.onnewintent (Intent); 
    Wxapi.handleintent (Getintent (), this); 
  if (mlog.debug) System.out.println ("Wxentryactivity onnewintent"); @Override public void Onreq (Basereq arg0) {if (mlog.debug) System.out.println ("Wxentryactivity onreq:" 
    +ARG0); 
  if (mlog.debug) Toast.maketext (This, "Onreq method Run", 0). Show (); @Override Public VOID onresp (Baseresp resp) {mlog.d ("Ansen", "Onresp ..."); 
    if (mlog.debug) Toast.maketext (This, "Onresp method Run", 0). Show (); if (Resp.gettype () ==constantsapi.command_sendmessage_to_wx) {//share switch (resp.errcode) {case Baseresp.errcode . 
        Err_ok:if (Mlog.debug) toast.maketext (Wxentryactivity.this, "share success!", Toast.length_short). Show (); 
      Break Case BaseResp.ErrCode.ERR_USER_CANCEL://Toast.maketext (Wxentryactivity.this, "Share cancellation!", Toast.length_short). Show () 
        ; 
      Break 
      Case BaseResp.ErrCode.ERR_AUTH_DENIED:break; 
      } Intent Intent = new Intent (); 
        Intent.setaction (Apidefineconst.broadcast_action_weixin_share); 
        Localbroadcastmanager LBM = Localbroadcastmanager.getinstance (this); 
    Lbm.sendbroadcast (Intent); 
      }else if (Resp.gettype () ==constantsapi.command_sendauth) {//Login send broadcast Sendauth.resp AUTHRESP = (resp) resp; String Code = authresp.coDe 
      Intent Intent = new Intent (); 
      Intent.setaction (Apidefineconst.broadcast_action_weixin_token); 
      Intent.putextra ("Errcode", Authresp.errcode); 
      if (Authresp.errcode = = BaseResp.ErrCode.ERR_OK) {//user agrees to Intent.putextra ("code", code); 
        } if (Mlog.debug) Toast.maketext (this, "wxentryactivity send landing broadcast!!!!", 0). Show (); if (Android.os.Build.VERSION.SDK_INT >=) {intent.setflags (32);//3.1 later versions need to be set intent.flag_include_stopped 
        _packages} Localbroadcastmanager LBM = Localbroadcastmanager.getinstance (this); 
    Lbm.sendbroadcast (Intent); 
  Finish (); } 
}

Micro-Credit payment request and return value of the receive    micro-payment is also sent broadcast, if you still have the demand to judge the payment success or failure, you can in the broadcast intent to participate in the message

/** * Micro-Credit Payment callback activity * @author Ansen * @create Time 2015-08-29/public class Wxpayentryactivity extends Activi 
   
  Ty implements iwxapieventhandler{private Iwxapi Wxapi; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Wxapi = Wxapifactory.createwxapi (this, weixinpresenter.app_id); 
  Wxapi.handleintent (Getintent (), this); 
    } @Override protected void Onnewintent (Intent Intent) {super.onnewintent (Intent); 
    Setintent (Intent); 
  Wxapi.handleintent (Intent, this); @Override public void Onreq (Basereq arg0) {} @Override public void Onresp (Baseresp resp) {ML 
    OG.I ("micro-credit payment callback ...", "Ansen Onresp"); 
        if (resp.gettype () = = CONSTANTSAPI.COMMAND_PAY_BY_WX) {//micro-letter Payment callback if (RESP.ERRCODE==BASERESP.ERRCODE.ERR_OK) {//micro-letter Payment Successful 
        Intent Intent = new Intent (); 
          Intent.setaction (Apidefineconst.broadcast_action_weixin_pay); Localbroadcastmanager LBM = Localbroadcastmanager.getinstance (this); 
        Lbm.sendbroadcast (Intent); 
      Success//Toast.maketext (this,r.string.wxpay_success, 0). Show (); 
      }else{//Toast.maketext (this,r.string.wxpay_success, 0). Show (); 
  } finish ();  } 
   
}

It is important to note that the packet name and the class name that receive the micro-letter request and return value, the package name is the application's package name + ". Wxapi" class name must be a micro-letter specified class name and these two activity must be registered in Androidmanifest.xml, Upload a screenshot of the package name and class name that I made in the app

How to invoke a micro-letter login in an activity

1. Login broadcast listening internal class if you receive a broadcast, you get a micro-letter token.

Private class Wxentryreceiver extends Broadcastreceiver { 
  @Override public 
  void OnReceive Intent Intent) { 
    mlog.i ("Wxentryreceiver", "receiving micro-letter landing broadcast"); 
    if (mlog.debug) 
      showtoast ("Receive micro-letter landing broadcast"); 
    if (Intent.getaction (). Equals (Apidefineconst.broadcast_action_weixin_token)) { 
      int errcode = Intent.getextras () . GetInt ("Errcode"); 
      if (mlog.debug) 
        System.out.println ("Get Error code:" +errcode); 
      if (errcode==baseresp.errcode.err_user_cancel| | errcode==baseresp.errcode.err_auth_denied) { 
        requestdatafinish (); 
      } else{ 
        String code = Intent.getextras (). getString ("code"); 
        Xintestpresenter.getaccesstoken (code);}} 
   

2). Define member variables

 
 

3). Register for broadcast in OnCreate

Micro-letter Landing broadcast 
wxentryreceiver= new Wxentryreceiver (); 
Localbroadcastmanager LBM = Localbroadcastmanager.getinstance (this); 
Intentfilter filter = new Intentfilter (); 
Filter.addaction (Apidefineconst.broadcast_action_weixin_token); 

4). Call micro-letter Landing

Weixinpresenter xintestpresenter=new Weixinpresenter (this); 

Call in the activity of micro-letter sharing and calling the micro-letter payment code I will not post, I this blog just to give you a reference to the place, encounter problems or suggest the first time to see the official document.

Tell me about the problem I'm doing on the micro-mail landing.

1. Micro-letter landing, sharing, payment callback of the activity package name and class name must be strictly in accordance with the requirements to write

2. The activity that receives the callback is the activity must be registered in the Androidmanifest.xml

There are two constants in 3.WeiXinPresenter app_id and secret have to go to the micro-letter application. When you copy code, you assign these two constants

4. May visit the Network God Horse also needs some privileges remember to add permissions in Androidmanifest.xml

5. Call the micro-letter landing, sharing, payment your installation package must have a signature, the signature information must be with you on the micro-trust Web application signed information consistent with

6. Micro-letter without customer service support .... If there's a problem, see the official demo or the official API

7. Micro-mail SDK is often upgraded, if you have the latest development of the latest bar ...

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.