• 支付宝APP支付IOS手机端java后台版


     
     

    支付宝APP支付(IOS手机端+java后台)版

    0.介绍预览

    针对需要在IOS手机上接入原生微信支付宝场景,调用支付宝。如图:

                   

    1.资料准备

    1.1 账号注册

    打开https://openhome.alipay.com,注册支付宝开放平台开发者账号

    1.2 开发者认证

    登录,进入开发者中心,进行开发者资质认证,并创建移动应用。

    1.3 签约应用

    创建应用后上传相关资料,上线应用并通过审核。审核通过后点击应用,进行签约,此步骤不能省略,否则或报ISV权限不足。

     

    1.4 应用配置

    打开应用信息,配置一下内容,接口签名可下载支付宝签名验签工具进行生成,生成完成后将公钥复制到平台上。

     

    2.Java后台开发

    添加依赖

     1 [html] view plain copy
     2 
     3  print?
     4 <!-- 支付宝支付依赖 -->  
     5 <dependency>  
     6     <groupId>com.pentahohub.nexus</groupId>  
     7     <artifactId>alipay-sdk-java</artifactId>  
     8     <version>20170615110434</version>  
     9     <scope>system</scope>  
    10     <systemPath>${basedir}/libs/alipay-sdk-java20170615110434.jar</systemPath>  
    11 </dependency>  
    12 <dependency>  
    13     <groupId>commons-logging</groupId>  
    14     <artifactId>commons-logging</artifactId>  
    15     <version>1.1.1</version>  
    16 </dependency>  

    生成统一订单

     1 [java] view plain copy
     2 
     3  print?
     4 /** 
     5 * account 总金额 
     6 * sid 用户id 
     7 * desc 节点id 
     8 * @param request 
     9 * @return 
    10 */  
    11 @RequestMapping(value="/pay/alipay/signprams",produces="application/json;charset=utf-8")  
    12 @ResponseBody  
    13 public String signprams(HttpServletRequest request){  
    14 String res = "{code:404}";  
    15 try{  
    16     String totalAmount = request.getParameter("account");  
    17     String sid = request.getParameter("sid");  
    18     String nid = request.getParameter("desc");  
    19     String subject = "电费充值";  
    20     String body = "贵大电费预付费充值";  
    21     String prefix = "ALE"+sid+"E";  
    22     String out_trade_no = WXRequestUtil.getTradeNo(prefix);  
    23   
    24     //实例化客户端  
    25     AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do   
    26   
    27 ",  
    28         AlipayUtil.APPID, AlipayUtil.PRIVATE_KEY, "json", AlipayUtil.CHARSET, AlipayUtil.PUBLIC_KEY, "RSA2");  
    29     //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay  
    30     AlipayTradeAppPayRequest alirequest = new AlipayTradeAppPayRequest();  
    31     //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。  
    32     AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();  
    33     model.setPassbackParams(URLEncoder.encode(body.toString()));;  //描述信息  添加附加数据  
    34     model.setSubject(subject); //商品标题  
    35     model.setOutTradeNo(out_trade_no); //商家订单编号  
    36     model.setTimeoutExpress("30m"); //超时关闭该订单时间  
    37     model.setTotalAmount(totalAmount);  //订单总金额  
    38     model.setProductCode("QUICK_MSECURITY_PAY"); //销售产品码,商家和支付宝签约的产品码,为固定值QUICK_MSECURITY_PAY  
    39     alirequest.setBizModel(model);  
    40     alirequest.setNotifyUrl("http://pay.gzdxfszx.com/pay/alipay/notify.xs   
    41   
    42 ");  //回调地址  
    43     String orderStr = "";  
    44     try {  
    45     //这里和普通的接口调用不同,使用的是sdkExecute  
    46     AlipayTradeAppPayResponse response = alipayClient.sdkExecute(alirequest);  
    47     orderStr = response.getBody();  
    48 //                System.out.println(orderStr);//就是orderString 可以直接给客户端请求,无需再做处理。  
    49     } catch (AlipayApiException e) {  
    50     e.printStackTrace();  
    51     }  
    52   
    53     String sign = MD5Encode.encode(out_trade_no);  
    54     savePayLog(out_trade_no,totalAmount,sid,body, sign,nid,1);  
    55   
    56     JSONObject resObj = new JSONObject();  
    57     resObj.put("code",ResponseCode.HTTP_SUCCESS);  
    58     resObj.put("out_trade_no",out_trade_no);  
    59     resObj.put("sign",sign);  
    60     resObj.put("orderStr",orderStr);  
    61   
    62     res = resObj.toJSONString();  
    63 }catch (Exception e){  
    64     e.printStackTrace();  
    65 }  
    66 return res;  
    67 }  


    异步通知处理

    [java] view plain copy
    
     print?
    @RequestMapping(value="/pay/alipay/notify",produces="application/json;charset=utf-8")  
        @ResponseBody  
        public String notify(HttpServletRequest request){  
            Map requestParams = request.getParameterMap();  
            System.out.println("支付宝支付结果通知"+requestParams.toString());  
            //获取支付宝POST过来反馈信息  
            Map<String,String> params = new HashMap<String,String>();  
      
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {  
                String name = (String) iter.next();  
                String[] values = (String[]) requestParams.get(name);  
                String valueStr = "";  
                for (int i = 0; i < values.length; i++) {  
                    valueStr = (i == values.length - 1) ? valueStr + values[i]  
                            : valueStr + values[i] + ",";  
                }  
                //乱码解决,这段代码在出现乱码时使用。  
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");  
                params.put(name, valueStr);  
            }  
            //切记alipaypublickey是支付宝的公钥,请去open.alipay.com   
      
    对应应用下查看。  
            //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)  
            try {  
                //验证签名  
                boolean flag = AlipaySignature.rsaCheckV1(params, AlipayUtil.PUBLIC_KEY, AlipayUtil.CHARSET, "RSA2");  
                if(flag){  
                    if("TRADE_SUCCESS".equals(params.get("trade_status"))){  
    //                    //付款金额  
    //                    String amount = params.get("buyer_pay_amount");  
    //                    //支付宝交易号  
    //                    String trade_no = params.get("trade_no");  
    //                    //附加数据  
    //                    String passback_params = URLDecoder.decode(params.get("passback_params"));  
      
                        //商户订单号  
                        String out_trade_no = params.get("out_trade_no");  
                        updateOrderInfo(out_trade_no,MD5Encode.encode(out_trade_no));  
                    }  
                }  
            } catch (AlipayApiException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            return "success";  
        }  

    3.IOS客户端开发

    导入支付宝开发包

     

    添加URL Types

     

    在需要调用支付宝的地方实现方法

    [objc] view plain copy
    
     print?
    -(void)aliPay  
    {  
        [MBProgressHUD showMessage:@"跳转中,请稍候"];  
        NSString *appScheme = @"alisdkdemo";  
      
        NSString *userUrlStr = [NSString stringWithFormat:@"%@?sid=%@&account=%@&desc=%@", ALI_PREPAY_URL, self.student.sid,self.payJinE,self.student.nid];  
        NSURL *url = [NSURL URLWithString:userUrlStr];  
        //     NSLog(@"userUrlStr = %@", userUrlStr);  
          
        NSURLRequest *request = [NSURLRequest requestWithURL:url];  
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];  
          
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {  
            [MBProgressHUD hideHUD];  
              
    //                 NSLog(@"支付宝支付的response = %@", operation.responseString);  
            NSData *JSONData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];  
            NSDictionary *userDict = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];  
              
            NSString *orderString = [userDict objectForKey:@"orderStr"];  
            self.sign = [userDict objectForKey:@"sign"];  
            self.ordnum = [userDict objectForKey:@"out_trade_no"];  
              
            [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {  
                NSLog(@"reslut = %@",resultDic);  
                [MBProgressHUD hideHUD];  
                  
                NSString *resultStatus = [resultDic objectForKey:@"resultStatus"];  
                if([resultStatus isEqualToString:@"9000"]){  
                    // 支付成功,更新用户信息  
                    [self payDidFinish];  
                }else{  
                    // 支付失败,  
                    [self setupAlertControllerWithTitle:@"支付宝支付结果" messge:@"本次支付未完成,您可以稍后重试!" confirm:@"好的"];  
                }  
                  
            }];  
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
            [MBProgressHUD hideHUD];  
            NSLog(@"发生错误!%@",error);  
        }];  
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];  
        [queue addOperation:operation];  
          
          
          
    }  

    个人实例~~

    1.点击支付按钮

     1 - (void)alipayBtnClick{
     2 
     3     [HWSShopCartHttpRequst requestOrderPayUseAliPayWithOrderNo:self.orderNo Success:^(NSString *code, NSDictionary *dataDic) {
     4         
     5        NSString *paramsStr = dataDic[@"requestParams"];
     6         [[AlipaySDK defaultService] payOrder:paramsStr fromScheme:kAppScheme callback:^(NSDictionary *resultDic) {
     7             NSLog(@"reslut = %@",resultDic);
     8         }];
     9         
    10     } andFailure:^{
    11         
    12     }];
    13 
    14 }

    2.请求内部封装的代码实例

     1 /**
     2  *  统一下单支付宝支付
     3  *  @param orderNo         订单编号
     4  *
     5  *  @param success         成功
     6  *  @param failure         失败
     7  */
     8 + (void)requestOrderPayUseAliPayWithOrderNo:(NSString*)orderNo
     9                                          Success:(void (^)(NSString *code,NSDictionary *dataDic))success andFailure:(void(^)(void))failure
    10 {
    11     
    12     [KSHttpRequest post:[NSString stringWithFormat:@"%@%@",HOST,aliPay] parameters:@{@"orderNo":orderNo} success:^(id result) { 
    13         
    14         if ([result[@"code"] isEqualToString:@"1000"]) {
    15             
    16             NSLog(@"%@",result);
    17             
    18             NSDictionary *dataDic = result[@"data"];
    19             success(result[@"code"],dataDic);
    20             
    21         }else{
    22             failure();
    23             [MBProgressHUD showMessage:result[@"message"]];
    24         }
    25         
    26     } failure:^(NSError *error) {
    27         failure();
    28     }];
    29 }

     //待续

    https://docs.open.alipay.com/204/105295/ 

  • 相关阅读:
    31款简单实用的CSS+JS下拉菜单脚本
    POWERDESIGNER 15 反向生成PDM[转]
    WCF异常信息
    下载文件
    分区表的维护 ORA14402 更新分区关键字列
    [转]Winform框架之字典数据管理
    用例图(User Case)
    datetime的时值
    JS date对象的减法处理
    JS获取当前页面的高度
  • 原文地址:https://www.cnblogs.com/henusyj-1314/p/8192987.html
Copyright © 2020-2023  润新知