phonegap(cordova) 自己定义插件代码篇(六)----android ,iOS 微信支付工具整合

还是那句话,在使用插件代码篇的时候,请先了解插件机制(如整合原生插件先阅读原生插件文档。非常重要。非常重要!非常重要!),如未了解,请先阅读入门篇。这里就专贴关键代码

必须先把官方sdk 依照要求一步一步的整到自己项目中。然后再来看此代码,这里是cordova 整合代码

如有不明确的。加群 38840127     

(function (cordova) {
    var define = cordova.define;

    define("cordova/plugin/wxpay", function (require, exports, module) {
        var argscheck = require('cordova/argscheck'),
	    exec = require('cordova/exec');
        exports.pay = function (orderInfo, successCB, failCB) {
            argscheck.checkArgs('AFF', 'wxpay.pay', arguments);
            if (!orderInfo) {
                failCB && failCB("请输入订单信息.");
            } else {
                exec(successCB, failCB, "WXPay", "pay", orderInfo);
            }
        };

    });
    cordova.addConstructor(function () {
        if (!window.plugins) {
            window.plugins = {};
        }
        console.log("将插件注入cordovaWXPay...");
        window.plugins.wxpay = cordova.require("cordova/plugin/wxpay");
        console.log("wxpay注入结果:" + typeof (window.plugins.wxpay));
    });
})(cordova);
Android

public class WXPayPlugin extends CordovaPlugin {

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		String WXParnter_ID = args.getString(0);
		// 预支付订单id
		String prepay_id = args.getString(1);

		// nonceStr
		String nonceStr = args.getString(2);
		String timestamp = args.getString(3);
		// 程序签名
		String wxAppSign = args.getString(4);

		if ("pay".equals(action)) {
//			Log.i("ourwxpay", prepay_id + ">>>" + ">>>" + nonceStr + ">>>"
//					+ ">>>" + wxAppSign+">>>"+timestamp+"WXParnter_ID"+WXParnter_ID+">>"+wxAppSign);

			PayReq req = new PayReq();
			req.appId = Constants.APP_ID;
			req.partnerId = WXParnter_ID;
			req.prepayId = prepay_id;
			req.packageValue = "Sign=WXPay";
			req.nonceStr = nonceStr;
			req.timeStamp = timestamp;
			// req.timeStamp = String.valueOf(genTimeStamp());
			req.sign = wxAppSign;
			// 调用支付
			boolean re = Constants.api.sendReq(req);
			Log.i("ourwxpay",re+"<<<");

			callbackContext.success();
			return true;

		} else {
			return false;
		}
	}

	 

}
</pre><p></p><p></p><pre code_snippet_id="1551972" snippet_file_name="blog_20160108_4_9274250" name="code" class="java">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);
    	Constants.api.handleIntent(getIntent(), this);
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		Constants.api.handleIntent(getIntent(), this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) { 

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			String msg = "false";
			if(resp.errCode==0){
				msg = "true";
			}
			
			// 通知到页面 支付工具 0--微信 1--支付宝 2--银联
			String jsCode = "pay.result('0','','" + msg + "')";
			yooshow.instance.ToJS(jsCode);
 
		}
	}
}


iOS

#import <Cordova/CDV.h>

@interface CDVWXPay : CDVPlugin
@property (nonatomic,copy) NSString*callbackID;
//Instance Method
-(void) pay:(CDVInvokedUrlCommand*)command ;

@end


#import "CDVWXPay.h"
#import "Order.h"
#import "Conts.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "AppDelegate.h"
@implementation CDVWXPay
@synthesize callbackID;
-(void)pay:(CDVInvokedUrlCommand *)command
{
    
    //合作者账号
    NSString* WXPartnerID = [command.arguments objectAtIndex:0];
    //预支付订单号
    NSString* WXPrepayID = [command.arguments objectAtIndex:1];
    //nonceStr
    NSString* NonceStr = [command.arguments objectAtIndex:2];
    //时间戳
    NSString* Timestamp = [command.arguments objectAtIndex:3];
    //appsign
    NSString* AppSign = [command.arguments objectAtIndex:4];
    
    PayReq* request = [[[PayReq alloc] init] autorelease];
    request.partnerId = WXPartnerID;
    request.prepayId = WXPrepayID;
    request.package =@"Sign=WXPay";
    request.nonceStr = NonceStr;
    request.timeStamp = [Timestamp intValue];
    request.sign = AppSign;
    [WXApi sendReq:request];
    
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end

-(void) onResp:(BaseResp*)resp
{
 
    if([resp isKindOfClass:[PayResp class]]){
        NSString* msg = @"false";
        switch (resp.errCode) {
            case WXSuccess:
                msg = @"true";
                 break;
                
            default:
                
                break;
        } 
        NSString *js =  [[NSString alloc]initWithFormat:@"pay.result('0','','%@')",  msg  ];
        [[AppDelegate appDelegate] runJS:js];
    } 

}



服务端相应  C# 版

/// <summary>
        /// 微信签名(预支付订单生成)
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>

        public WXPrepayOrderEntity WXPaySign(WXPayParam param)
        {
            var config = AppService.Instance.GetThirdPartyConfig();
            OrderInfo orderInfo = OrderService.Instance.GetList(o => o.OrderNO == param.OrderNO).FirstOrDefault();
            WXPayPrepayParam prepayParam = new WXPayPrepayParam();
            prepayParam.Body = orderInfo.Subject;

            // 32位内的随机串,防重发
            prepayParam.Noncestr = Guid.NewGuid().ToString().Replace("-", "");
            prepayParam.Out_Trade_NO = orderInfo.OrderNO;
            prepayParam.ClientIP = "192.168.10.1";
            prepayParam.Toatal_fee = (int)(orderInfo.TotalAmount * 100);//转换成分
            prepayParam.WXTradeType = WXTradeTypeKind.APP.ToString();
            //生成预支付订单号
            string prepayId = PayService.Instance.GenWXPayPrepayid(prepayParam);
            //再次签名
            List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
            paramList.Add(new KeyValuePair<string, string>("appid", config.WXOpenAppID));
            paramList.Add(new KeyValuePair<string, string>("noncestr", prepayParam.Noncestr));
            paramList.Add(new KeyValuePair<string, string>("package", "Sign=WXPay"));
            paramList.Add(new KeyValuePair<string, string>("partnerid", config.WXPayPartner));
            paramList.Add(new KeyValuePair<string, string>("prepayid", prepayId));
            string timestamp = Convert.ToInt64(DateTime.Now.Subtract(Convert.ToDateTime("1970-01-01")).TotalSeconds).ToString();
            paramList.Add(new KeyValuePair<string, string>("timestamp", timestamp));
            string appSign = GenWXPayAppSign(paramList);


            WXPrepayOrderEntity result = new EntityModel.Pay.Entity.WXPrepayOrderEntity();

            result.WXPrepayID = prepayId;
            result.WXPartnerID = config.WXPayPartner;
            result.WXNonceStr = prepayParam.Noncestr;
            result.WXAppSign = appSign;
            result.WXTimestamp = timestamp;
            return result;
        }


/// <summary>
        /// 验证微信支付回调,假设通过则处理订单。并返回true ,假设验证失败则直接返回false
        /// </summary>
        /// <param name="wxNotifyString"></param>
        /// <returns></returns>
        public string WXPayNotifyVerify(string wxNotifyString)
        {
            var config = AppService.Instance.GetThirdPartyConfig();

            //=======【基本信息设置】=====================================
            /* 微信公众号信息配置
            * APPID:绑定支付的APPID(必须配置)
            * MCHID:商户号(必须配置)
            * KEY:商户支付密钥。參考开户邮件设置(必须配置)
            * APPSECRET:公众帐号secert(仅JSAPI支付的时候须要配置)
            */
            WxPayConfig.APPID = config.WXOpenAppID;
            WxPayConfig.MCHID = config.WXPayPartner;
            WxPayConfig.KEY = config.WXPayPartner_Key;
            WxPayConfig.APPSECRET = config.WXOpenAppSecret;
            //=======【证书路径设置】===================================== 
            /* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时须要)
            */
            WxPayConfig.SSLCERT_PATH = "cert/apiclient_cert.p12";
            WxPayConfig.SSLCERT_PASSWORD = "";
            //=======【支付结果通知url】===================================== 
            /* 支付结果通知回调url。用于商户接收支付结果
            */
            WxPayConfig.NOTIFY_URL = config.WXPayServer_Notify;
            //=======【商户系统后台机器IP】===================================== 
            /* 此參数可手动配置也可在程序中自己主动获取
            */
            WxPayConfig.IP = "8.8.8.8";


            //=======【代理server设置】===================================
            /* 默认IP和port号分别为0.0.0.0和0。此时不开启代理(如有须要才设置)
            */
            WxPayConfig.PROXY_URL = "";

            //=======【上报信息配置】===================================
            /* 測速上报等级。0.关闭上报; 1.仅错误时上报; 2.全量上报
            */
            WxPayConfig.REPORT_LEVENL = 1;

            //=======【日志级别】===================================
            /* 日志等级,0.不输出日志;1.仅仅输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
            */
            WxPayConfig.LOG_LEVENL = 0;




            //转换数据格式并验证签名
            WxPayData notifyData = new WxPayData();
            try
            {
                notifyData.FromXml(wxNotifyString);
            }
            catch (WxPayException ex)
            {
                //若签名错误。则马上返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                return res.ToXml();

            }

            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在。则马上返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                return res.ToXml();

            }

            string transaction_id = notifyData.GetValue("transaction_id").ToString();

            //查询订单。推断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败,则马上返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                //Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                return res.ToXml();
            }
            //查询订单成功
            else
            {
                //推断该笔订单是否在商户站点中已经做过处理
                //假设没有做过处理。依据订单号(out_trade_no)在商户站点的订单系统中查到该笔订单的具体,并运行商户的业务程序
                //假设有做过处理,不运行商户的业务程序

                //注意:
                //该种交易状态仅仅在两种情况下出现
                //1、开通了普通即时到账,买家付款成功后。
                //2、开通了高级即时到账。从该笔交易成功时间算起。过了签约时的可退款时限(如:三个月以内可退款、一年以内可退款等)后。

                //成功之后改动订单状态,记帐。加花
                OrderPaySuccessParam param = new OrderPaySuccessParam();
                //订单号
                param.OrderNO = notifyData.GetValue("out_trade_no").ToString();
                //支付宝交易号
                param.TradeNO = transaction_id;
                //支付方式
                param.PayMethod = PaymentMethodKind.Online;
                //卖家收款账户
                param.Account = WxPayConfig.MCHID;
                //卖家收款账户银行
                param.Bank = PayTypeKind.WeiXin.ToString();
                //买家账户
                param.PayAccount = notifyData.GetValue("openid").ToString();
                //买家收款账户银行
                param.PayBank = notifyData.GetValue("bank_type").ToString();
                //实际支付金额
                param.TotalAmount = Convert.ToDouble(Convert.ToInt32(notifyData.GetValue("total_fee")) * 0.01);
                //支付时间
                param.PayDate = DateTime.ParseExact(notifyData.GetValue("time_end").ToString(), "yyyyMMddHHmmss", null);
                //支付工具类型
                param.PayType = PayTypeKind.WeiXin;

                OrderService.Instance.OrderPaySuccess(param);

                WxPayData res = new WxPayData();
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                //Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
                return res.ToXml();
            }
        }
        //查询微信支付订单
        private bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                return true;
            }
            else
            {
                return false;
            }
        }


phonegap(cordova) 自己定义插件代码篇(六)----android ,iOS 微信支付工具整合

上一篇:微信订阅号,获取用户openid


下一篇:微信小程序页面跳转传参