微信登录_小白之旅的艰辛历程

前言:由于自己微信登录这一块一直没做,忙忙碌碌中生活,再者就是根据公司业务逻辑,还要接入网易云的一键登录配置页面无从跳转.言而总之,总而言之:菜是原罪.还是记录下自己实现步骤方便查看,以后避免错误发生.
贴出微信开发文档地址:传送门
第一步:添加微信依赖:

dependencies {
    
    //微信登录
    implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'

}

第二步定义常量类:

微信登录_小白之旅的艰辛历程_第1张图片常量中的appid(应用唯一标识)和secret(应用密钥 AppSecret)一般都是项目经理或者老板申请给你的,不然用自己的你那天跑路的就没的玩了.

第三步:创建wxapi包 创建WXEntryActivity


    private IWXAPI iwxapi;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		//wxapi包微信强制要求
        //接收到分享以及登录的intent传递handleIntent方法,处理结果
        iwxapi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, false);
        iwxapi.handleIntent(getIntent(), this);
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        //登录回调
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) resp).code;
                //获取accesstoken
                Log.e("code",code);
                StringBuffer url = new StringBuffer();
                
                url.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                        .append("?appid=")
                        .append(Constant.WX_APP_ID)
                        .append("&secret=")
                        .append(Constant.WX_APPSecret)
                        .append("&code=")
                        .append(code)
                        .append("&grant_type=authorization_code");
                OkHttpClient okHttpClient = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url(url.toString())
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String responseInfo = response.body().string();
                        String access = null;
                        String openId = null;
                        try {
                            JSONObject jsonObject = new JSONObject(responseInfo);
                            access = jsonObject.getString("access_token");
                            openId = jsonObject.getString("openid");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Log.e("null", access + "----" + openId);
                        getUserInfo(access, openId);

                    }
                });

                break;




        }
    }

    private void getUserInfo(String access, String openId) {
    //网络请求时,要求必须用get请求  通过access_token和openId获取个人信息
        StringBuffer infoUrl = new StringBuffer();
        infoUrl.append("https://api.weixin.qq.com/sns/userinfo")
                .append("?access_token=")
                .append(access)
                .append("&openid=")
                .append(openId);
        OkHttpClient okHttpClient = new OkHttpClient();
         Request request = new Request.Builder()
                .url(infoUrl.toString())  
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
		
                String info= response.body().string();
                String headimgurl = null;
                String nickname = null;
                String openid=null;
                String unionid=null;
                try {
                //此时将获取的个人信息提交给后台
                    JSONObject jsonObject = new JSONObject(info);
                    headimgurl = jsonObject.getString("headimgurl");
                    nickname = jsonObject.getString("nickname");
                    openid=jsonObject.getString("openid");
                    unionid=jsonObject.getString("unionid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e("info",headimgurl+"-------"+nickname);
            }
        });
    }


第四步 在LoginActivity和MainActivity中初始化:

public class MainActivity extends AppCompatActivity {
	@BindView(R.id.wechat_weixin)
    ImageView wechat_weixin;
	private IWXAPI api;
	 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID, true);
        api.registerApp(Constant.WX_APP_ID);

    }
    @OnClick(R.id.wechat_weixin)
    public void OnCheckedChangeListener(View view) {
        switch (view.getId()) {
            case R.id.wechat_weixin:
                if (!api.isWXAppInstalled()) {
                    Toast.makeText(MainActivity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wechat_sdk_demo_test";
                    api.sendReq(req);
                }
                break;

            default:
                break;
        }
    }
}

最后在AndroidManifest.xml声明一下

 
        

最后微信登录总算是实现了,用时三天.亲测有效.如果读者有幸看到给个赞 鼓励一下.

岁月如刀,我似芹萝,经过这些年努力,理想终于成了泡影。

你可能感兴趣的:(Android记录技术)