Android 微信授权登录、获取个人信息

使用微信功能首先就要做好微信的相关配置

去微信平台申请的app应用,绑定一个app,并去申请功能的使用权限:

1 .  在微信平台的申请的那个app,打包后(非debug包),在打包后的app应用软件里面下载一个app签名工具,在app签名工具里面输入appmanifest里面的包名,包名是package里面的,一定要是这个包名,别把包名弄混了,最后生成一个签名,放在微信开放平台的信息输入框里面),


2  . 然后就是调用微信的回调类:       WXEntryActivity 而且这个类名必须是这个,而这个类名必须在.wxapi包名下,不然微信无法掉起

3.接着就是配置清单:exported=""   这个属性是必须要添加的

  <activity android:name=".wxapi.WXEntryActivity"
                  android:label="@string/app_name"

                  android:exported="true"/>

这样配置就完成了。


下面给大家分享一下源码

扫描二维码关注公众号,回复: 1427177 查看本文章

这个是微信主页面,下面写了一个点击按钮,点击之后就会执行点击按钮里面的方法,需要WXEntryActivity类回调一个code值,通过这个code值就能请求一下数据,获得用户信息。

LoginActivity 

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;


import com.example.hulei.wechatlogin.App;
import com.example.hulei.wechatlogin.R;
import com.example.hulei.wechatlogin.activity.MainActivity;
import com.example.hulei.wechatlogin.utils.HttpCallBackListener;
import com.example.hulei.wechatlogin.utils.HttpUtil;
import com.example.hulei.wechatlogin.utils.PrefParams;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;


import org.json.JSONException;
import org.json.JSONObject;


/**
 * Created by asus on 2016/1/16.
 */
public class LoginActivity extends Activity {


    public static final String TAG = "loginFragment";


    private LinearLayout mLoginWeChat;
    private IWXAPI api;
    private ReceiveBroadCast receiveBroadCast;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.frag_login, container, false);
        rootView.setTag(TAG);
        mLoginWeChat = (LinearLayout) rootView.findViewById(R.id.layout_login_wx);
        mLoginWeChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                weChatAuth();
            }
        });
        return rootView;
    }


    @Override
    public void onResume() {
        super.onResume();
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("authlogin");
        getActivity().registerReceiver(receiveBroadCast, filter);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiveBroadCast);
    }


    private void weChatAuth() {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(LoginActivity.this, App.WX_APPID, true);
        }
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wx_login_duzun";
        api.sendReq(req);
    }


    public void getAccessToken() {
        SharedPreferences WxSp = getApplicationContext()
                .getSharedPreferences(PrefParams.spName, Context.MODE_PRIVATE);
        String code = WxSp.getString(PrefParams.CODE, "");
        final SharedPreferences.Editor WxSpEditor = WxSp.edit();
        Log.d(TAG, "-----获取到的code----" + code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + App.WX_APPID
                + "&secret="
                + App.WX_APPSecret
                + "&code="
                + code
                + "&grant_type=authorization_code";
        Log.d(TAG, "--------即将获取到的access_token的地址--------");
        HttpUtil.sendHttpRequest(url, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {


                //解析以及存储获取到的信息
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.d(TAG, "-----获取到的json数据1-----" + jsonObject.toString());
                    String access_token = jsonObject.getString("access_token");
                    Log.d(TAG, "--------获取到的access_token的地址--------" + access_token);
                    String openid = jsonObject.getString("openid");
                    String refresh_token = jsonObject.getString("refresh_token");
                    if (!access_token.equals("")) {
                        WxSpEditor.putString(PrefParams.ACCESS_TOKEN, access_token);
                        WxSpEditor.apply();
                    }
                    if (!refresh_token.equals("")) {
                        WxSpEditor.putString(PrefParams.REFRESH_TOKEN, refresh_token);
                        WxSpEditor.apply();
                    }
                    if (!openid.equals("")) {
                        WxSpEditor.putString(PrefParams.WXOPENID, openid);
                        WxSpEditor.apply();
                        getPersonMessage(access_token, openid);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError(Exception e) {
                Toast.makeText(getActivity(), "通过code获取数据没有成功", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void getPersonMessage(String access_token, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        HttpUtil.sendHttpRequest(url, new HttpCallBackListener() {
            @Override
            public void onFinish(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.d(TAG, "------获取到的个人信息------" + jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError(Exception e) {
                Toast.makeText(getActivity(), "通过openid获取数据没有成功", Toast.LENGTH_SHORT).show();
            }
        });
    }


    class ReceiveBroadCast extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            getAccessToken();
            Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent1);
        }
    }
}

下面的就是回调类,大家一定要记住我上面定义的格式啊!

WXEntryActivity 

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;


import com.example.hulei.wechatlogin.App;
import com.example.hulei.wechatlogin.utils.PrefParams;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;


/**
 * Created by asus on 2016/1/16.
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {


    private IWXAPI api;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, App.WX_APPID, false);
        api.handleIntent(getIntent(), this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }


    @Override
    public void onReq(BaseReq baseReq) {


    }


    @Override
    public void onResp(BaseResp baseResp) {
        String result = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) baseResp).code;
                SharedPreferences WxSp = getApplicationContext().getSharedPreferences(PrefParams.spName, Context.MODE_PRIVATE);
                SharedPreferences.Editor WxSpEditor = WxSp.edit();
                WxSpEditor.putString(PrefParams.CODE,code);
                WxSpEditor.apply();
                Intent intent = new Intent();
                intent.setAction("authlogin");
                WXEntryActivity.this.sendBroadcast(intent);
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送被拒绝";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            default:
                result = "发送返回";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();


                finish();
                break;
        }
    }
}

这两个类就可以调用微信了,下面分享一下我代码里面使用的工具类:

HttpUtil 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * Created by asus on 2016/1/16.
 */
public class HttpUtil {
    public static void sendHttpRequest(final String address,final HttpCallBackListener listener){

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        HttpURLConnection connection = null;
                        try {
                            URL url = new URL(address);
                            connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setConnectTimeout(8000);
                            connection.setReadTimeout(8000);
                            InputStream in = connection.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                            StringBuilder response = new StringBuilder();
                            String line;
                            while ((line = reader.readLine())!=null){
                                response.append(line);
                            }
                            if (listener!= null){
                                listener.onFinish(response.toString());
                            }
                        } catch (MalformedURLException e) {
                            if (listener!=null){
                                listener.onError(e);
                            }
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).start();
    }
}

HttpCallBackListener

public interface HttpCallBackListener {


    void onFinish(String response);


    void onError(Exception e);

}


PrefParams 

public class PrefParams {

    //微信登錄
    public static final String spName = "WX_SP";
    public static final String CODE = "code";
    public static final String ACCESS_TOKEN = "access_token";
    public static final String REFRESH_TOKEN = "refresh_token";
    public static final String WXOPENID = "wxopenid";
    public static final String EXPIRES_IN = "expires_in";
    public static final String IS_AUTH_LOGIN = "is_auth_login";

}

Application 

public class App extends Application {
    public static final String WX_APPID = "";
    public static final String WX_APPSecret = "";

    private IWXAPI api;
    @Override
    public void onCreate() {
        super.onCreate();
        api = WXAPIFactory.createWXAPI(this, WX_APPID, true);
        api.registerApp(WX_APPID);
    }

}

猜你喜欢

转载自blog.csdn.net/nazicsdn/article/details/80542044