标签:
最近在项目中加入微信登录,以下是微信登录实现的步骤,希望给大家有所帮助。
第一步:
登录微信开放平台,点击下图中的“创建应用”:
创建应用时需要签名,下载下图中签名工具:
应用创建完毕后会得到两个值:AppID、AppSecret,这两个值保存好,后面会用到。
第二步:
下载微信的SDK,选择下图的Android开放工具包:
将工具包下的 ----->导入你的项目工程中的-------->中。
第三步
在你的工程中创建一个包,记住你的包名格式必须是你工程AndroidManifest.xml中的package名+wxapi,如下图中的
最后包名: net.sourceforge.simcpux.wxapi
在这个包下新建一个WXEntryActivity类,并在这个类中定义下图中的回调方法:
public class WXEntryActivity extends Activity implements IWXAPIEventHandler{ private IWXAPI api; private BaseResp resp = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false); api.handleIntent(getIntent(), this); } // 微信发送请求到第三方应用时,会回调到该方法 @Override public void onReq(BaseReq req) { finish(); } // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法 @Override public void onResp(BaseResp resp) { String result = ""; if (resp != null) { resp = resp; } switch(resp.errCode) { case BaseResp.ErrCode.ERR_OK: result ="发送成功"; Toast.makeText(this, result, Toast.LENGTH_LONG).show(); 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; } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); api.handleIntent(intent, this); finish(); } }
在以上方法中,当你登录微信时,出现授权界面时,点击授权后会回调onResp,会得到一个resp,通过这个resp能得到code,通过以下方法:
(SendAuth.Resp) .code;
获取code后,记住这个code后面有用。以上的WX_APP_ID是你创建应用时得到的AppID。
之后在你项目登录界面的Activity中加入以下代码实现登录授权界面。当你登录授权后回到你的Activity后,会执行Activity的生命周期onResume(),因此建议你在以上WXEntryActivity这个类中将resp保存在全局变量中。
在登录的Activity中添加以下方法:
public class MainLoginTest extends Activity { public static IWXAPI WXapi; private String weixinCode; private final static int LOGIN_WHAT_INIT = 1; private static String get_access_token = ""; // 获取第一步的code后,请求以下链接获取access_token public static String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; //获取用户个人信息 public static String GetUserInfo="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } /** * 登录微信 */ private void WXLogin() { WXapi = WXAPIFactory.createWXAPI(this, WX_APP_ID, true); WXapi.registerApp(WX_APP_ID); SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_sdk_demo"; WXapi.sendReq(req); } @Override protected void onResume() { super.onResume(); /* * resp是你保存在全局变量中的 */ if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) { // code返回 weixinCode = ((SendAuth.Resp)resp).code; /* * 将你前面得到的AppID、AppSecret、code,拼接成URL */ get_access_token = getCodeRequest(weixinCode); Thread thread=new Thread(downloadRun); thread.start(); try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 获取access_token的URL(微信) * @param code 授权时,微信回调给的 * @return URL */ public static String getCodeRequest(String code) { String result = null; GetCodeRequest = GetCodeRequest.replace("APPID", urlEnodeUTF8(AppConstants.WX_APP_ID)); GetCodeRequest = GetCodeRequest.replace("SECRET", urlEnodeUTF8(AppConstants.WX_APP_SECRET)); GetCodeRequest = GetCodeRequest.replace("CODE",urlEnodeUTF8( code)); result = GetCodeRequest; return result; } /** * 获取用户个人信息的URL(微信) * @param access_token 获取access_token时给的 * @param openid 获取access_token时给的 * @return URL */ public static String getUserInfo(String access_token,String openid){ String result = null; GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN", urlEnodeUTF8(access_token)); GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid)); result = GetUserInfo; return result; } public static String urlEnodeUTF8(String str) { String result = str; try { result = URLEncoder.encode(str, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return result; } public Runnable downloadRun = new Runnable() { @Override public void run() { WXGetAccessToken(); } }; /** * 获取access_token等等的信息(微信) */ private void WXGetAccessToken(){ HttpClient get_access_token_httpClient = new DefaultHttpClient(); HttpClient get_user_info_httpClient = new DefaultHttpClient(); String access_token=""; String openid =""; try { HttpPost postMethod = new HttpPost(get_access_token); HttpResponse response = get_access_token_httpClient.execute(postMethod); // 执行POST方法 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader( new InputStreamReader(is)); String str = ""; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); } is.close(); String josn = sb.toString(); JSONObject json1 = new JSONObject(josn); access_token = (String) json1.get("access_token"); openid = (String) json1.get("openid"); } else { } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } String get_user_info_url=getUserInfo(access_token,openid); WXGetUserInfo(get_user_info_url); } /** * 获取微信用户个人信息 * @param get_user_info_url 调用URL */ private void WXGetUserInfo(String get_user_info_url){ HttpClient get_access_token_httpClient = new DefaultHttpClient(); String openid=""; String nickname=""; String headimgurl=""; try { HttpGet getMethod = new HttpGet(get_user_info_url); HttpResponse response = get_access_token_httpClient.execute(getMethod); // 执行GET方法 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader( new InputStreamReader(is)); String str = ""; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); } is.close(); String josn = sb.toString(); JSONObject json1 = new JSONObject(josn); openid = (String) json1.get("openid"); nickname = (String) json1.get("nickname"); headimgurl=(String)json1.get("headimgurl"); } else { } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }
根据以上程序,可以获取用户信息、code、openid、access_token
最后一步:
在AndroidManifest中添加以下配置代码:
<activity android:name="net.sourceforge.simcpux.wxapi.WXEntryActivity" android:configChanges="orientation|keyboardHidden" android:exported="true" android:launchMode="singleTop" android:screenOrientation="portrait" android:theme="@android:style/Theme.Translucent.NoTitleBar" > <intent-filter> <action android:name="android.intent.action.VIEW" > </action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
至此微信登录完毕
标签:
原文地址:http://my.oschina.net/u/1244156/blog/465147