转载需要著名出处:
http://blog.csdn.net/lowprofile_coding/article/details/78004224
之前写过微信登录分享支付第一版:
http://blog.csdn.net/lowprofile_coding/article/details/48086381
前言
大部分的app都有接入第三方sdk的需求。例如第三方登录需要接入微信、QQ、微博。第三方支付需要接入微信、支付宝、银联。
这些我都有使用过,都有使用过他们的sdk,感觉最麻烦的就是微信,不能直接调试,得用正式的签名进行签名才能调试。还有他们官方的demo也是跑不起来的,因为没有签名文件。需要注意的地方也很多。
代码实现
微信sdk现在支持Android Studio在线引用了,之前都是添加jar的方法。需要访问微信的接口获取用户信息,所以把我们之前封装的okhttp也一起在线引用。okhttp需要在自定义的Application中初始化这个我就不贴代码了。之前已经讲过很多次。在app/build.gradle文件dependencies标签中加入以下两行代码:
compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
compile 'com.ansen.http:okhttpencapsulation:1.0.1'
需要用到网络,所以在AndroidManifest.xml文件中加入网络权限:
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录之后信息在这里显示"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_nickname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="昵称:"/>
<TextView
android:id="@+id/tv_age"
android:layout_below="@+id/tv_nickname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄:"/>
</RelativeLayout>
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="微信登录"/>
<Button
android:id="@+id/btn_share_friend_circle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="分享到朋友圈"/>
<Button
android:id="@+id/btn_share_friend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="分享给好友"/>
<Button
android:id="@+id/btn_pay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="微信支付"/>
</LinearLayout>
布局文件很简单,就LinearLayout里面放了几个TextView,跟几个按钮。
WeiXin.java 用于EventBus来传送消息,微信sdk有个很奇怪的地方,就是不管登录、分享、支付之后都得用一个Activity来接收,所以我们还得从接收的那个activity把结果信息通过EventBus传递给MainActivity。虽然用广播也能实现,但是个人喜欢用EventBus,使用灵活。简单轻量。
public class WeiXin {
private int type;//1:登录 2.分享 3:微信支付
private int errCode;//微信返回的错误码
private String code;//登录成功才会有的code
public WeiXin() {
}
public WeiXin(int type,int errCode, String code) {
this.type = type;
this.errCode=errCode;
this.code = code;
}
public int getType() {
return type;
}
public void se