亲宝软件园·资讯

展开

android微信授权

前端小白123 人气:0

微信官方文档API:https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html

1.申请你的 AppID

只有审核通过的应用才能进行开发。

2.下载 SDK 及 API 文档

Android Studio 环境下:

在 build.gradle 文件中,添加如下依赖即可:
dependencies {
implementation ‘com.tencent.mm.opensdk:wechat-sdk-android:6.8.0'
}

3.将APP注册到微信

    IWXAPI msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constant.AppID, true);

    if (msgApi.isWXAppInstalled()) {
      // 将应用的appId注册到微信
      msgApi.registerApp(Constant.AppID);
      //建议动态监听微信启动广播进行注册到微信
      registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          // 将该app注册到微信
          msgApi.registerApp(Constant.AppID);
        }
      }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
      final Req req = new Req();
      req.scope = "snsapi_userinfo"; //获取用户个人信息则填写 snsapi_userinfo
      req.state =  "mvwl-"; //可根据项目填写
      msgApi.sendReq(req);
    } else {
      Toast.makeText(LoginActivity.this, "请安装微信客户端后进行此操作").show();
      return;

    }

4.创建WXEntryActivity,在AndroidMainifest.xml中添加WXEntryActivity

public class WXEntryActivity extends WXCallbackActivity  implements IWXAPIEventHandler {
  public static final String WXLOGIN_ACTION = "com.mvw.test.wxlogin";
  private IWXAPI iwxapi;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    iwxapi = WXAPIFactory.createWXAPI(this, "自己项目APPID", true);
    try {
      Intent intent = getIntent();
      iwxapi.handleIntent(intent, this);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    iwxapi.handleIntent(intent, this);
  }
  // 微信发送请求到第三方应用时,会回调到该方法
  @Override
  public void onReq(BaseReq baseReq) {
    switch (baseReq.getType()) {
      case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
        break;
      case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
        break;
      default:
        break;
    }
  }

  @Override
  public void onResp(BaseResp baseResp) {
    Intent intent = new Intent(WXLOGIN_ACTION);
    //登录回调
    Log.i("微信", "onResp: "+ baseResp.errCode);
    switch (baseResp.errCode){
      case BaseResp.ErrCode.ERR_OK:
        String code = ((SendAuth.Resp) baseResp).code;
        intent.putExtra("Wx_Login", code);
        intent.putExtra("error_code", 0);
        break;
      //用户拒绝授权
      case BaseResp.ErrCode.ERR_AUTH_DENIED:
        intent.putExtra("error_code", -4);
        break;
      //用户取消授权
      case BaseResp.ErrCode.ERR_USER_CANCEL:
        intent.putExtra("error_code", -2);
        break;
    }
    sendBroadcast(intent);  //使用了广播
    finish();
  }
}

<activity
      android:configChanges="keyboardHidden|orientation|screenSize"
      android:exported="true"
      android:name=".wxapi.WXEntryActivity"
      android:theme="@android:style/Theme.Translucent.NoTitleBar" />

5.接收微信返回参数code,根据code获取access_token,获取用户个人信息
下面是完整的使用列子。

package com.mvw.test.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;test
import com.google.gson.GsonBuilder;
import com.mvw.test.R;
import com.mvw.test.wxapi.WXEntryActivity;
import com.test.netlibrary.OkHttpUtils;
import com.test.netlibrary.callback.StringCallback;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth.Req;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.PlatformConfig;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.MediaType;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 登录
 */
public class LoginActivity extends Activity implements View.OnClickListener {
private String WEIXIN_ACCESS_TOKEN_KEY = "wx_access_token_key"; //微信access_token
  private String WEIXIN_OPENID_KEY = "wx_openid_key"; //微信openid
  private String WEIXIN_REFRESH_TOKEN_KEY = "wx_refresh_token_key";//微信refresh_token
  private String WEIXIN_UNIONID = "wx_unionid_key";//微信unionid
  private Activity activity;
  private IWXAPI msgApi;
  private WXLoginReceiver wxLoginReceiver;
  private  boolean flag=false;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    activity = this;
    initView();
  }
  private void initView() {
    ImageView iv_weChat = (ImageView) findViewById(R.id.iv_weChat);
    iv_weChat.setOnClickListener(this);
  }
  
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.iv_weChat:
           registerWeChat();
        break;
    }
  }


//注册广播
  @Override
  protected void onResume() {
    super.onResume();
    flag = true;
    if (wxLoginReceiver == null) {
       IntentFilter wxIntent = new IntentFilter(WXEntryActivity.WXLOGIN_ACTION);
      wxLoginReceiver = new WXLoginReceiver();
       registerReceiver(wxLoginReceiver, wxIntent);
    }

  }

  /**
   * 微信登录成功接收广播
   * ShareUtilService 封装的SharedPreferences存储方法
   */
  class WXLoginReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      String code = intent.getStringExtra("Wx_Login");
      int error_code = intent.getIntExtra("error_code", -1);
      if (TextUtils.equals(intent.getAction(), WXEntryActivity.WXLOGIN_ACTION)) {
        switch (error_code) {
          case 0:
            if (!code.isEmpty()) {
              String accessToken = ShareUtilService.getString(WEIXIN_ACCESS_TOKEN_KEY, "");
              String openid = ShareUtilService.getString(WEIXIN_OPENID_KEY, "");
              if (!"".equals(accessToken)) {
                // 有access_token,判断是否过期有效
                isExpireAccessToken(accessToken, openid);
              } else {
                // 没有access_token
                getAccessToken(code);
              }
            }
            break;
          case -4: //用户拒绝授权
          case -2:  //用户取消授权
            Log.i("微信", "onReceive: " + error_code);
            break;
        }

      }
    }
  }

  /**
   * 微信授权登录,请求 CODE
   */
  private void registerWeChat() {
    ShareUtilService.remove(WEIXIN_REFRESH_TOKEN_KEY);
    ShareUtilService.remove(WEIXIN_ACCESS_TOKEN_KEY);
    ShareUtilService.remove(WEIXIN_OPENID_KEY);
    ShareUtilService.remove(WEIXIN_UNIONID);
    msgApi = WXAPIFactory.createWXAPI(LoginActivity.this, Constant.AppID, true);
    Log.i("微信", "registerWeChat: " + msgApi.isWXAppInstalled());
    if (msgApi.isWXAppInstalled()) {
      // 将应用的appId注册到微信
      msgApi.registerApp(Constant.AppID);
      //建议动态监听微信启动广播进行注册到微信
      registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          // 将该app注册到微信
          msgApi.registerApp("自己项目APPID");
        }
      }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

      final Req req = new Req();
      req.scope = "snsapi_userinfo";
      req.state =  "mvwl-";//根据自己项目需要定义
      msgApi.sendReq(req);

    } else {
      Toast.makeText(LoginActivity.this, R.string.pay_wx_client_install,
          Toast.LENGTH_SHORT).show();
      return;

    }

  }

  /**
   * 微信获取accessToken
   * @param code 微信返回的code
   */
  private void getAccessToken(String code) {
    Map<String, String> map = new HashMap<>();
    map.put("appid", "自己项目APPID");
    map.put("secret", "自己项目APPSecret");
    map.put("code", code);
    map.put("grant_type", "authorization_code");
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/access_token?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信获取Err", e.getMessage());
         
          }

          @Override
          public void onResponse(String response, int id) {
            String access = null;
            String openid = null;
            try {
                JSONObject jsonObject = new JSONObject(response);
                access = jsonObject.getString("access_token");
                openid = jsonObject.getString("openid");
                String refresh = jsonObject.getString("refresh_token");
                ShareUtilService.setString(WEIXIN_ACCESS_TOKEN_KEY, access);
                ShareUtilService.setString(WEIXIN_OPENID_KEY, openid);
                ShareUtilService.setString(WEIXIN_REFRESH_TOKEN_KEY, refresh);
                getWeChatUserInfo(access, openid);
            } catch (JSONException e) {
              e.printStackTrace();
            }

          }
        });
  }

  /**
   * 获取用户信息
   * @param accessToken 接口调用凭证
   * @param openid 授权用户唯一标识
   */
  private void getWeChatUserInfo(String accessToken, String openid) {
    Map<String, String> map = new HashMap<>();
    map.put("access_token", accessToken);
    map.put("openid", openid);
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/userinfo?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信用户信息Err", e.getMessage());
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject jsonObject = new JSONObject(response);
                ShareUtilService.setString("userInfo", response);
                String unionid = jsonObject.getString("unionid");
                ShareUtilService.setString(WEIXIN_UNIONID,unionid);

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

  /**
   * 判断accesstoken是过期
   *
   * @param accessToken token
   * @param openid 授权用户唯一标识
   */
  private void isExpireAccessToken(final String accessToken, final String openid) {
    Map<String, String> map = new HashMap<>();
    map.put("access_token", accessToken);
    map.put("openid", openid);
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/auth?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信token过期Err", e.getMessage());
            
          }

          @Override
          public void onResponse(String response, int id) {
            try {
              JSONObject jsonObject = new JSONObject(response);
              int errCode = jsonObject.getInt("errcode");
              if (errCode == 0) {
                getWeChatUserInfo(accessToken, openid);
              } else {
                // 过期了,使用refresh_token来刷新accesstoken
                refreshAccessToken();
              }

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

          }
        });

  }

  /**
   * 刷新获取新的access_token
   */

  private void refreshAccessToken() {
    // 从本地获取以存储的refresh_token
    String refreshToken = ShareUtilService.getString(WEIXIN_REFRESH_TOKEN_KEY, "");
    if (TextUtils.isEmpty(refreshToken)) {
      return;
    }
    Map<String, String> map = new HashMap<>();
    map.put("appid", "自己项目的APPID“);
    map.put("grant_type", "refresh_token");
    map.put("refresh_token", refreshToken);
    OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/refresh_token?").params(map).build().execute(
        new StringCallback() {
          @Override
          public void onError(Call call, Exception e, int id) {
            Log.i("微信刷新TokenError", e.getMessage());
            // 重新请求授权
            registerWeChat();
          }
          @Override
          public void onResponse(String response, int id) {
            try {
               JSONObject jsonObject = new JSONObject(response);
                String access = jsonObject.getString("access_token");
                String openid = jsonObject.getString("openid");
                getWeChatUserInfo(access, openid);
        
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        });
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if(flag){
      flag=false;
      if (wxLoginReceiver != null) {
        unregisterReceiver(wxLoginReceiver);
      }
    }

  }
}

加载全部内容

相关教程
猜你喜欢
用户评论