salesforce 和微信的集成(一)通过SFDC Site打开微信开发接口

        本文代码参照柳峰的代码。十分感谢。

        开始在做微信集成的时候,是采用微信+阿里云服务器+SFDC这种模式进行的。在阿里云上部署java程序实现和微信服务器的沟通,在通过SFDC的对外API实现和java程序的沟通。这种方式使项目成本提升,并且大多数客户难以接受。

       后来在论坛和qq群里,看大家的讨论,发现可以采用REST API来实现。在我的传统观念里REST API需要使用SeessionID和token的。使用site功能,就相当于把借口直接暴露出来,省去了Oath认证的步骤,一般在做接口测试的时候会这么做。(Site这个功能,在有的org里没有,需要申请,这部分内容我不打了解。不过我申请的免费开发org里有这个功能)

      闲言不多说。

     1、在SFDC上创建Site,设置如图。

2、点击保存按钮进入到如图的页面(下次进来的时候,要先edit,然后保存,才能再次来到这个页面)


在标示为1的地方设计Site访问的class,和profile的设置方法类似。标记为2的地方不可以添加任何的页面,否则程序出现问题。

3、新建一个类代码如下

@RestResource(urlMapping='/CoreService/*')
global with sharing class ApexRESTCycleExample {
    @HttpGet
     global static void doGet(){
        // 微信加密签名  
        String signature=RestContext.request.params.get('signature');        
        // 时间戳  
        String timestamp=RestContext.request.params.get('timestamp');    
        // 随机数  
        String nonce=RestContext.request.params.get('nonce');       
        // 随机字符串  
        String echostr=RestContext.request.params.get('echostr'); 
        system.debug(signature+'====='+timestamp+'====='+nonce+'====');
        String endstr= '';
        if(checkSignature(signature,timestamp,nonce)){
          
            RestContext.response.addHeader('Content-Type', 'text/plain');
        	RestContext.response.responseBody = Blob.valueOf(echostr);
           
        }
   } 
    public static boolean checkSignature(String signature, String timestamp, String nonce) {  
            String[] arr = new String[] { 'weixin', timestamp, nonce };  
            // 将token、timestamp、nonce三个参数进行字典序排序  
           // Arrays.sort(arr);  
            arr.sort();
            String content = '';  
            for (Integer i = 0; i < arr.size(); i++) {  
                content += arr[i];  
            }
            Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(content));
            String hexDigest = EncodingUtil.convertToHex(hash);
            String singUpperCase = hexDigest.toUpperCase();
            System.debug(singUpperCase +'===============');   
          
            // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信  
            Boolean flag = singUpperCase != null ? singUpperCase .equals(signature.toUpperCase()) : false;
            system.debug(flag + '==============');
            return flag;  
            
            
     }  
    
}

该段代码参考 柳峰的博客编写。

4、测试程序如图。注意:必须以https的形式访问,否则失败

5、设置微信中的接口

   复制上面的link到微信里,就可以成功打开了。


问题总结:1、我在写的时候,由于不知道可以直接调用API返回数据,绕了很多的弯路。

                     2、要以https的方式请求。

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值