近来,因开发需要,接触微信登录、支付、和支付宝支付,网上的介绍过于笼统,或者代码不完整或者大多源码又需要积分,摸索了半天,微信登录微信支付支付宝支付需要首先注册相关注册相关相应账号,然后注册开发者账号等,详情见微信开发平台,这里直接上完整的代码。
微信登录比较简单,首先在Android Studio的build.gradle中添加相关依赖,如下所示:
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
public static final String App_ID="XXXXXXX";
public static final String AppSecret="XXXXXXXXX";
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();
}
}
});
}
});
}
}
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();
}
}
}
}
implementation(name: 'alipaySdk-15.6.5-20190718211148', ext: 'aar')
orderInfo=response.body().getData();
Runnable runnable = new Runnable() {
@Override
public void run() {
PayTask apipay = new PayTask(SettlementActivity.this);
Map 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) 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) 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 call, Throwable t) {
}
});