Android 移动支付插件demo(主应用+支付插件)

本文详细介绍了一种基于Android的第三方支付插件开发流程,包括应用如何调用支付插件及支付插件的核心逻辑实现。文章通过具体示例介绍了如何使用AIDL进行进程间通信,实现支付功能。

     本文主要讲解下类似于支付宝、银联支付的第三方支付插件开发流程(应用调用支付插件流程+支付插件主逻辑开发)。

一、首先介绍下什么是aidl和icp:

     aidl是 Android Interface definition language的缩写,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口;

     icp:interprocess communication :内部进程通信。

二、支付插件开发要先掌握aidl使用方法,下面我来介绍下支付插件开发的流程:

1、我们需要创建一个支付插件工程,如图所示:


在IPayService.aidl中我们定义了支付、注册回调、注销回调等方法,代码如下:

package com.lukejun.app;

import com.lukejun.app.IRemoteServiceCallback;

interface IPayService {
	String pay(String orderInfo);
	String prePay(String pre);
	void registerCallback(IRemoteServiceCallback callback);
	String test();
	void unregisterCallback(IRemoteServiceCallback callback);
}
IRemoteServiceCallback.aidl就是上面用到的回调接口,其中startActivity方法是从主应用中activity进入支付插件中activity,在插件activity中可做支付业务操作,代码如图:

package com.lukejun.app;

import android.os.Bundle;

interface IRemoteServiceCallback {
	void startActivity(String packageName , String className, int iCallingPid, in Bundle bundle);
	boolean isHideLoadingScreen();
	void payEnd(boolean arg0, String arg1);
}
接下来贴MyRemoteService代码,如图:

public class MyRemoteService extends Service{


	public class MIPayService extends IPayService.Stub{
		IRemoteServiceCallback iCallback = null;
		@Override
		public String pay(String orderInfo) throws RemoteException {
			if(iCallback != null){
				Bundle bundle = new Bundle();
				bundle.putString("orderInfo", orderInfo);
				iCallback.startActivity(getPackageName(), "com.lukejun.app.ShowActivity", 1, bundle);
				
			}
			String result = null;
			while (true) {
				result = PayResult.getInstance().getResult();
				PayResult.getInstance().setResult(null);
				if(null != result){
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
				
			}
			
			return result;
		}

		@Override
		public String prePay(String pre) throws RemoteException {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public void registerCallback(IRemoteServiceCallback callback)
				throws RemoteException {
			iCallback = callback;
			
		}

		@Override
		public String test() throws RemoteException {
			
			return null;
		}

		@Override
		public void unregisterCallback(IRemoteServiceCallback callback)
				throws RemoteException {
			iCallback = null;
			
		}
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {

		return new MIPayService() ;
	}
	@Override
	public void onCreate() {
		
		super.onCreate();
		
	}
	 
	@Override
	public void onDestroy() {

		super.onDestroy();
	}
	
}
我们通过实现IPayService类,在pay方法中读取从主应用中传来的支付订单信息(orderInfo),调用IRemoteServiceCallback的startactivity方法进入插件页面进行业务操作,然后建立while循环一直等待插件业务处理后的支付结果,得到支付结果后跳出循环,把支付结果返回给主应用。

2、支付插件端的主要逻辑已经完成了,接下来我们介绍主应用调用插件方法,工程截图如下:


把支付插件端的IPayService和IRemoteServiceCallback连包一起拷贝到主应用要(保持包名一致),一般第三方支付都会打包成jar包供主应用调用,下面贴下主应用调用示例:

public class TextActivity extends Activity{
	
	private MobileSecurePayHelper mspHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mspHelper = new MobileSecurePayHelper(this);
		findViewById(R.id.Button01).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				boolean isMobile_spExist = mspHelper.detectMobile_sp();
				//检测插件支付安装,如果没有安装提示安装和是否插件有更新。
                if (!isMobile_spExist){
                    return;
                }
				MobileSecurePayer msp = new MobileSecurePayer();
				boolean bRet = msp.pay("content", mHandler, Constants.RQF_PAY,
                        TextActivity.this);
				Log.i(TextActivity.class.getSimpleName(), String.valueOf(bRet));
			}
		});
		
	}
	
	private Handler mHandler = createHandler();
	private Handler createHandler()
    {
        return new Handler(){
            public void handleMessage(Message msg)
            {
                String strRet = (String) msg.obj;
               Toast.makeText(TextActivity.this, strRet, Toast.LENGTH_SHORT).show();
                super.handleMessage(msg);
            }
        };

    }
}
下面讲解下pay方法,代码如下:

public boolean pay(final String strOrderInfo, final Handler callback,
			final int myWhat, final Activity activity) {
		if (mbPaying)
			return false;
		mbPaying = true;
		mActivity = activity;
		// bind the service.
		// 绑定服务
		if (payService == null) {
			// 绑定安全支付服务需要获取上下文环境,
			// 如果绑定不成功使用mActivity.getApplicationContext().bindService
			// 解绑时同理
			mActivity.getApplicationContext().bindService(
					new Intent("com.lukejun.app.action.MY_REMOTE_SERVICE"),
					mSecurePayConnection, Context.BIND_AUTO_CREATE);		
		}
		// else ok.
		// 实例一个线程来进行支付
		new Thread(new Runnable() {
			public void run() {
				try {
					// wait for the service bind operation to completely
					// finished.
					// Note: this is important,otherwise the next
					// payService.Pay()
					// will fail.
					// 等待安全支付服务绑定操作结束
					// 注意:这里很重要,否则payService.pay()方法会失败
					synchronized (lock) {
						if (payService == null)
							lock.wait();
					}					
					// register a Callback for the service.
					// 为安全支付服务注册一个回调
					payService.registerCallback(mCallback);

					// call the MobileSecurePay service.
					// 调用安全支付服务的pay方法
					String strRet = payService.pay(strOrderInfo);
					BaseHelper.log(TAG, "服务端支付结果:" + strRet);
					
					// set the flag to indicate that we have finished.
					// unregister the Callback, and unbind the service.
					// 将mbPaying置为false,表示支付结束
					// 移除回调的注册,解绑安全支付服务
					mbPaying = false;
					payService.unregisterCallback(mCallback);
					mActivity.getApplicationContext().unbindService(
							mSecurePayConnection);

					// send the result back to caller.
					// 发送交易结果
					Message msg = new Message();
					msg.what = myWhat;
					msg.obj = strRet;
					callback.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
					// send the result back to caller.
					// 发送交易结果
					Message msg = new Message();
					msg.what = myWhat;
					msg.obj = e.toString();
					callback.sendMessage(msg);
				}
			}
		}).start();

		return true;
	}
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
		/**
		 * This is called by the remote service regularly to tell us about new
		 * values. Note that IPC calls are dispatched through a thread pool
		 * running in each process, so the code executing here will NOT be
		 * running in our main thread like most other things -- so, to update
		 * the UI, we need to use a Handler to hop over there. 通过IPC机制启动安全支付服务
		 */
		public void startActivity(String packageName, String className,
				int iCallingPid, Bundle bundle) throws RemoteException {
			Intent intent = new Intent(Intent.ACTION_MAIN, null);

			if (bundle == null)
				bundle = new Bundle();
			// else ok.

			try {
				bundle.putInt("CallingPid", iCallingPid);
				intent.putExtras(bundle);
			} catch (Exception e) {
				e.printStackTrace();
			}

			intent.setClassName(packageName, className);
			mActivity.startActivity(intent);
		}

		/**
		 * when the msp loading dialog gone, call back this method.
		 */
		@Override
		public boolean isHideLoadingScreen() throws RemoteException {
			return false;
		}

		/**
		 * when the current trade is finished or cancelled, call back this
		 * method.
		 */
		@Override
		public void payEnd(boolean arg0, String arg1) throws RemoteException {

		}

	};
3、demo运行流程:把RemoteServiceText工程的apk安装包复制到 RemoteClientText的assets文件中中,然后运行RemoteClientText工程,就介绍到这里,如有需要可以自己下载代码看看。
代码下载:http://download.youkuaiyun.com/detail/lukejun1988/7368517


支付宝手机支付接口搞了三天了,连支付宝的技术人员都没能帮我解决问题,在百度找了很多和我一样问题的,都无法解决。 主要问题就是,使用0001加密,返回值无法验证。 求人不如求己,我还是自己认真的阅读了下手册,仔细的分析下代码,终于把问题给解决了。 废话不多说,直接上菜。 1、本程序直接复制到你的根目录即可 (没有修改过ECSHOP核心文件的前提下) 2、/alipay/key/ 文件夹里有个两个文件alipay_public_key.pem (公钥) rsa_private_key.pem (私钥) 公钥和私钥的配置方法很简单,看手册会看晕的。我简化点说。 (1)打开 openssl(openssl生成工具 用完可删) 文件夹。运行这个文件夹下的 /bin/openssl.exe程序 (2)打开 openssl(openssl生成工具 用完可删) 文件夹下的 /bin/生成命令.txt (3)按照1、2、3的顺序,在OpenSSL.exe程序中运行。操作完成后。 你会发现 /bin 文件夹下面多了两个.pem文件 和 一个.txt的文件 (4)将rsa_public_key.pem 用记事本打开,将前缀和后缀之间的内容复制(即-----BEGIN PUBLIC KEY-----和-----END PUBLIC KEY----- 之间的内容) (5)进入支付宝签约管理,点击查看PID | Key 然后点击 无线产品密钥管理(wap专用) 查看 (6)点击RSA加密:添加密钥(或查看密钥) 将刚刚复制的内容粘贴到这个文本框内,记得一定要删除所有的空格,开头和结尾一定要不要有空格。点击保存(或修改) (7)完成后点击查看支付宝公钥,将里面的内容复制出来,粘贴到/alipay/key/alipay_public_key.pem 的文件里,格式已经在该文件里写的很清楚的。 (8)将刚刚生成的rsa_private_key.pem文件里的内容复制到/alipay/key/rsa_private_key.pem 里,注意格式。 3、完成后直接上传到网站根目录即可。 4、注意,本程序是直接覆盖alipay.php的,如果你想保留支付宝的网页支付插件,请慎用,建议新建一个手机网站使用。 本人并不是技术特别厉害的程序员,本程序经过N多测试均未发现问题,如果你无法正常使用,极有可能是你的公钥没有配置好,可以联系支付宝的技术教你弄弄。 如果你发现我写的代码有点冗余,请与我联系,我们共同完善。QQ:927822902 特别声明:本人平时特别忙,如果是想加QQ寻求一对一解决问题的,请勿加。付费例外:)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值