ios微信支付 注意事项

1.先到微信官网下载所使用的SDK   微信官网下载地址https://open.weixin.qq.com

2.配置info信息

        1>  在自己的工程TARGETS->Info->URL Types下填写你注册的URL Schemes .

2>  在Custom iOS Target Properties 中添加LSApplicationQueriesSchemes字段,添加上weixin

3.APPDelegate的设置

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//注册微信

 [WXApiregisterApp:WEIXIN_AppID];//微信

}


-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url

{

return [WXApihandleOpenURL:url delegate:self];

}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

{

return [WXApihandleOpenURL:url delegate:self];

}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options

{

  /*! @brief处理微信通过URL启动App时传递的数据

   *

   * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。

   * @param url微信启动第三方应用时传递过来的URL

   * @param delegate  WXApiDelegate对象,用来接收微信触发的消息。

   * @return成功返回YES,失败返回NO

   */

  return [WXApihandleOpenURL:url delegate:self];

}

//微信支付成功后会走的代理函数

-(void) onResp:(BaseResp*)resp

{

  if ([respisKindOfClass:[PayRespclass]]){

      PayResp*response=(PayResp*)resp;

      switch(response.errCode){

        caseWXSuccess:

          //服务器端查询支付通知或查询API返回的结果再提示成功

          NSLog(@"支付成功");

          break;

        default:

          NSLog(@"支付失败,retcode=%d",resp.errCode);

          break;

      }

    }

}


4.配置统一下单接口

////////////生成签名的方法/////////////


//创建package签名

-(NSString*) createMd5Sign:(NSMutableDictionary*)dict

{

  NSMutableString *contentString  =[NSMutableStringstring];

  NSArray *keys = [dictallKeys];

  //按字母顺序排序

  NSArray *sortedArray = [keyssortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2) {

    return [obj1compare:obj2 options:NSNumericSearch];

  }];

  //拼接字符串

  for (NSString *categoryIdin sortedArray) {

    if (   ![[dictobjectForKey:categoryId]isEqualToString:@""]

        && ![categoryId isEqualToString:@"sign"]

        && ![categoryId isEqualToString:@"key"]

        )

    {

      [contentString appendFormat:@"%@=%@&", categoryId, [dictobjectForKey:categoryId]];

    }

    

  }

  //添加key字段

  [contentString appendFormat:@"key=%@",WEIXIN_APISecret];

  //得到MD5 sign签名

  NSString *md5Sign =[selfgetmd5WithString:contentString];//[WXUtil md5:contentString];

  

  return md5Sign.uppercaseString;

}


- (NSString*)getmd5WithString:(NSString *)string

{

  const char* original_str=[string UTF8String];

  unsignedchar digist[CC_MD5_DIGEST_LENGTH];//CC_MD5_DIGEST_LENGTH = 16

  CC_MD5(original_str,strlen(original_str), digist);

  NSMutableString* outPutStr = [NSMutableStringstringWithCapacity:10];

  for(int  i =0; i<CC_MD5_DIGEST_LENGTH;i++){

    [outPutStr appendFormat:@"%02x", digist[i]];//小写x表示输出的是小写MD5,大写X表示输出的是大写MD5

  }

  return [outPutStrlowercaseString];

}

//附加CC_MD5_DIGEST_LENGTH需支持#import <CommonCrypto/CommonDigest.h>头文件


////////////////将参数转化为XML格式///////////////////////


//获取package带参数的签名包

-(NSString *)genPackage:(NSMutableDictionary*)packageParams

{

  NSString *sign;

  NSMutableString *reqPars=[NSMutableStringstring];

  //生成签名

  sign        = [selfcreateMd5Sign:packageParams];

  //生成xmlpackage

  NSArray *keys = [packageParamsallKeys];

  [reqPars appendString:@"<xml>"

   ];

  for (NSString *categoryIdin keys) {

    [reqPars appendFormat:@"<%@>%@</%@>"

     , categoryId, [packageParams objectForKey:categoryId],categoryId];

  }

  [reqPars appendFormat:@"<sign>%@</sign>"

   , sign];

  [reqPars appendString:@"</xml>"

   ];

  

  return [NSStringstringWithString:reqPars];

}


///////////////配置统一下单接口参数和调用微信支付参数/////////////

{

  //============================================================

  // V3&V4支付流程实现

  //注意:参数配置请查看服务器端Demo

  // 更新时间:20151120

  //============================================================

  if (![WXApiisWXAppInstalled])

  {

    [MBProgressHUDshowSuccess:[ConstantgetStringWithKey:@"WX_App_Installed"]toView:nil];

    return;

  }

  NSString *urlString   =@"https://api.mch.weixin.qq.com/pay/unifiedorder";

  NSURL *url=[NSURLURLWithString:urlString];

  NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url

                                                         cachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:20];

  NSString *noncestr  = [NSStringstringWithFormat:@"%d",rand()];

  NSMutableDictionary *packageParams = [NSMutableDictionarydictionary];

  [packageParams setObject:WEIXIN_AppID  forKey:@"appid"];      //开放平台appid

  [packageParams setObject:WEIXIN_MchId  forKey:@"mch_id"];     //商户号

  [packageParams setObject:@"WEB"  forKey:@"device_info"];//支付设备号或门店号

  [packageParams setObject: noncestr    forKey:@"nonce_str"];  //随机串

  [packageParams setObject:@"APP"    forKey:@"trade_type"]; //支付类型,固定为APP

  [packageParams setObject: [dictobjectForKey:@"productName"]   forKey:@"body"];       //订单描述,展示给用户

  [packageParams setObject: [dictobjectForKey:@"notify_url"forKey:@"notify_url"]; //支付结果异步通知

  [packageParams setObject: [dictobjectForKey:@"orderNo"]     forKey:@"out_trade_no"];//商户订单号

  [packageParams setObject:HTTP_spbill forKey:@"spbill_create_ip"];//发器支付的机器ip

  [packageParams setObject:@"1"   forKey:@"total_fee"];      //订单金额,单位为分

  

  NSString *parseParamsResult = [selfgenPackage:packageParams];

  NSData *postData = [parseParamsResultdataUsingEncoding:NSUTF8StringEncoding];

  [request setHTTPMethod:@"POST"];

  [request setHTTPBody:postData];

  //[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

  [NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuenew] completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError){

    dispatch_async(dispatch_get_main_queue(), ^{

      if (connectionError==nil) {

        //id dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        NSDictionary *dict = [NSDictionarydictionaryWithXMLData:data];

        //对数据库数据进行修改

        if ([[dictobjectForKey:@"return_code"]isEqualToString:@"SUCCESS"])

        {

          //刷新完成

          /*

           *生成订单信息及签名

           */

          PayReq *request = [[PayReqalloc] init];

          /** 商家向财付通申请的商家id */

          request.partnerId = [dictobjectForKey:@"mch_id"];

          /** 预支付订单 */

          request.prepayId= [dictobjectForKey:@"prepay_id"];

          /** 商家根据财付通文档填写的数据和签名 */

          request.package =@"Sign=WXPay";

          /** 随机串,防重发 */

          request.nonceStr= [dictobjectForKey:@"nonce_str"];

          /** 时间戳,防重发 */

          NSString* strtime = [[NSStringstringWithFormat:@"%f",[[NSDatedate] timeIntervalSince1970]*1000]substringWithRange:NSMakeRange(0,10)];

          request.timeStamp=[ strtimedoubleValue] ;

          /** 商家根据微信开放平台文档对数据做的签名 */

          NSMutableDictionary *packageParams= [[NSMutableDictionaryalloc] init];

          [packageParams setObject:WEIXIN_AppIDforKey:@"appid"];

          [packageParams setObject:request.partnerIdforKey:@"partnerid"];

          [packageParams setObject:request.prepayIdforKey:@"prepayid"];

          [packageParams setObject:request.packageforKey:@"package"];

          [packageParams setObject:request.nonceStrforKey:@"noncestr"];

          [packageParams setObject:strtimeforKey:@"timestamp"];

          //第二次签名

          request.sign=  [selfcreateMd5Sign:packageParams];//[dict objectForKey:@"sign"];

          /*! @brief发送请求到微信,等待微信返回onResp

           *

           * 函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。支持以下类型

           * SendAuthReqSendMessageToWXReqPayReq等。

           * @param req具体的发送请求,在调用函数后,请自己释放。

           * @return成功返回YES,失败返回NO

           */

          BOOL ret = [WXApisendReq:request];

          NSLog(@"%d",ret);

          

        }

        

      }

      else

      {

      }

    });

  }];

}





你可能感兴趣的:(ios微信支付 注意事项)