微信APP支付-Android+springboot搭建后端(一)上篇文章介绍了后端搭建的过程,这篇介绍Android端搭建过程。首先打开微信商户平台的APP接入文档,按照这个步骤来。在这里主要介绍如何接入。
一、Android端
按照官方要求将一些参数拿到。
1、创建项目
主要的目录结构如下,其中要注意的是wxapi包按照官方要求,必须在你的包之下。
2、添加依赖
app/build.gradle
在app/build.gradle下加入微信支付的依赖以及okhttp3。
implementation 'com.tencent.mm.opensdk:wechat-sdk-android:+' //微信支付
implementation 'com.squareup.okhttp3:okhttp:3.14.7'
3、AndroidManifest.xml
添加微信支付的权限
<!--微信支付权限-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--wx pay-->
<activity
android:name=".wxapi.WXPayEntryActivity"
android:exported="true"
android:launchMode="singleTop">
</activity>
4、wxapi
Constants
public class Constants {
public static final String APP_ID = 填写自己的APPID;
}
WXPayEntryActivity
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
try {
api.handleIntent(getIntent(), this);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onStart() {
super.onStart();
api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
api.handleIntent(getIntent(), this);
}
@Override
protected void onResume() {
super.onResume();
api = WXAPIFactory.createWXAPI(this, Constants.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 req) {
}
@Override
public void onResp(BaseResp resp) {
int result = 0;
//有时候支付结果还需要发送给服务器确认支付状态
if (resp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX){
if (resp.errCode==0){
Toast.makeText(this,"支付成功",Toast.LENGTH_LONG).show();
Log.d("WcChatPay","支付成功");
}else if (resp.errCode==-2){
Toast.makeText(this,"取消支付",Toast.LENGTH_LONG).show();
Log.d("WcChatPay","取消支付");
}else {
Toast.makeText(this,"支付失败",Toast.LENGTH_LONG).show();
Log.d("WcChatPay","支付失败");
}
finish();
}
}
}
5、布局文件
activity_we_chat_pay
布局文件很简单,就是一个微信支付的button。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeChatPay">
<Button
android:id="@+id/wechatpay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="微信支付"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
6、WeChatPay
public class WeChatPay extends AppCompatActivity {
private Button wechatpay;
private IWXAPI msgApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_we_chat_pay);
wechatpay = findViewById(R.id.wechatpay);
//初始化操作
msgApi = WXAPIFactory.createWXAPI(this, null);
msgApi.registerApp(Constants.APP_ID);
wechatpay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getWeChatPayData();
}
});
}
private void getWeChatPayData(){
new Thread(new Runnable() {
@Override
public void run() {
MediaType JSON = MediaType.parse("application/json;charset=utf-8");
JSONObject jsonObject = new JSONObject();
//创建OkHttp对象
OkHttpClient httpClient = new OkHttpClient();
try {
// jsonObject.put("productId",1);
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsonObject));
String url = "https://ip/api/wx-pay/native/";
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
//发送请求获取返回数据
Response response = httpClient.newCall(request).execute();
//处理返回的数据
String resData = response.body().string();
Message message = new Message();
message.what = 1;
message.obj = resData;
wechathandeler.sendMessage(message);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
@SuppressLint("HandlerLeak")
Handler wechathandeler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
//微信
try {
JSONObject jsonObject = new JSONObject(msg.obj.toString());
JSONObject resultData = new JSONObject(jsonObject.getString("data"));
String appid = resultData.getString("appid");
String partnerid = resultData.getString("partnerid");
String noncestr = resultData.getString("noncestr");
String packagevalue = resultData.getString("packagevalue");
String prepayid = resultData.getString("prepayid");
String sign = resultData.getString("sign");
String timestamp = resultData.getString("timestamp");
//调起支付
PayReq request = new PayReq();
request.appId = Constants.APP_ID;
request.partnerId = partnerid;
request.prepayId = prepayid;
request.packageValue = packagevalue;
request.nonceStr = noncestr;
request.timeStamp = timestamp;
request.sign = sign;
Log.d("WcChatPay","sign====>"+sign);
msgApi.sendReq(request);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
}
此时这就完成了前端的操作。Android端使用OKhttp3想服务器端发送请求下单,然后得到响应结果。将数据解析出来,然后调起支付就可以。
此时发现Android端以及获取到下单的数据了。点击支付之后返回商家,就可以收到支付成功了。当然在这里收到支付成功,后端继续做相应的处理,在这里就不展示了。
取消支付以及支付失败就不展示了,在不同的场景,Android端和后端都需要进行不同的处理。
二、总结
主要就是总结一下,比如在开发的时候遇到一些坑,这里就挑一些拿出来分析,希望有帮助。
这个bug主要就是签名生成错误。我们需要好好的阅读官方提供的demo,APP下单生成签名的参数就只有四个appId,timeStamp,nonceStr,prepayid。所以根据我后端的代码就可以了。