Android开发中,大多数电商APP都会有支付这么模块,此博客就讲一下微信支付,代码不多,很简单就可以完成,支付宝支付请看博客 Android支付之支付宝封装类
先来看看效果图
微信支付首先要去微信开发平台申请,得到相关信息,根据微信平台文档操作即可,如:appId keydeng
首先导入libammsdk.jar 包
之后在项目包名下创建 wxapi 包 如 com.zq.demo.wxapi 前提 com.zq.demo 包名乃是项目包名,不能有错。
包下有三个类
Constants.Java(注:当然这个类也可以不要)
public class Constants { public static final String APP_ID = "申请的APPID"; public static class ShowMsgActivity { public static final String STitle = "showmsg_title"; public static final String SMessage = "showmsg_message"; public static final String BAThumbData = "showmsg_thumb_data"; } }
AppRegister.java 注册
public class AppRegister extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null); msgApi.registerApp(Constants.APP_ID); } }
WXPayEntryActivity.java 支付回调
/*** * 微信支付成功回调接口 * @author zq * */ public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{ private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";private IWXAPI api; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pay_result); 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) { if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.app_tip); builder.setMessage(getString(R.string.pay_result_callback_msg, String.valueOf(resp.errCode))); builder.show(); if(resp.errCode==0)//返回参数意思 参考文档即可 { //支付成功 执行相关操作 } else {
//支付失败 } } finish(); } }
调用支付
/*** * 微信支付 */ public void wxpaly() { PayReq request = new PayReq(); request.appId =Constants.APP_ID; request.nonceStr ="iuWeKvt82vAGzxH3"; request.partnerId = "1900000109"; request.prepayId = "1101000000140415649af9fc314aa427",; request.packageValue = "Sign=WXPay"; request.timeStamp = "支付时间"; request.sign = "7FFECB600D7157C5AA49810D2D8F28BC2811827B"; api.sendReq(request); }
其中的参数为了安全一般是从后台接口获取得到的。
AndroidManifest.xml配置
<activity android:name="com.zq.demo.wxapi.WXPayEntryActivity" android:exported="true" android:launchMode="singleTop" > <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="申请的APPId" /> </intent-filter> </activity> <receiver android:name="com.zq.demo.wxapi.AppRegister" > <intent-filter> <action android:name="com.tencent.mm.plugin.openapi.Intent.ACTION_REFRESH_WXAPP" /> </intent-filter> </receiver>
权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
代码不多,主要是细节,希望对大家有所帮助。