Android calls WeChat for login, sharing, payment, and android calls

Source: Internet
Author: User

Android call login, sharing, payment, android call

It is much more troublesome to use the sdk than to call the qq sdk, And the callback is too troublesome. The actvity under the specified package must also be called back, so I am writing a blog here. If you have this need, you can learn from it. In the future, you will find some useful information for other projects.


I. logon involves three steps:

1). Authorize Login
2). Obtain the User token Based on the authorized login code.
3). obtain user information based on the token
4). The received request and return value. If your program needs to receive the sent request or the response result sent to the request, perform the following three steps:

A. create a wxapi directory under the corresponding directory of your package name, and add a WXEntryActivity class under the wxapi directory. This class inherits from Activity (for example, the package name of the application is net. sourceforge. simcpux,

Shows the newly added class)

Add the exported attribute to the manifest file and set it to true. For example:

B. Implement the IWXAPIEventHandler interface. The sent request is called back to the onReq method, and the response result sent to the request is called back to the onResp method.
C. In WXEntryActivity, pass the received intent and the object implementing the IWXAPIEventHandler interface to the handleIntent method of the iwxapi interface, for example:

Official 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

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


2. directly call the sdk for sharing. The callback class is the same as the login callback class. It is used to distinguish between login and sharing based on the BaseResp type.


Iii. Payment

1). Send a payment request

2). Receive the return value of the payment (similar to receiving the return value of login. share, I will not write the detailed operation steps)

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


4. paste the code to explain

I have encapsulated login, share, and payment into a class. You can refer to this class and encapsulate 6 methods. I will introduce several required methods.

1) constructor: When initializing an object, initialize the object and register the app_id

2). login () initiates a login request to obtain the code from the login listening Actviity.

3). getAccessToken (String code) after you obtain the code from the listening Activity, you can use this method to obtain the access token.

4). getWeiXinUserInfo (final WeiXinToken obj) gets user information and passes in a WeiXinToken object, which is the return value of step 3.

5). share (final boolean friendsCircle, final VideoB videoB) share images with friends or friends. If you share images, compress the images when they are too large.

At 32 KB

6). isWXAppInstalled () Check for Installation

7). wxPay (final BaseActivity, String order_id, String payType): Some parameters for payment of our project are saved on the server, so I also requested my own

Server. If you store the code locally, you can directly copy the code in the callback function. In the payment listening Actviity, obtain the payment status code.

For the meaning of PayReq class properties, see the official documentation: https://pay.weixin.qq.com/wiki/doc/api/app.php? Chapter = 9_12

/*** Share, log on, and pay * @ author ansen * @ create time 2015-08-29 */public class WeiXinPresenter extends Presenter {public static final int IMAGE_SIZE = 32768; // The size of the shared image is limited to public static final String APP_ID = ""; // unique ID of the application. The public static final String SECRET = "" is obtained after the application is submitted for approval on the open platform ""; // AppSecret of the application key, which is obtained after the application is submitted to the open platform for approval by private IWXAPI wxAPI; private IView iView; private IUserController userController; @ Overridepublic IView getIView () {Return iView;} public WeiXinPresenter (Context context) {if (context! = Null & context instanceof IView) iView = (IView) context; if (wxAPI = null) {wxAPI = wxapifacloud. createWXAPI (context, APP_ID, true); wxAPI. registerApp (APP_ID);} if (null = userController) userController = ControllerFactory. getUserController ();}/*** login (three steps) * 1. authorize logon * 2. obtain the user's token based on the authorized login code * 3. obtain user information * @ param activity */public void login () {SendAuth. req req = new SendAuth. req (); req. scope = "snsapi_u Serinfo "; req. state = String. valueOf (System. currentTimeMillis (); wxAPI. sendReq (req);}/*** get access token */public void getAccessToken (String code) {if (! UserController. isLogin () {// use a third party to log on to userController if no logon is found. getWeiXinAccessToken (APP_ID, SECRET, code, new RequestDataCallback <WeiXinToken> () {@ Overridepublic void dataCallback (WeiXinToken obj) {if (obj! = Null) {if (obj. getErrcode () = 0) {if (MLog. debug) iView. showToast ("Unique ID of the authorized user:" + obj. getOpenid (); getWeiXinUserInfo (obj);} else {iView. showToast (obj. getErrmsg () ;}} else {}}});} else {// user logged in}/*** get user information */private void getWeiXinUserInfo (final WeiXinToken obj) {userController. getWeiXinUserInfo (obj. getAccess_token (), obj. getOpenid (), new RequestDataCallback <RegisterB> () {@ Overridepublic void dataCallback (Register B 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 to log on * @ param registerB */private void thirdLogin (RegisterB registerB) {userController. thirdAuth (registerB, new RequestData Callback <UserP> () {@ Overridepublic void dataCallback (UserP 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 () ;}}});}/*** share * @ param friendsCircle whether to share to your friends */ Public void share (final boolean friendsCircle, final VideoB videoB) {new LoadPicThread (videoB. getCover_url (), new Handler () {@ Overridepublic void handleMessage (Message msg) {byte [] bytes = (byte []) msg. obj; if (bytes. length> IMAGE_SIZE) {iView. showToast (R. string. image_no_big); return;} System. out. println ("image length:" + bytes. length); WXVideoObject videoObject = new WXVideoObject (); // video type videoObject. videoUrl = videoB. Get1__url () + Constants. WEI_XIN + "& polic_from =" + com. kaka. utils. constants. ANDROID; // video playback urlWXMediaMessage wxMessage = new WXMediaMessage (videoObject); wxMessage. title = videoB. getContent (); wxMessage. thumbData = bytes; SendMessageToWX. req req = new SendMessageToWX. req (); // The transaction field uniquely identifies a request req. transaction = String. valueOf (videoB. getId () + System. currentTimeMillis (); req. message = wxMessage; r Eq. 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;} @ Overridepublic void run () {try {URL picurl = new URL (url); HttpURLConnection conn = (HttpURLConnection) picurl. openConnection (); // Obtain the connection conn. setConnectTimeout (6000); // set the 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, 100, output); int options = 100; while (output. toByteArray (). length> IMAGE_SIZE & options! = 10) {output. reset (); // clear baosbmp. compress (Bitmap. compressFormat. JPEG, options, output); // compress options % here and store the compressed data in 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 whether public boolean isWXAppInstalled () {return wxAPI is installed. isWXAppInstalled ();} public void wxPay (final BaseActivity activity, String order_id, String payType) {activity. showProgress (""); ControllerFactory. getWalletsController (). getPayments (order_id, payType, new RequestDataCallback <PaymentsP> () {@ Overridepublic void dataCallback (PaymentsP obj) {if (checkCallbackData (obj, true) {if (obj. getError () = obj. errorNone) {PayReq req = new PayReq (); // the req to be modified. 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 to pay .. "); iView. showToast ("start to pay .. ") ;}} else {iView. showToast (obj. getError_reason ();} activity. hideProgress ();}});}}


Login and receiving of sharing requests and return values login. The sharing status is broadcast and the current Activity is ended.

/*** Login share callback Activity * @ author ansen * @ create time 2015-05-25 */public class WXEntryActivity extends Activity implements extends {private IWXAPI wxAPI; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); if (MLog. debug) System. out. println ("WXEntryActivity onCreate"); wxAPI = wxapifacloud. createWXAPI (this, WeiXinPresenter. APP_ID, true); wxAPI. regist ErApp (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");} @ Overridepublic void onReq (BaseReq arg0) {if (MLog. debug) System. out. println ("WXEntryActivity onReq:" + arg0); if (MLog. debug) Toast. makeText (this, "on Run the Req method ", 0 ). show () ;}@ Overridepublic void onResp (BaseResp resp) {MLog. d ("ansen", "onResp ..... "); if (MLog. debug) Toast. makeText (this, "onResp method running", 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, "shared successfully! ", Toast. LENGTH_SHORT). show (); break; case BaseResp. ErrCode. ERR_USER_CANCEL: // Toast. makeText (WXEntryActivity. this," cancel sharing! ", 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) {// log on to 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) {// The User agrees to intent. putExtra ("code", code);} if (MLog. debug) Toast. makeText (this, "WXEntryActivity sends a login broadcast !!!! ", 0 ). show (); if (android. OS. build. VERSION. SDK_INT> = 12) {intent. setFlags (32); // Intent needs to be set for Versions later than 3.1. FLAG_INCLUDE_STOPPED_PACKAGES} LocalBroadcastManager lbm = LocalBroadcastManager. getInstance (this); lbm. sendBroadcast (intent) ;}finish ();}}


The receiving and payment of the payment request and return value are also broadcast messages. If you still need to determine whether the payment is successful or fails, you can transmit parameters in the broadcast intent.

/*** Payment callback Activity ** @ author ansen * @ create time 2015-08-29 */public class WXPayEntryActivity extends Activity implements extends {private IWXAPI wxAPI; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); wxAPI = wxapifacloud. createWXAPI (this, WeiXinPresenter. APP_ID); wxAPI. handleIntent (getIntent (), this) ;}@ Override protected void onNewIntent (Intent intent) {super. onNewIntent (intent); setIntent (intent); wxAPI. handleIntent (intent, this) ;}@ Overridepublic void onReq (BaseReq arg0) {}@ Overridepublic void onResp (BaseResp resp) {MLog. I ("Payment callback .. "," ansen onResp "); if (resp. getType () = ConstantsAPI. COMMAND_PAY_BY_WX) {// payment callback if (resp. errCode = BaseResp. errCode. ERR_ OK) {// The payment is 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 ();}}


Note that you must pay attention to the received request and the returned package name and class name. The package name is the package name of the application + ". wxapi "class name must be the specified class name and the two activities must be in AndroidManifest. register in xml, upload a package name and Class Name of the app I made



How to call login in activity

1) log on to the internal class of the broadcast listener and obtain the token if the broadcast is received.

Private class WXEntryReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {MLog. I ("WXEntryReceiver", "receive login broadcast"); if (MLog. debug) showToast ("receive login 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

    private WXEntryReceiver wxEntryReceiver=null;


3). Register broadcast in oncreate

// Log on to the broadcast wxentrycycler = new wxentrycycler (); LocalBroadcastManager lbm = LocalBroadcastManager. getInstance (this); IntentFilter filter = new IntentFilter (); filter. addAction (APIDefineConst. BROADCAST_ACTION_WEIXIN_TOKEN); lbm. registerReceiver (wxEntryReceiver, filter );

4). Call Login

    WeiXinPresenter xinTestPresenter=new WeiXinPresenter(this);    xinTestPresenter.login();


I will not post the code for calling share and call payment in the Activity. This blog is just for your reference. If you have any problems, we recommend that you read the official documentation as soon as possible.


About the problems I encountered during login

1. The activity package name and class name for login, sharing, and payment callback must be written in strict accordance with requirements

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

3. WeiXinPresenter has two constants, APP_ID and SECRET, which are available only when you apply for them. You must assign values to these two constants when copying code.

4. You may need some permissions to access the network. Remember to add permissions in AndroidManifest. xml.

5. You must have a signature for the login, sharing, and payment of the call to your installation package. The signature information must be consistent with the signature information you applied for on the official website.

6. No customer service support ..... If any problem occurs, check the official demo or official API.

7. the sdk is updated frequently. If you have the latest version during development, use the latest version .....


After talking so much, I feel like I have talked a lot of nonsense... I hope I can help you... if you have any questions, I can leave a message ....


I uploaded an sdk jar package on csdn, you can download: http://download.csdn.net/detail/lowprofile_coding/9061367


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.