前言
近来,因开发需要,接触微信登录、支付、和支付宝支付,网上的介绍过于笼统,或者代码不完整或者大多源码又需要积分,摸索了半天,微信登录微信支付支付宝支付需要首先注册相关注册相关相应账号,然后注册开发者账号等,详情见微信开发平台,这里直接上完整的代码。
微信登录
微信登录比较简单,首先在Android Studio的build.gradle中添加相关依赖,如下所示:
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
- 在你的包名相应目录下新建一个wxapi目录,然后创建WXEntryActivity类,让它直接继承IWXAPIEventHandler
- 新建工具类,记录对应的AppID和AppSecret,如下所示,同时在AndroidManifest.xml中配置相关权限:
public static final String App_ID="XXXXXXX";
public static final String AppSecret="XXXXXXXXX";
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- 重写onReq和onResp方法,因为实现IWXAPIEventHandler接口,微信发送的请求将回调到onReq方法,发送到微信请求的响应结果将回调到onResp方法,所以我们在onResp中针对不同情况进行处理
- 吊起微信登录,获取相应的授权,从而获取微信个人信息
完整代码如下,可直接复制:
- WXEntryActivity类
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
private IWXAPI iwxapi;
public static String CODE;
public static boolean isOK = false;
private String openid,access;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wxentry);
iwxapi = WXAPIFactory.createWXAPI(this, Utils.App_ID, true);
iwxapi.handleIntent(getIntent(), this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
iwxapi.handleIntent(intent,this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
SendAuth.Resp sendResp= (SendAuth.Resp) baseResp;
CODE=sendResp.code;
getAccessToken(CODE);
isOK=true;
// WXEntryActivity.this.finish();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
Toast.makeText(WXEntryActivity.this,"用户拒绝授权",Toast.LENGTH_SHORT).show();
isOK=false;
WXEntryActivity.this.finish();
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
Toast.makeText(this, "用户取消授权", Toast.LENGTH_SHORT).show();
WXEntryActivity.this.finish();
break;
default:
isOK=false;
WXEntryActivity.this.finish();
break;
}
}
private void getAccessToken(String code) {
//获取授权
String path="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Utils.App_ID+"&secret="+Utils.AppSecret+"&code="+code+"&grant_type=authorization_code";
OkHttpClient client=new OkHttpClient();
final Request request=new Request.Builder()
.url(path)
.build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String result=response.body().string();
try {
JSONObject jsonObject=new JSONObject(result);
openid=jsonObject.getString("openid");
access=jsonObject.getString("access_token");
Log.d("-----------", openid);
} catch (JSONException e) {
e.printStackTrace();
}
//获取个人信息
String getUserInfo="https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openid;
OkHttpClient client1=new OkHttpClient();
final Request request1=new Request.Builder()
.url(getUserInfo)
.build();
Call info=client1.newCall(request1);
info.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(getApplicationContext(),"登陆失败",Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String nickName=null;
String sex=null;
String province=null;
String country=null;
String city=null;
String avatarUrl=null;
final String result=response.body().string();
try {
//解析出微信的常用信息,如性别,昵称,省市区等
JSONObject jsonObject=new JSONObject(result);
nickName=jsonObject.getString("nickname");
sex=jsonObject.getString("sex");
city=jsonObject.getString("city");
province=jsonObject.getString("province");
country=jsonObject.getString("country");
avatarUrl=jsonObject.getString("headimgurl");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}
}
微信支付
- 微信支付与微信登录基本相同,这里我们创建WXPayEntryActivity类。
- 订单信息包含支付金额,支付时间,这些一般由服务端去实现,交付给app转发给微信服务器,对客户端来说,只需要调用支付SDK将订单信息发送给微信服务器,其具体的回调接口是该类中的onResp函数,在该函数中可判断是否支付成功。代码如下:
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wxpay_entry);
api= WXAPIFactory.createWXAPI(this, Utils.App_ID);
api.handleIntent(getIntent(),this);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent,this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp resp) {
if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
if (resp.errCode == 0) // 支付成功
{
Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
//后续的操作
finish();
} else {
Toast.makeText(this, resp.errCode + "test", Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
}
支付宝支付
- 支付宝支付相对简单,首先导入相关sdk,将sdk放入应用工程lib目录下:
- 在主项目的 build.gradle 中,添加下面的内容,将 libs 目录作为依赖仓库:
- 在App的build.gradle添加相关依赖,如下所示:
implementation(name: 'alipaySdk-15.6.5-20190718211148', ext: 'aar')
- 获取 PayTask 支付对象调用支付(支付行为需要在独立的非ui线程中执行)
orderInfo=response.body().getData();
Runnable runnable = new Runnable() {
@Override
public void run() {
PayTask apipay = new PayTask(SettlementActivity.this);
Map<String, String> result = apipay.payV2(orderInfo, true);
Message msg = new Message();
msg.what = SDK_PAY_FLAG;
msg.obj = result;
mHandler.sendMessage(msg);
}
};
Thread authThread = new Thread(runnable);
authThread.start();
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@SuppressWarnings("unused")
public void handleMessage(Message msg) {
switch (msg.what) {
case SDK_PAY_FLAG: {
@SuppressWarnings("unchecked")
PayResult payResult = new PayResult((Map<String, String>) msg.obj);
String resultInfo = payResult.getResult();
String resultStatus = payResult.getResultStatus();
if (TextUtils.equals(resultStatus, "9000")) {
Toast.makeText(SettlementActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//这里进行后续操作,比如跳转等等
} else {
Toast.makeText(SettlementActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
}
break;
}
case SDK_AUTH_FLAG:
@SuppressWarnings("unchecked")
AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
String resultStatus = authResult.getResultStatus();
if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
Toast.makeText(SettlementActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SettlementActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
}
}
}
};
@Override
public void onFailure(Call<AliPayOrderStr> call, Throwable t) {
}
});