微信API自动登录流程

登录步骤[1]:

1. 申请APP KEY

在开放平台上注册应用即可获取。

2. 导入jar包

导入libammsdk.jar即可。

3. 添加权限

<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

4. 创建WXEntryActivity类

- 在包名相应目录下新建一个wxapi目录,并在该wxapi目录下新增一个WXEntryActivity类,该类继承自Activity

- 在manifest文件里面加上exported属性,设置为true

- 实现IWXAPIEventHandler接口

@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("onActivityResult");
    }

    @Override
    public void onReq(BaseReq arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "onReq", Toast.LENGTH_SHORT).show();
        System.out.println("onReq");
    }

    @Override
    public void onResp(BaseResp arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "onResp", Toast.LENGTH_SHORT).show();
        SendAuth.Resp authResp = (SendAuth.Resp) arg0;
        System.out.println("onResp code:" + authResp.code);
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/sns/oauth2/access_token");
        sb.append("?appid=");
        sb.append(APP_ID);
        sb.append("&secret=");
        sb.append(SECRET);
        sb.append("&code=");
        sb.append(authResp.code);
        sb.append("&grant_type=authorization_code");
        String url = sb.toString();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        //新开一个activity,用Volley发送请求,用code换回access_token、refresh_token、expires_in和openid
        Intent intent = new Intent(WXEntryActivity.this, WeixinActivity2.class);
        intent.putExtras(bundle);
        System.out.println("url:"+url);
        startActivity(intent);
        this.finish();
    }

注意:由于某种未知的原因,WXEntryActivity在执行onresp后会自行销毁并重新生成,然后重新执行onCreate方法。我的方法是在onCreate中加判断条件,并在一定条件下将activity自动销毁。
什么是refresh_token?
但是OAuth2.0为了增强安全性,access token的有效期被大大缩短,通常只有几个小时,也可以申请增加到几十天,但是总是会有过期的时候。为此,OAuth2.0增加了一个refresh token的概念,这个token并不能用于请求api.它是用来在access token过期后刷新access token的一个标记。[2]
什么是openid?
OpenID (OID) is an open standard and decentralized protocol by the non-profit OpenID Foundation that allows users to be authenticated by certain co-operating sites (known as Relying Parties or RP) using a third party service. This eliminates the need for webmasters to provide their own ad hoc systems and allowing users to consolidate their digital identities[3].
新的activity中的相关代码:

@Override
private void sendRequest(String url) {
        // TODO Auto-generated method stub
        System.out.println("Sending request");
        JsonObjectRequest req = new JsonObjectRequest(url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("response:" + response.toString());
                        String artiwaresUrl = "http://www.artiwares.com:8080/account/social_account/";
                        HashMap map = new HashMap();
                        map.put("platform", "wechat");
                        try {
                            map.put("access_token",
                                    response.getString("access_token"));
                            map.put("expires_in",
                                    response.getString("expires_in"));
                            map.put("refresh_token",
                                    response.getString("refresh_token"));
                            map.put("openid", response.getString("openid"));
                            System.out.println("JSONException:"
                                    + response.getString("access_token"));
                            System.out.println("expires_in:"
                                    + response.getString("expires_in"));
                            System.out.println("refresh_token:"
                                    + response.getString("refresh_token"));
                            System.out.println("openid:"
                                    + response.getString("openid"));
                        } catch (JSONException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                            System.out
                                    .println("JSONException:" + e1.toString());
                        }

                        JSONObject params = new JSONObject(map);
                        CookieRequest result = new CookieRequest(
                                Request.Method.POST, artiwaresUrl, params,
                                new Response.Listener() {
                                    @Override
                                    public void onResponse(JSONObject arg0) {
                                        System.out.println("Login success!");
                                        System.out.println("arg0:"
                                                + arg0.toString());
                                    }
                                }, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(
                                            VolleyError error) {
                                        // error
                                        System.out.println("VolleyError:"
                                                + error.toString());

                                    }
                                });
                        mQueue.add(result);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("Error: " + error.getMessage());
                    }
                });
        System.out.println("url2:" + url);
        mQueue.add(req);
    }

实现 WeiboAuthListener 接口

class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle values) {
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            System.out.println("token:" + mAccessToken.getToken());
            System.out.println("values:" + values.toString());
            if (mAccessToken.isSessionValid()) {

                Toast.makeText(WeiboActivity.this,
                        "weibosdk_demo_toast_auth_success", Toast.LENGTH_SHORT)
                        .show();
            } else {
                String code = values.getString("code");
                String message = "weibosdk_demo_toast_auth_failed";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(WeiboActivity.this, message, Toast.LENGTH_LONG)
                        .show();
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(WeiboActivity.this,
                    "weibosdk_demo_toast_auth_canceled", Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(WeiboActivity.this,
                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

创建WXAPI:

IWXAPI api = WXAPIFactory.createWXAPI(this, APP_ID, false);
api.handleIntent(getIntent(), this);

以上过程可在WXEntryActivity的onCreate方法中执行。注意:在发出请求之前需要先生成WXEntryActivity的实例,否则onResp方法不会被调用。

发送请求:

api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);
        final com.tencent.mm.sdk.modelmsg.SendAuth.Req req = new com.tencent.mm.sdk.modelmsg.SendAuth.Req();
        req.scope = "snsapi_userinfo,snsapi_base";
        req.state = "none";
        Toast.makeText(this, "getToken()", Toast.LENGTH_SHORT).show();
        api.sendReq(req);

注意:req.scope = “snsapi_userinfo,snsapi_base”;只填任何一个都不行。

你可能感兴趣的:(微信API自动登录流程)