欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-25 09:15:46
0.介绍预览 针对需要在ios手机上接入原生微信支付场景,调用微信进行支付。如图: 1.资料准备 1.1 账号注册 打开https://open.weixin....

0.介绍预览

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

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

1.资料准备

1.1 账号注册

打开https://open.weixin.qq.com,注册微信开放平台开发者账号

1.2 开发者认证

登录,进入账号中心,进行开发者资质认证。

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

1.3 注册应用

认证完成后,进入管理中心,新建移动应用。填写应用资料,其中android版应用签名可通过扫码安装温馨提供的应用获得,详细参考微信文档。创建完成后点击查看,申请开通微信支付。一切准备就绪!

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

2.java后台开发

添加依赖

<!-- 微信支付依赖 -->
<dependency>
 <groupid>org.xmlpull</groupid>
 <artifactid>xmlpull</artifactid>
 <version>1.1.3.1 </version>
</dependency>
<dependency>
 <groupid>net.sf.json-lib</groupid>
 <artifactid>json-lib</artifactid>
 <version>2.3</version>
 <classifier>jdk15</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
 <groupid>com.thoughtworks.xstream</groupid>
 <artifactid>xstream</artifactid>
 <version>1.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.ning/async-http-client -->
<dependency>
 <groupid>com.ning</groupid>
 <artifactid>async-http-client</artifactid>
 <version>1.8.13</version>
</dependency>

生成统一订单

@requestmapping(value="/pay/wxpay/params",produces="application/json;charset=utf-8")
 @responsebody
 public string signprams(httpservletrequest request){
  string res = "{code:404}";
  try{
  // 充值金额
   string account = request.getparameter("account");
  // 用户id
   string sid = request.getparameter("sid");
   string subject = "订单标题";
   string body = "订单描述";
 
   int acc = (int) (double.valueof(account) * 100);
   string appid = "您的appid";
   string out_trade_no = "生成您的订单号";
  // 生成订单数据
   sortedmap<string, string> paymap = genorderdata(request, subject, body, acc, appid, out_trade_no);
 
   savepaylog(out_trade_no,account,sid,body,paymap.get("paysign"),nid,2);
 
   // 4.返回数据
   res = buildpayres(paymap,out_trade_no);
  }catch (exception e){
   e.printstacktrace();
   res = "{code:500}";
  }
  return res;
 }
 
 private sortedmap<string, string> genorderdata(httpservletrequest request, string subject, string body,
          int acc, string appid, string out_trade_no)
   throws ioexception, executionexception, interruptedexception, xmlpullparserexception {
  sortedmap<string, string> paramap = new treemap<string, string>();
  paramap.put("appid", appid);
  paramap.put("attach", subject);
  paramap.put("body", body);
  paramap.put("mch_id", "您的商户id,到商户平台查看");
  paramap.put("nonce_str", create_nonce_str());
  paramap.put("notify_url", "http://pay.xxxxx.com/pay/wxpay/notify.htm ");// 此路径是微信服务器调用支付结果通知路径
  paramap.put("out_trade_no", out_trade_no);
  paramap.put("spbill_create_ip", request.getremoteaddr());
  paramap.put("total_fee", acc+"");
  paramap.put("trade_type", "app");
  string sign = createsign(paramap);
  paramap.put("sign", sign);
  // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder 
  string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  string xml = getrequestxml(paramap);
  string xmlstr = httpkit.post(url, xml);
 
  // 预付商品id
  string prepay_id = "";
  if (xmlstr.indexof("success") != -1) {
   map<string, string> map = wxrequestutil.doxmlparse(xmlstr);
   prepay_id = (string) map.get("prepay_id");
  }
 
  sortedmap<string, string> paymap = new treemap<string, string>();
  paymap.put("appid", appid);
  paymap.put("partnerid", "您的商户id,到商户平台查看");
  paymap.put("prepayid", prepay_id);
  paymap.put("package", "sign=wxpay");
  paymap.put("noncestr", create_nonce_str());
  paymap.put("timestamp", wxrequestutil.create_timestamp());
  string paysign = createsign(paymap);
  paymap.put("paysign", paysign);
  return paymap;
 }
 
 //请求xml组装 
 public static string getrequestxml(sortedmap<string,string> parameters){ 
  string sign = "";
   stringbuffer sb = new stringbuffer(); 
   sb.append("<xml>"); 
   set es = parameters.entryset(); 
   iterator it = es.iterator(); 
   while(it.hasnext()) { 
    map.entry entry = (map.entry)it.next(); 
    string key = (string)entry.getkey(); 
    string value = (string)entry.getvalue(); 
//    if ("attach".equalsignorecase(key)||"body".equalsignorecase(key)||"sign".equalsignorecase(key)) { 
//     sb.append("<"+key+">"+value+"</"+key+">"); 
//    }
    if ("sign".equalsignorecase(key)){
    sign = "<"+key+">"+value+"</"+key+">";
    }else { 
     sb.append("<"+key+">"+value+"</"+key+">"); 
    } 
   } 
   sb.append(sign); 
   sb.append("</xml>"); 
   return sb.tostring(); 
  } 
 
 //生成签名 
 public string createsign(sortedmap<string,string> parameters){ 
   stringbuffer sb = new stringbuffer(); 
   set es = parameters.entryset(); 
   iterator it = es.iterator(); 
   while(it.hasnext()) { 
    map.entry entry = (map.entry)it.next(); 
    string k = (string)entry.getkey(); 
    object v = entry.getvalue(); 
    if(null != v && !"".equals(v) 
      && !"sign".equals(k) && !"key".equals(k)) { 
     sb.append(k + "=" + v + "&"); 
    } 
   } 
   sb.append("key=" + wxconfig.app_pertner_key); 
   system.out.println(sb.tostring());
   string sign = md5utils.md5encode(sb.tostring(),"utf-8").touppercase(); 
   return sign; 
  } 
 
 
 public string create_nonce_str() {
 string chars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789";
 string res = "";
 for (int i = 0; i < 32; i++) {
 random rd = new random();
 res += chars.charat(rd.nextint(chars.length() - 1));
 }
 return res;
 }

3.ios客户端开发

导入微信开发包

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

添加url types

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

在appdelegate.m中注册应用

#import "appdelegate.h"
#import "xstabbarviewcontroller.h"
#import <alipaysdk/alipaysdk.h>
#import "wxapi.h"
 
@interface appdelegate ()<wxapidelegate>
 
@end
 
@implementation appdelegate
 
 
- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions {
 // override point for customization after application launch.
 
// [nsthread sleepfortimeinterval:2.0];
 
 // 进入主控制器
 self.window = [[uiwindow alloc] init];
 self.window.frame = [uiscreen mainscreen].bounds;
 self.window.rootviewcontroller = [[xstabbarviewcontroller alloc] init];
 
 [self.window makekeyandvisible];
 
 //向微信注册应用。
 [wxapi registerapp:@"wxfb96c2a9b531be26"];
 
 return yes;
}
 
-(void) onresp:(baseresp*)resp
{
//  nslog(@" ----onresp %@",resp);
 /*
  errcode err_ok = 0(用户同意)
  err_auth_denied = -4(用户拒绝授权)
  err_user_cancel = -2(用户取消)
  code 用户换取access_token的code,仅在errcode为0时有效
  state 第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendreq时传入,由微信终端回传,state字符串长度不能超过1k
  lang 微信客户端当前语言
  country 微信用户当前国家信息
  */
 if ([resp iskindofclass:[sendauthresp class]]) //判断是否为授权请求,否则与微信支付等功能发生冲突
 {
  sendauthresp *aresp = (sendauthresp *)resp;
  if (aresp.errcode== 0)
  {
   //   nslog(@"code %@",aresp.code);
   [[nsnotificationcenter defaultcenter] postnotificationname:@"wechatdidloginnotification" object:self userinfo:@{@"code":aresp.code}];
  }
 }else{ // 支付请求回调
  //支付返回结果,实际支付结果需要去微信服务器端查询
  nsstring *strmsg = [nsstring stringwithformat:@"支付结果"];
  nsstring *respcode = @"0";
  switch (resp.errcode) {
   case wxsuccess:
    strmsg = @"支付结果:成功!";
    //    nslog(@"支付成功-paysuccess,retcode = %d", resp.errcode);
    respcode = @"1";
    break;
   default:
    strmsg = [nsstring stringwithformat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errcode,resp.errstr];
    //    nslog(@"错误,retcode = %d, retstr = %@", resp.errcode,resp.errstr);
    respcode = @"0";
    break;
  }
  [[nsnotificationcenter defaultcenter] postnotificationname:@"wechatdidpaynotification" object:self userinfo:@{@"respcode":respcode}];
 }
}
 
 
//ios 9.0 之前的处理方法不保证正确,如有错误还望指正
- (bool)application:(uiapplication *)application openurl:(nsurl *)url sourceapplication:(nsstring *)sourceapplication annotation:(id)annotation
{
 nslog(@"ios 9.0 之前");
 return [self applicationopenurl:url];
}
 
-(bool)application:(uiapplication *)app openurl:(nsurl *)url options:(nsdictionary<uiapplicationopenurloptionskey,id> *)options {
 nslog(@"ios 9.0 之后");
 return [self applicationopenurl:url];
}
 
- (bool)applicationopenurl:(nsurl *)url
{
 if([[url absolutestring] rangeofstring:@"wxfb96c2a9b531be26://pay"].location == 0){
  return [wxapi handleopenurl:url delegate:self];
 }
 if ([url.host isequaltostring:@"safepay"])
 {
  [[alipaysdk defaultservice] processorderwithpaymentresult:url standbycallback:nil];
  return yes;
 }
 return yes;
}
 
}

在需要支付的controller中接受微信支付通知

- (void)viewdidload {
 [super viewdidload];
 
 // 接受微信支付通知
 [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(wechatdidpaynotification:) name:@"wechatdidpaynotification" object:nil];
}

向服务器端获取统一订单,并拉起微信进行支付

-(void)weixinpay
{
 nsstring *userurlstr = [nsstring stringwithformat:@"%@?sid=%@&account=%@&desc=%@", wx_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];
 
 [mbprogresshud showmessage:@"跳转中,请稍候"];
 [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];
  
  // 调用微信支付
  payreq *request = [[payreq alloc] init];
  /** 商家向财付通申请的商家id */
  request.partnerid = [userdict objectforkey:@"partnerid"];
  /** 预支付订单 */
  request.prepayid= [userdict objectforkey:@"prepayid"];
  /** 商家根据财付通文档填写的数据和签名 */
  request.package = [userdict objectforkey:@"package"];
  /** 随机串,防重发 */
  request.noncestr= [userdict objectforkey:@"noncestr"];
  /** 时间戳,防重发 */
  request.timestamp= [[userdict objectforkey:@"timestamp"] intvalue];
  /** 商家根据微信开放平台文档对数据做的签名 */
  request.sign= [userdict objectforkey:@"sign"];
  self.sign = request.sign;
  self.ordnum = [userdict objectforkey:@"ordnum"];
  
 
  [wxapi sendreq: request];
 }failure:^(afhttprequestoperation *operation, nserror *error) {
  [mbprogresshud hidehud];
  nslog(@"发生错误!%@",error);
 }];
 nsoperationqueue *queue = [[nsoperationqueue alloc] init];
 [queue addoperation:operation];
 
}
// 微信支付结果
-(void)wechatdidpaynotification:(nsnotification *)notification
{
// nslog(@"wechatdidpaynotification");
 nsdictionary *namedictionary = [notification userinfo];
 nsstring *respcode = [namedictionary objectforkey:@"respcode"];
 if([respcode isequaltostring:@"1"]){
  // 支付成功,更新用户信息
  [self paydidfinish];
 }else{
  // 支付失败,
  [self setupalertcontrollerwithtitle:@"微信支付结果" messge:@"本次支付未完成,您可以稍后重试!" confirm:@"好的"];
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。