最近在項目中加入微信登陸,如下是微信登陸實現的步驟,但願給你們有所幫助。java
第一步:node
登陸微信開放平臺,點擊下圖中的「建立應用」:android
建立應用時須要簽名,下載下圖中籤名工具:json
應用建立完畢後會獲得兩個值:AppID、AppSecret,這兩個值保存好,後面會用到。api
第二步:微信
下載微信的SDK,選擇下圖的Android開放工具包:app
將工具包下的 ----->導入你的項目工程中的-------->中。ide
第三步工具
在你的工程中建立一個包,記住你的包名格式必須是你工程AndroidManifest.xml中的package名+wxapi,以下圖中的post
最後包名: 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>
至此微信登陸完畢