Android 集成微信支付步骤详解
程序员文章站
2023-12-22 14:24:04
...
Android开发要点说明 集成之前的步骤不能省,下面引用官网步骤
1、后台设置
商户在微信开放平台申请开发应用后,微信开放平台会生成APP的唯一标识APPID。由于需要保证支付安全,需要在开放平台绑定商户应用包名和应用签名,设置好后才能正常发起支付。设置界面在【开放平台】中的栏目【管理中心 / 修改应用 / 修改开发信息】里面,如图红框内所示。
应用包名:是在APP项目配置文件AndroidManifest.xml中声明的package值,例如DEMO中的package="net.sourceforge.simcpux"。
应用签名:根据项目的应用包名和编译使用的keystore,可由签名工具生成一个32位的md5串,在调试的手机上安装签名工具后,运行可生成应用签名串,如图8.9所示,绿色串即应用签名。签名工具下载地址点击打开链接https://open.weixin.qq.com/zh_CN/htmledition/res/dev/download/sdk/Gen_Signature_Android.apk
2.Android 开始集成支付代码
首先导包
compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
异步任务获取支付参数
import android.content.Intent;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;
public class PayActivity extends BaseActivity {
@Bind(R.id.top_title)
TextView top_title;
@Bind(R.id.count_down)
RushBuyCountDownTimerView count_down;
@Bind(R.id.price)
TextView price;
@Bind(R.id.image_zfb)
ImageView image_zfb;
@Bind(R.id.iamge_wechat)
ImageView iamge_wechat;
@Bind(R.id.order_num)
TextView order_num;
@Bind(R.id.order_name)
TextView order_name;
@Bind(R.id.order_time)
TextView order_time;
@Bind(R.id.order_money)
TextView order_money;
@Bind(R.id.pay_total)
TextView pay_total;
private int select = 1;
private OrderEntity mPerson;
@Override
protected int getLayoutId() {
return R.layout.activity_pay;
}
@Override
public void initView() {
super.initView();
mPerson = (OrderEntity) getIntent().getSerializableExtra("body");
if (mPerson != null) {
price.setText("¥" + mPerson.getOrder_total());
order_num.setText("订单号:" + mPerson.getOrder_sn());
order_name.setText("产品名称:" + mPerson.getName());
order_time.setText("游玩时间:" + mPerson.getUse_date());
order_money.setText("订单金额:" + mPerson.getOrder_total() + "(在线支付)");
pay_total.setText("¥" + mPerson.getOrder_total());
long time = 1000 * 60 * 30;
count_down.setTime(time);
count_down.start();
}
top_title.setText("订单支付");
}
@Override
public void initData() {
super.initData();
}
@OnClick({R.id.top_left, R.id.zfb_rela, R.id.wechat_rela, R.id.submit})
void onClick(View view) {
switch (view.getId()) {
case R.id.top_left:
PayActivity.this.finish();
break;
case R.id.zfb_rela:
if (select == 1) {
return;
}
select = 1;
setview(select);
break;
case R.id.wechat_rela:
if (select == 2) {
return;
}
select = 2;
setview(select);
break;
case R.id.submit://购买
if (mPerson != null) {
new PayOrderTask().execute();
}
break;
}
}
private void setview(int index) {
image_zfb.setImageResource(R.drawable.order_pay_gray_gou);
iamge_wechat.setImageResource(R.drawable.order_pay_gray_gou);
if (index == 1) {
image_zfb.setImageResource(R.drawable.order_pay_red_gou);
} else {
iamge_wechat.setImageResource(R.drawable.order_pay_red_gou);
}
}
/*
*异步从后台获取支付参数
* */
class PayOrderTask extends WorkTask<Void, Void, WeiChatBean> {
@Override
protected void onPrepare() {
super.onPrepare();
showAlert("..正在购买..", false);
}
@Override
public WeiChatBean workInBackground(Void... voids) throws TaskException {
//产品编号
MapUtil.sharedInstance().putDefaultValue(Constants.PAY_PRODUCT_ID, mPerson.getOrder_sn());
MapUtil.sharedInstance().putDefaultValue(Constants.ORDER_ID, mPerson.getOrder_id());
//支付的金钱
MapUtil.sharedInstance().putDefaultValue(Constants.PAY_MONEY, mPerson.getOrder_total());
return SDK.newInstance(PayActivity.this).getPrePayOrder(mPerson.getName(), mPerson.getOrder_sn(), mPerson.getOrder_total());
}
@Override
protected void onSuccess(WeiChatBean info) {
super.onSuccess(info);
dismissAlert();
if (info.getBody() != null) {
ToBuyUtils.lunchWeChat(PayActivity.this, Consts.PayType.Pay_Product_Buy, info.getBody());
}
}
@Override
protected void onFailure(TaskException exception) {
super.onFailure(exception);
dismissAlert();
Toast.makeText(PayActivity.this, "" + exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
调起微信支付类统一入口
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
/**
* Created by lyj on 2017/8/1.
*/
public class ToBuyUtils {
/**
* 调起微信支付
* @param info
*/
public static void lunchWeChat(Context context, Consts.PayType payType, BRewardBean info){
//获取到打赏订单等信息
IWXAPI msgApi = WXAPIFactory.createWXAPI(context,null);
msgApi.registerApp(Constants.WE_CHAT_APP_ID);//微信开放平台创建应用的appid
PayReq req = ToBuyUtils.getWeChatPayReq(info);
msgApi.sendReq(req);
//存入订单编号,供后面查询订单支付情况
MapUtil.sharedInstance().putDefaultValue(Constants.ORDER_ID_KEY,info.getNoncestr());
//存入微信支付类型
MapUtil.sharedInstance().putDefaultValue(Constants.ORDER_TYPE,payType.getPayTypeName());
}
/**
* 获取微信支付的PayReq
*
* @param bean
* @return
*/
public static PayReq getWeChatPayReq(BRewardBean bean) {
PayReq req = new PayReq();
req.appId = bean.getAppid();//微信ID
req.partnerId = bean.getPartnerid();//商户ID
req.prepayId = bean.getPrepayid();//预支付订单编号
req.packageValue =bean.getWechatPackage();
req.nonceStr= bean.getNoncestr();
req.timeStamp = bean.getTimestamp();
req.sign = bean.getSign();
return req;
}
/**
* 判断字符串是否为空
*/
public static boolean isEmpty(String data) {
return data == null || data.trim().length() < 1 || "null".equals(data.toLowerCase()) || data.equals("false");
}
public static String formatString(String str, String defaultStr) {
if (null == str || str.equals("") || str.length()<1) {
return defaultStr;
}
return str;
}
public static String formatObject(Object object, String defaultStr) {
if (object == null) {
return defaultStr;
}
return object.toString();
}
public static int formatNum(String intStr, int defaultValue) {
int value;
if (TextUtils.isEmpty(intStr) || intStr.equals("") || intStr.equals("null"))
return defaultValue;
try {
value = Integer.parseInt(intStr);
} catch (Exception e) {
value = defaultValue;
}
return value;
}
public static double formatDoubleNum(String intStr, double defaultValue) {
double value;
if (TextUtils.isEmpty(intStr) || intStr.equals("") || intStr.equals("null"))
return defaultValue;
try {
value = Double.parseDouble(intStr);
} catch (Exception e) {
value = defaultValue;
}
return value;
}
}
接下来就是微信支付状态回调了WXPayEntryActivity.java ,注意:这个activity的路径必须是 微信开放平台填写的包名加.wxapi下 ,
package 你的包名.wxapi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.ArrayList;
/**
* 微信支付返回
*/
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI api;
private TextView tvPayCallBack;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_result);
api = WXAPIFactory.createWXAPI(this, Constants.WE_CHAT_APP_ID, true);
api.handleIntent(getIntent(), this);
tvPayCallBack = (TextView) findViewById(R.id.tvPayCallBack);
}
@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(final BaseResp resp) {
if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
if (resp.errCode == 0) {
//根据订单号 查询支付状态 要以后台查询微信后台的结果为准
延时1.5秒再调后台接口查询
} else if (resp.errCode == -2) {
//用户没有操作
this.finish();
} else {
TLog.log("tttt", "--支付失败:" );
dialog("签名问题,支付失败", resp.errCode + "");
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
MapUtil.sharedInstance().clear();
}
private void dialog(String title, String dex) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); //先得到构造器
builder.setMessage(title + "==" + dex); //设置内容
builder.setCancelable(false);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //关闭dialog
WXPayEntryActivity.this.finish();
}
});
//参数都设置完成了,创建并显示出来
builder.create().show();
}
private void dialogs(String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); //先得到构造器
builder.setMessage(title); //设置内容
builder.setCancelable(false);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){ //设置确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //关闭dialog
// MapUtil.sharedInstance().getDefaultValue(Constants.PAY_PRODUCT_ID).toString();
Intent intent=new Intent(WXPayEntryActivity.this,OrderDetailActivity.class);
intent.putExtra("order_state", getResources().getString(R.string.personal_out_order));
intent.putExtra("order_id",MapUtil.sharedInstance().getDefaultValue(Constants.ORDER_ID).toString());
startActivity(intent);
WXPayEntryActivity.this.finish();
}
});
//参数都设置完成了,创建并显示出来
builder.create().show();
}
}
整个Android端微信支付就到此完成了