2017-04-05 11:49:06 qq_31901919 阅读数 2196

一. 第一步:下载微信SDK
包的内容如下:
这里写图片描述
二. 工程配置:

1.配置URL scheme
这里写图片描述

2.加入白名单
这里写图片描述

3.倒入必要的SDK
这里写图片描述

三. 代码:
好了,准备工作已经完成,下面开始写代码了
在AppDelegate里面:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.


        /**  微信  */

        WXApi.registerApp(WX_APPID, enableMTA: true)

        return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        WXApi.handleOpen(url, delegate: self)
        return true
    }

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

        WXApi.handleOpen(url, delegate: self)
        return true
}

/**  微信会调  */
func onResp(_ resp: BaseResp!) {
        if resp.errCode == 0 && resp.type == 0 {//授权成功
            let response = resp as! SendAuthResp
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WXLoginSuccessNotification"), object: response.code)
        }

}

在登录界面:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view,    typically from a nib.
    NotificationCenter.default.addObserver(self,selector: #selector(WXLoginSuccess(notification:)),name:   NSNotification.Name(rawValue: "WXLoginSuccessNotification"),object: nil)
}

//微信登录
@IBAction func wxLoginBtnAction(_ sender: UIButton) {
    let urlStr = "weixin://"
    if UIApplication.shared.canOpenURL(URL.init(string: urlStr)!) {
        let red = SendAuthReq.init()
        red.scope = "snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact"
        red.state = "\(arc4random()%100)"
        WXApi.send(red)
    }else{
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(URL.init(string: "http://weixin.qq.com/r/qUQVDfDEVK0rrbRu9xG7")!, options: [:], completionHandler: nil)
        } else {
            // Fallback on earlier versions
            UIApplication.shared.openURL(URL.init(string: "http://weixin.qq.com/r/qUQVDfDEVK0rrbRu9xG7")!)
        }
    }
}

/**  微信通知  */
func WXLoginSuccess(notification:Notification) {

    let code = notification.object as! String
    let requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(WX_APPID)&secret=\(WX_APPSecret)&code=\(code)&grant_type=authorization_code"

    DispatchQueue.global().async {

        let requestURL: URL = URL.init(string: requestUrl)!
        let data = try? Data.init(contentsOf: requestURL, options: Data.ReadingOptions())

        DispatchQueue.main.async {
            let jsonResult = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,Any>
            let openid: String = jsonResult["openid"] as! String
            let access_token: String = jsonResult["access_token"] as! String
            self.getUserInfo(openid: openid, access_token: access_token)
        }
    }
}

/**  获取用户信息  */
func getUserInfo(openid:String,access_token:String) {
    let requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=\(access_token)&openid=\(openid)"

    DispatchQueue.global().async {

        let requestURL: URL = URL.init(string: requestUrl)!
        let data = try? Data.init(contentsOf: requestURL, options: Data.ReadingOptions())

        DispatchQueue.main.async {
            let jsonResult = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,Any>
            print(jsonResult)

        }
    }
}

好了,微信用户信息我们已经拿到了,下面只需要把这些信息发送给后台想怎么登就怎么登,哈哈哈!

2015-03-13 10:58:43 songjie_13120695139 阅读数 0

向微信注册appid,成功后

1.在工程Plist文件中添加一个 URL type  "URL scheme”为你所注册的应用程序id,既AppID

导入libWeChatSDK.a WXApi.h , WXApiObject.h 三个文件

在程序登录那个函数注册

WXApi.registerApp("")括号内为id号

2.设置代理,遵守协议(转到微信)

func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {

        return WXApi.handleOpenURL(url, delegate: delegate)

    }

    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {

        return WXApi.handleOpenURL(url, delegate: delegate)

    }

3.写要分享内容

    func shareInfo(sceneCode:Int32){

 var sendMag = SendMessageToWXReq()

        sendMag.scene =  sceneCode


分享是文本类型

//        var str = extendMoney.text?.lastPathComponent

//        NSLog("str = \(str)")

//        sendMag.bText = true

//        var appStr = "\n\napp下载链接" + "\n苹果版:" + self.appleUrl + "\n安卓版:" + self.andridUrl

//        sendMag.text = "发放金额:" + self.extendMoney.text! + "\n分成类别:" + self.extendType.text! + appStr

分享是多媒体

        sendMag.bText = false

        var message = WXMediaMessage()

        message.setThumbImage(UIImage(named: "icon.png"))

        var sendOb = WXWebpageObject()// 分享其他类型内容,只是把WXWebpageObject(链接) 换成WXImageObject(图片)、WXMusicObject(音乐)、WXVideoObject(视频)……等  

        sendOb.webpageUrl = "http://baidu.com"

        message.mediaObject = sendOb

        sendMag.message = message

         WXApi.sendReq(sendMag)

    }

4.分享成功后回调函数

func onResp(resp: BaseResp!){

一般为一些提示信息(alertview)

NSLog(@"%@",resp);      

NSLog(@"errStr %@",[resp errStr]);     

NSLog(@"errCode %d",[resp errCode]); (0.成功)     

NSLog(@"type %d",[resp type]); 



}



2016-10-08 22:06:37 sbt0198 阅读数 0

转自:http://www.myexception.cn/swift/1991018.html

前言

Swift 语言,怎么说呢,有一种先接受后排斥,又欢迎的感觉,纵观国外大牛开源框架或项目演示,Swift几乎占据了多半,而国内虽然出现很多相关技术介绍和教程,但是在真正项目开发中使用的占据很少部分,原因一是目前熟练它的开发者并不多,二是版本不太稳定,还需要更成熟可靠的版本支持,但总之未来还是很有前景的,深有体会,不管是代码量还是编译效率,以及语言特性,现代性都优于Object-C,估计后续会被苹果作为官方开发语言,值得期待。

走起

鉴于此,笔者将之前用Object-C写的SSO授权登录:微信,QQ和微博,重新用Swift语言写一遍,以便需要的朋友参考,算是SSO授权登录的姊妹篇;

一、总体架构

1、引入第三方库

除了必须引入对应的登录SDK外,额外引入了SDWebImage,SVProgressHUD,看名字大家都明白吧,引入登录SDK请各自看官方的开发文档,需要加入什么系统库文件,需要配置Other Linker Flags 等,请参考各自官方文档即可;

2、配置连接桥文件

因为创建的工程是基于Swift语言,目前官方SDK和其它三方库都是用OC写的,所以为了在swift中调用oc代码,需要配置连接桥文件Bridging-Header.h,搜索objective-C bridging Header健,然后在值里面输入XXXLogin/Bridging-Header.h,注意是绝对路径,里面可以输入需要调用的头文件,如

#import "WXApi.h"
#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"

3、配置工程

因为是SSO跳转方式,需要配置URL Schemes,以便程序返回识别宿主程序,配置方法很简单,参考各自文档即可,在info里面可以可视化添加,各自的key值采用官方demo所提供;

二、微信

1、注册

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    //向微信注册
    WXApi.registerApp(kWXAPP_ID)

    return true
}

2、授权登录

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"onRecviceWX_CODE_Notification:", name: "WX_CODE", object: nil)

    let sendBtn:UIButton = UIButton()
    sendBtn.frame = CGRectMake(30, 100, kIPHONE_WIDTH-60, 40)
    sendBtn.backgroundColor = UIColor.redColor()
    sendBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
    sendBtn.setTitle("Swift版本之微信授权登录", forState: UIControlState.Normal)
    sendBtn.addTarget(self, action: "sendBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(sendBtn)


    headerImg = UIImageView(frame: CGRectMake(30, 160, 120, 120))
    headerImg.backgroundColor = UIColor.yellowColor()
    self.view.addSubview(headerImg)

    nicknameLbl.frame = CGRectMake(170, 160, kIPHONE_WIDTH-60-140, 40)
    nicknameLbl.backgroundColor = UIColor.lightGrayColor()
    nicknameLbl.textColor = UIColor.purpleColor()
    nicknameLbl.textAlignment = NSTextAlignment.Center
    self.view.addSubview(nicknameLbl)
}


func sendBtnClick(sneder:UIButton){
    sendWXAuthRequest()
}

//微信登录 第一步
func sendWXAuthRequest(){
    let req : SendAuthReq = SendAuthReq()
    req.scope = "snsapi_userinfo,snsapi_base"
    WXApi .sendReq(req)
}

3、回调

func onResp(resp: BaseResp!) {
    /*
    ErrCode ERR_OK = 0(用户同意)
    ERR_AUTH_DENIED = -4(用户拒绝授权)
    ERR_USER_CANCEL = -2(用户取消)
    code    用户换取access_token的code,仅在ErrCode为0时有效
    state   第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendReq时传入,由微信终端回传,state字符串长度不能超过1K
    lang    微信客户端当前语言
    country 微信用户当前国家信息
    */
    // var aresp resp :SendAuthResp!
    var aresp = resp as! SendAuthResp
    //  var aresp1 = resp as? SendAuthResp

    if (aresp.errCode == 0)
    {
        println(aresp.code)
        //031076fd11ebfa5d32adf46b37c75aax
        var dic:Dictionary<String,String>=["code":aresp.code];
        let value = dic["code"]
        println("code:\(value)")

        NSNotificationCenter.defaultCenter().postNotificationName("WX_CODE", object: nil, userInfo: dic)
    }
}

4、获取用户信息

//微信回调通知,获取code 第二步
func onRecviceWX_CODE_Notification(notification:NSNotification){
    SVProgressHUD.showSuccessWithStatus("获取到code", duration: 1)
    var userinfoDic : Dictionary = notification.userInfo!
    let code: String = userinfoDic["code"] as! String
    print("Recevice Code: \(code)")
    self.getAccess_token(code)
}

//获取token 第三步
func getAccess_token(code :String){
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    var requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(kWXAPP_ID)&secret=\(kWXAPP_SECRET)&code=\(code)&grant_type=authorization_code"
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        var requestURL: NSURL = NSURL(string: requestUrl)!
        var data = NSData(contentsOfURL: requestURL, options: NSDataReadingOptions(), error: nil)
        dispatch_async(dispatch_get_main_queue(), {
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
            println("Recevice Token: \(jsonResult)")
            SVProgressHUD.showSuccessWithStatus("获取到Token和openid", duration: 1)
            let token: String = jsonResult["access_token"] as! String
            let openid: String = jsonResult["openid"] as! String
            self.getUserInfo(token, openid: openid)
        })
    })
}

//获取用户信息 第四步
func getUserInfo(token :String,openid:String){
    // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
    var requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=\(token)&openid=\(openid)"
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        var requestURL: NSURL = NSURL(string: requestUrl)!
        var data = NSData(contentsOfURL: requestURL, options: NSDataReadingOptions(), error: nil)
        dispatch_async(dispatch_get_main_queue(), {
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
            print("Recevice UserInfo: \(jsonResult)")
            /*
            Recevice UserInfo:
            {
            city = Chaoyang;
            country = CN;
            headimgurl = "http://wx.qlogo.cn/mmopen/FrdAUicrPIibcpGzxuD0kjfssQogj3icL8QTJQYUCLpgzSnvY6rJFGORreicPUiaPCzojwNlsXq4ibbc8e3gGFricWqJU5ia7ibicLVhfT/0";
            language = "zh_CN";
            nickname = "\U706b\U9505\U6599";
            openid = "oyAaTjkR8T6kcKWyA4VPYDa_Wy_w";
            privilege =     (
            );
            province = Beijing;
            sex = 1;
            unionid = "o1A_Bjg52MglJiEjhLmB8SyYfZIY";
            }
            */

            SVProgressHUD.showSuccessWithStatus("获取到用户信息", duration: 1)
            let headimgurl: String = jsonResult["headimgurl"] as! String
            let nickname: String = jsonResult["nickname"] as! String
            self.headerImg.sd_setImageWithURL(NSURL(string: headimgurl))
            self.nicknameLbl.text = nickname
        })
    })
}

5、跳转

//微信的跳转回调
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool    {
    return  WXApi.handleOpenURL(url, delegate: self)
}
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
    return  WXApi.handleOpenURL(url, delegate: self)
}

三、QQ

1、注册

func sendBtnClick(sneder:UIButton){
    sendQQAuthRequest()
}

//第一步  QQ登录
func sendQQAuthRequest(){
    tencentOAuth = TencentOAuth(appId: kQQAPP_ID, andDelegate: self)
    var permissions = [kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO]
    tencentOAuth.authorize(permissions, inSafari: false)
}

2、授权登录

如上

3、回调

//第二步 登录成功回调
func tencentDidLogin() {
    let accessToken = tencentOAuth.accessToken
    println("accessToken:\(accessToken)") //641B23508B62392C52D6DFADF67FAA9C
    getUserInfo()
}

//失败
func tencentDidNotLogin(cancelled: Bool) {
    println("登录失败了")
}

//无网络
func tencentDidNotNetWork() {
    println("没有网络")
}

4、获取用户信息

 //第三步 获取用户信息
func getUserInfo(){
    SVProgressHUD.showWithStatus("正在获取用户信息...")
    tencentOAuth.getUserInfo()
}


//第四步 在获取用户回调中获取用户信息
func getUserInfoResponse(response: APIResponse!) { 
    SVProgressHUD.dismissWithSuccess("获取用户信息成功", afterDelay: 1)
    var dic:Dictionary = response.jsonResponse
    println("dic:\(dic)")

    //        [is_lost: 0, figureurl: http://qzapp.qlogo.cn/qzapp/222222/C5527A2F775D9EA7C20317128FAC202B/30, vip: 0, is_yellow_year_vip: 0, province: 北京, ret: 0, is_yellow_vip: 0, figureurl_qq_1: http://q.qlogo.cn/qqapp/222222/C5527A2F775D9EA7C20317128FAC202B/40, yellow_vip_level: 0, level: 0, figureurl_1: http://qzapp.qlogo.cn/qzapp/222222/C5527A2F775D9EA7C20317128FAC202B/50, city: 海淀, figureurl_2: http://qzapp.qlogo.cn/qzapp/222222/C5527A2F775D9EA7C20317128FAC202B/100, nickname: 竹中雨滴, msg: , gender: 男, figureurl_qq_2: http://q.qlogo.cn/qqapp/222222/C5527A2F775D9EA7C20317128FAC202B/100]
    refeshUserInfo(dic)
}


//第五步 刷新用户界面
func refeshUserInfo(dic : NSDictionary){
    let headimgurl: String = dic["figureurl_qq_2"] as! String
    let nickname: String = dic["nickname"] as! String 
    self.headerImg.sd_setImageWithURL(NSURL(string: headimgurl))
    self.nicknameLbl.text = nickname
}

5、跳转

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    return TencentOAuth.HandleOpenURL(url)
}

func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
    return TencentOAuth.HandleOpenURL(url)
}

四、微博

1、注册

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    WeiboSDK.registerApp(kAppKey)

    return true
}

2、授权登录

func sendBtnClick(sneder:UIButton){
    sendSinaAuthRequest()
}

//第一步  微博登录
func sendSinaAuthRequest(){
    var request : WBAuthorizeRequest = WBAuthorizeRequest.request() as! WBAuthorizeRequest
    request.redirectURI = kRedirectURI
    request.scope = "all"
    request.userInfo = ["SSO_Key":"SSO_Value"]
    WeiboSDK.sendRequest(request)
}

3、回调

func didReceiveWeiboRequest(request: WBBaseRequest!) {

}

func didReceiveWeiboResponse(response: WBBaseResponse!) {
    if response.isKindOfClass(WBAuthorizeResponse){
        if (response.statusCode == WeiboSDKResponseStatusCode.Success) {
            var authorizeResponse : WBAuthorizeResponse = response as! WBAuthorizeResponse
            var userID = authorizeResponse.userID
            var accessToken = authorizeResponse.accessToken
            println("userID:\(userID)\naccessToken:\(accessToken)")
            var userInfo = response.userInfo as Dictionary
            NSNotificationCenter.defaultCenter().postNotificationName("SINA_CODE", object: nil, userInfo: userInfo)
        }
    }
}

4、获取用户信息

//第二步  通过通知得到登录后获取的用户信息
func onRecviceSINA_CODE_Notification(notification:NSNotification)
{
    SVProgressHUD.showSuccessWithStatus("获取到用户信息", duration: 1)

    var userinfoDic : Dictionary = notification.userInfo!

    println("userInfo:\(userinfoDic)")


    /*
    userID:2627289515
    accessToken:2.002BqnrCyY87OC80500cab28Ofqd3B
    userInfo:
    [uid: 2627289515, remind_in: 647057, scope: invitation_write, refresh_token: 2.002BqnrCyY87OC10f7877765yPietB,
    app: {
    logo = "http://ww1.sinaimg.cn/square/65745bf7jw1ea399us692j2028028glf.jpg";
    name = "SDK\U5fae\U535a\U5e94\U7528demo";
    }, 
    access_token: 2.002BqnrCyY87OC80500cab28Ofqd3B, expires_in: 647057
    ]

    */

    var userAppInfo: Dictionary<String,String> = userinfoDic["app"] as! Dictionary

    refeshUserInfo(userAppInfo)
}

//第三步 刷新用户界面
func refeshUserInfo(dic : NSDictionary){

    let headimgurl: String = dic["logo"] as! String
    let nickname: String = dic["name"] as! String

    self.headerImg.sd_setImageWithURL(NSURL(string: headimgurl))
    self.nicknameLbl.text = nickname
}

5、跳转

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    return WeiboSDK.handleOpenURL(url, delegate: self)
}

func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
    return WeiboSDK.handleOpenURL(url, delegate: self)
}

五、对比分析

1、demo情况

微博demo代码工整度完爆微信,QQ,看着很舒服,心情也不错;另外微博放在了github上面,适合pod管理,注释也极好,微信文档写的挺不错,QQ写的简直丧心病狂,需要极度耐心才能看明白,表示很无语,另外本三种方式授权登录的源代码有偿提供,如需可以邮件mmw05@163.com即可;

2、嵌入时间

微信算是很容易嵌入SDK,QQ也还可以,微博需要注意boundID有限制,微信的逻辑算是比较冗余繁琐,从授权到获取到用户信息需要很多接口,而QQ和微博可以直接从授权登陆回调中获取到,是比较便捷的,从上面代码可以看出来;

后记

从objective-C到Swift,苹果力求简约,但又不简单,现代化的语言,必然在性能各方面优于传统,只是需要时间和更多的考验,作为开发者,多一个选择,岂不更好!
附图:
这里写图片描述

2018-07-11 07:19:29 weixin_34318326 阅读数 1172

微信支付其实在日常的开发中是经常接触的,但是在H5跳转问题上有或多或少的坑本,其中最难解决的是支付完成后返回App,并且返回App后白屏的解决。本次使用的是Swift:WKWebview OC 和WebView同理

建议阅读时间:10mins


  • 问题分析

    正常的H5支付流程如下

    按照上面的支付流程会出现 App -> 微信 -> 支付 -> 点击 完成 -> safari访问redirect_url设置的URL,这种流程其实用户体验是有点糟糕的,我们期望是 App -> 微信 -> 支付 -> 点击 完成 -> App访问redirect_url设置的URL

    问题分析到上面已经非常明了了,无非就是拦截处理,下面讲讲具体的实施。

  • 问题分析

    根据上面的分析解决的思路应该非常的清晰

    拦截请求

    首先在decidePolicyFor 回调里拦截支付的请求拦截的字符串:https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb 如果包含了该链接做如下处理,isload变量是控制是否是第一次没有修改redirect_url参数的请求防止重复请求

      if urlString?.range(of: "https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb") != nil && !self.isload{
          if let mUrlStr = urlString{
              let array : Array = mUrlStr.components(separatedBy: "redirect_url=")
              self.redirect_url =  array[1]
              let rs = "\(WXH5SchemeURL)://".urlEncoded()
              let mNewUrl = array[0] + "redirect_url=\(rs)"
              let newURLS = URL(string: mNewUrl)
              var mRequest = URLRequest.init(url: newURLS!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
              mRequest.setValue("\(WXH5SchemeURL)://", forHTTPHeaderField: "Referer")
              webView.load(mRequest)
              self.isload = true
              decisionHandler(.cancel)
              return
          }
      }
      self.isload = false
      decisionHandler(.allow)
      }
    复制代码

    拦截weixin://wap/pay? 打开微信

      if urlString?.range(of: "weixin://wap/pay?") != nil{
          if let mUrlStr = urlString{
              let openWX = URL(string: mUrlStr)
              if (UIApplication.shared.canOpenURL(openWX!)){
                  if #available(iOS 10.0, *){
                      UIApplication.shared.open(openWX!, options: [UIApplicationOpenSettingsURLString:false], completionHandler: nil)
                  }else{
                      UIApplication.shared.openURL(openWX!)
                  }
              }
              decisionHandler(.cancel)
              return
          }
      }
    复制代码

    这一步的话没甚好介绍的就是拦截打开微信支付即可。

    在项目设置Scheme链接用于支付完后返回App

    具体操作如下图

    到这一步已经成功了一大半了,你会发现现在支付成功后能返回App了但是返回的时候webView是白屏。白屏其实就是网页没有任何请求导致的,接下来我们就要使用上步提前记录好后台给的redirect_url的url了。

    在AppDelegate里监听url.scheme的值

    在AppDelegate里监听url.scheme的值是否为我们之前设置好的xxxx.com 如果是xxxx.com 发起通知 通知webview加载提前记录好的redirect_url的url了

      if ([url.scheme rangeOfString:@"quanzidian.net"].length!=0) {
      	[NSNotificationCenter defaultCenter] postNotificationName:@"WX_H5_PAY" object:nil];
      	return YES;
      }
    复制代码

    在wkWebView接收通知

      NotificationCenter.default.addObserver(self, selector: #selector(goBackWhitWXPay), name: NSNotification.Name(rawValue: "WX_H5_PAY"), object: nil)
    复制代码

    重新刷新WKWebview

      @objc func goBackWhitWXPay(){
      	if !self.redirect_url.isEmpty{
          	self.request = URLRequest(url: URL(string: self.redirect_url)!)
          	redirect_url = ""
      	}
      }
    复制代码

    项目使用的oc/Swift 混编有些地方和你使用的语言不一致时请自行模仿做写。

    到这里微信H5支付所有的问题就完美解决了 唯一的坑就是在截取请求时,重写redirect_url时注意一定时授权的URL://的协议。

    更多详情请访问https://siterzzz.github.io

2015-04-24 20:22:41 linweicanpc2 阅读数 3483


1.到微信开放平台下载SDK包

2.讲SDK包添加到项目中,新建一个桥接文件BridgingHeader.h并设置好(Build Settings -> Swift Compiler - code Generation -> Objective-C Bridging Header
填入“BridgingHeader.h”),BridgingHeader.h 中 加入#import "WXApi.h"  #import "WXApiObject.h"

3.在工程中链接上:SystemConfiguration.framework,libz.dylib,libsqlite3.0.dylib,如果报以下错误,需另加一个libc++.dylib

Undefined symbols for architecture i386:
  "operator delete[](void*)", referenced from:
      +[WeChatApiUtil EncodeBase64:] in libWeChatSDK.a(WeChatApiUtil.o)

4.如果报以下错误
<unknown>:0: error: /project/test/ocproject/sdk/WeChatSDK_1.4.3/WXApiObject.h:302: expected a type

将WXApiObject.h中

-(void) setThumbImage:(UIImage *)image;

改为

-(void) setThumbImage:(NSObject *)image;


5.环境配置完成,可以开始使用SDK进行开发了

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
      
        var appID:String = "wxd930ea5d5a258f4f"
        WXApi.registerApp(appID)
        
        return true
    }


func application(application: UIApplication!, openURL url: NSURL!, sourceApplication: String!, annotation: AnyObject!) -> Bool
    {
        return WXApi.handleOpenURL(url, delegate:mainViewController)
    }



ps:分享图片时,缩略图不能超过30K。